db backup prior to drupal security update
[yaffs-website] / web / core / modules / ckeditor / tests / modules / src / Kernel / CKEditorTest.php
1 <?php
2
3 namespace Drupal\Tests\ckeditor\Kernel;
4
5 use Drupal\KernelTests\KernelTestBase;
6 use Drupal\language\Entity\ConfigurableLanguage;
7 use Drupal\editor\Entity\Editor;
8 use Drupal\filter\Entity\FilterFormat;
9
10 /**
11  * Tests for the 'CKEditor' text editor plugin.
12  *
13  * @group ckeditor
14  */
15 class CKEditorTest extends KernelTestBase {
16
17   /**
18    * Modules to enable.
19    *
20    * @var array
21    */
22   public static $modules = ['system', 'user', 'filter', 'editor', 'ckeditor', 'filter_test'];
23
24   /**
25    * An instance of the "CKEditor" text editor plugin.
26    *
27    * @var \Drupal\ckeditor\Plugin\Editor\CKEditor;
28    */
29   protected $ckeditor;
30
31   /**
32    * The Editor Plugin Manager.
33    *
34    * @var \Drupal\editor\Plugin\EditorManager;
35    */
36   protected $manager;
37
38   protected function setUp() {
39     parent::setUp();
40
41     // Install the Filter module.
42
43     // Create text format, associate CKEditor.
44     $filtered_html_format = FilterFormat::create([
45       'format' => 'filtered_html',
46       'name' => 'Filtered HTML',
47       'weight' => 0,
48       'filters' => [
49         'filter_html' => [
50           'status' => 1,
51           'settings' => [
52             'allowed_html' => '<h2 id> <h3> <h4> <h5> <h6> <p> <br> <strong> <a href hreflang>',
53           ]
54         ],
55       ],
56     ]);
57     $filtered_html_format->save();
58     $editor = Editor::create([
59       'format' => 'filtered_html',
60       'editor' => 'ckeditor',
61     ]);
62     $editor->save();
63
64     // Create "CKEditor" text editor plugin instance.
65     $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor');
66   }
67
68   /**
69    * Tests CKEditor::getJSSettings().
70    */
71   public function testGetJSSettings() {
72     $editor = Editor::load('filtered_html');
73
74     // Default toolbar.
75     $expected_config = $this->getDefaultInternalConfig() + [
76       'drupalImage_dialogTitleAdd' => 'Insert Image',
77       'drupalImage_dialogTitleEdit' => 'Edit Image',
78       'drupalLink_dialogTitleAdd' => 'Add Link',
79       'drupalLink_dialogTitleEdit' => 'Edit Link',
80       'allowedContent' => $this->getDefaultAllowedContentConfig(),
81       'disallowedContent' => $this->getDefaultDisallowedContentConfig(),
82       'toolbar' => $this->getDefaultToolbarConfig(),
83       'contentsCss' => $this->getDefaultContentsCssConfig(),
84       'extraPlugins' => 'drupalimage,drupallink',
85       'language' => 'en',
86       'stylesSet' => FALSE,
87       'drupalExternalPlugins' => [
88         'drupalimage' => file_url_transform_relative(file_create_url('core/modules/ckeditor/js/plugins/drupalimage/plugin.js')),
89         'drupallink' => file_url_transform_relative(file_create_url('core/modules/ckeditor/js/plugins/drupallink/plugin.js')),
90       ],
91     ];
92     $expected_config = $this->castSafeStrings($expected_config);
93     ksort($expected_config);
94     ksort($expected_config['allowedContent']);
95     $this->assertIdentical($expected_config, $this->castSafeStrings($this->ckeditor->getJSSettings($editor)), 'Generated JS settings are correct for default configuration.');
96
97     // Customize the configuration: add button, have two contextually enabled
98     // buttons, and configure a CKEditor plugin setting.
99     $this->enableModules(['ckeditor_test']);
100     $this->container->get('plugin.manager.editor')->clearCachedDefinitions();
101     $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor');
102     $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions();
103     $settings = $editor->getSettings();
104     $settings['toolbar']['rows'][0][0]['items'][] = 'Strike';
105     $settings['toolbar']['rows'][0][0]['items'][] = 'Format';
106     $editor->setSettings($settings);
107     $editor->save();
108     $expected_config['toolbar'][0]['items'][] = 'Strike';
109     $expected_config['toolbar'][0]['items'][] = 'Format';
110     $expected_config['format_tags'] = 'p;h2;h3;h4;h5;h6';
111     $expected_config['extraPlugins'] .= ',llama_contextual,llama_contextual_and_button';
112     $expected_config['drupalExternalPlugins']['llama_contextual'] = file_url_transform_relative(file_create_url('core/modules/ckeditor/tests/modules/js/llama_contextual.js'));
113     $expected_config['drupalExternalPlugins']['llama_contextual_and_button'] = file_url_transform_relative(file_create_url('core/modules/ckeditor/tests/modules/js/llama_contextual_and_button.js'));
114     $expected_config['contentsCss'][] = file_url_transform_relative(file_create_url('core/modules/ckeditor/tests/modules/ckeditor_test.css'));
115     ksort($expected_config);
116     $this->assertIdentical($expected_config, $this->castSafeStrings($this->ckeditor->getJSSettings($editor)), 'Generated JS settings are correct for customized configuration.');
117
118     // Change the allowed HTML tags; the "allowedContent" and "format_tags"
119     // settings for CKEditor should automatically be updated as well.
120     $format = $editor->getFilterFormat();
121     $format->filters('filter_html')->settings['allowed_html'] .= '<pre class> <h1> <blockquote class="*"> <address class="foo bar-* *">';
122     $format->save();
123
124     $expected_config['allowedContent']['pre'] = ['attributes' => 'class', 'styles' => FALSE, 'classes' => TRUE];
125     $expected_config['allowedContent']['h1'] = ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE];
126     $expected_config['allowedContent']['blockquote'] = ['attributes' => 'class', 'styles' => FALSE, 'classes' => TRUE];
127     $expected_config['allowedContent']['address'] = ['attributes' => 'class', 'styles' => FALSE, 'classes' => 'foo,bar-*'];
128     $expected_config['format_tags'] = 'p;h1;h2;h3;h4;h5;h6;pre';
129     ksort($expected_config['allowedContent']);
130     $this->assertIdentical($expected_config, $this->castSafeStrings($this->ckeditor->getJSSettings($editor)), 'Generated JS settings are correct for customized configuration.');
131
132     // Disable the filter_html filter: allow *all *tags.
133     $format->setFilterConfig('filter_html', ['status' => 0]);
134     $format->save();
135
136     $expected_config['allowedContent'] = TRUE;
137     $expected_config['disallowedContent'] = FALSE;
138     $expected_config['format_tags'] = 'p;h1;h2;h3;h4;h5;h6;pre';
139     $this->assertIdentical($expected_config, $this->castSafeStrings($this->ckeditor->getJSSettings($editor)), 'Generated JS settings are correct for customized configuration.');
140
141     // Enable the filter_test_restrict_tags_and_attributes filter.
142     $format->setFilterConfig('filter_test_restrict_tags_and_attributes', [
143       'status' => 1,
144       'settings' => [
145         'restrictions' => [
146           'allowed' => [
147             'p' => TRUE,
148             'a' => [
149               'href' => TRUE,
150               'rel' => ['nofollow' => TRUE],
151               'class' => ['external' => TRUE],
152               'target' => ['_blank' => FALSE],
153             ],
154             'span' => [
155               'class' => ['dodo' => FALSE],
156               'property' => ['dc:*' => TRUE],
157               'rel' => ['foaf:*' => FALSE],
158               'style' => ['underline' => FALSE, 'color' => FALSE, 'font-size' => TRUE],
159             ],
160             '*' => [
161               'style' => FALSE,
162               'on*' => FALSE,
163               'class' => ['is-a-hipster-llama' => TRUE, 'and-more' => TRUE],
164               'data-*' => TRUE,
165             ],
166             'del' => FALSE,
167           ],
168         ],
169       ],
170     ]);
171     $format->save();
172
173     $expected_config['allowedContent'] = [
174       'p' => [
175         'attributes' => TRUE,
176         'styles' => FALSE,
177         'classes' => 'is-a-hipster-llama,and-more',
178       ],
179       'a' => [
180         'attributes' => 'href,rel,class,target',
181         'styles' => FALSE,
182         'classes' => 'external',
183       ],
184       'span' => [
185         'attributes' => 'class,property,rel,style',
186         'styles' => 'font-size',
187         'classes' => FALSE,
188       ],
189       '*' => [
190         'attributes' => 'class,data-*',
191         'styles' => FALSE,
192         'classes' => 'is-a-hipster-llama,and-more',
193       ],
194       'del' => [
195         'attributes' => FALSE,
196         'styles' => FALSE,
197         'classes' => FALSE,
198       ],
199     ];
200     $expected_config['disallowedContent'] = [
201       'span' => [
202         'styles' => 'underline,color',
203         'classes' => 'dodo',
204       ],
205       '*' => [
206         'attributes' => 'on*',
207       ],
208     ];
209     $expected_config['format_tags'] = 'p';
210     ksort($expected_config);
211     ksort($expected_config['allowedContent']);
212     ksort($expected_config['disallowedContent']);
213     $this->assertIdentical($expected_config, $this->castSafeStrings($this->ckeditor->getJSSettings($editor)), 'Generated JS settings are correct for customized configuration.');
214   }
215
216   /**
217    * Tests CKEditor::buildToolbarJSSetting().
218    */
219   public function testBuildToolbarJSSetting() {
220     $editor = Editor::load('filtered_html');
221
222     // Default toolbar.
223     $expected = $this->getDefaultToolbarConfig();
224     $this->assertIdentical($expected, $this->castSafeStrings($this->ckeditor->buildToolbarJSSetting($editor)), '"toolbar" configuration part of JS settings built correctly for default toolbar.');
225
226     // Customize the configuration.
227     $settings = $editor->getSettings();
228     $settings['toolbar']['rows'][0][0]['items'][] = 'Strike';
229     $editor->setSettings($settings);
230     $editor->save();
231     $expected[0]['items'][] = 'Strike';
232     $this->assertIdentical($expected, $this->castSafeStrings($this->ckeditor->buildToolbarJSSetting($editor)), '"toolbar" configuration part of JS settings built correctly for customized toolbar.');
233
234     // Enable the editor_test module, customize further.
235     $this->enableModules(['ckeditor_test']);
236     $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions();
237     // Override the label of a toolbar component.
238     $settings['toolbar']['rows'][0][0]['name'] = 'JunkScience';
239     $settings['toolbar']['rows'][0][0]['items'][] = 'Llama';
240     $editor->setSettings($settings);
241     $editor->save();
242     $expected[0]['name'] = 'JunkScience';
243     $expected[0]['items'][] = 'Llama';
244     $this->assertIdentical($expected, $this->castSafeStrings($this->ckeditor->buildToolbarJSSetting($editor)), '"toolbar" configuration part of JS settings built correctly for customized toolbar with contrib module-provided CKEditor plugin.');
245   }
246
247   /**
248    * Tests CKEditor::buildContentsCssJSSetting().
249    */
250   public function testBuildContentsCssJSSetting() {
251     $editor = Editor::load('filtered_html');
252
253     // Default toolbar.
254     $expected = $this->getDefaultContentsCssConfig();
255     $this->assertIdentical($expected, $this->ckeditor->buildContentsCssJSSetting($editor), '"contentsCss" configuration part of JS settings built correctly for default toolbar.');
256
257     // Enable the editor_test module, which implements hook_ckeditor_css_alter().
258     $this->enableModules(['ckeditor_test']);
259     $expected[] = file_url_transform_relative(file_create_url(drupal_get_path('module', 'ckeditor_test') . '/ckeditor_test.css'));
260     $this->assertIdentical($expected, $this->ckeditor->buildContentsCssJSSetting($editor), '"contentsCss" configuration part of JS settings built correctly while a hook_ckeditor_css_alter() implementation exists.');
261
262     // Enable LlamaCss plugin, which adds an additional CKEditor stylesheet.
263     $this->container->get('plugin.manager.editor')->clearCachedDefinitions();
264     $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor');
265     $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions();
266     $settings = $editor->getSettings();
267     // LlamaCss: automatically enabled by adding its 'LlamaCSS' button.
268     $settings['toolbar']['rows'][0][0]['items'][] = 'LlamaCSS';
269     $editor->setSettings($settings);
270     $editor->save();
271     $expected[] = file_url_transform_relative(file_create_url(drupal_get_path('module', 'ckeditor_test') . '/css/llama.css'));
272     $this->assertIdentical($expected, $this->ckeditor->buildContentsCssJSSetting($editor), '"contentsCss" configuration part of JS settings built correctly while a CKEditorPluginInterface implementation exists.');
273
274     // Enable the Bartik theme, which specifies a CKEditor stylesheet.
275     \Drupal::service('theme_handler')->install(['bartik']);
276     $this->config('system.theme')->set('default', 'bartik')->save();
277     $expected[] = file_url_transform_relative(file_create_url('core/themes/bartik/css/base/elements.css'));
278     $expected[] = file_url_transform_relative(file_create_url('core/themes/bartik/css/components/captions.css'));
279     $expected[] = file_url_transform_relative(file_create_url('core/themes/bartik/css/components/table.css'));
280     $expected[] = file_url_transform_relative(file_create_url('core/themes/bartik/css/components/text-formatted.css'));
281     $this->assertIdentical($expected, $this->ckeditor->buildContentsCssJSSetting($editor), '"contentsCss" configuration part of JS settings built correctly while a theme providing a CKEditor stylesheet exists.');
282   }
283
284   /**
285    * Tests Internal::getConfig().
286    */
287   public function testInternalGetConfig() {
288     $editor = Editor::load('filtered_html');
289     $internal_plugin = $this->container->get('plugin.manager.ckeditor.plugin')->createInstance('internal');
290
291     // Default toolbar.
292     $expected = $this->getDefaultInternalConfig();
293     $expected['disallowedContent'] = $this->getDefaultDisallowedContentConfig();
294     $expected['allowedContent'] = $this->getDefaultAllowedContentConfig();
295     $this->assertEqual($expected, $internal_plugin->getConfig($editor), '"Internal" plugin configuration built correctly for default toolbar.');
296
297     // Format dropdown/button enabled: new setting should be present.
298     $settings = $editor->getSettings();
299     $settings['toolbar']['rows'][0][0]['items'][] = 'Format';
300     $editor->setSettings($settings);
301     $expected['format_tags'] = 'p;h2;h3;h4;h5;h6';
302     $this->assertEqual($expected, $internal_plugin->getConfig($editor), '"Internal" plugin configuration built correctly for customized toolbar.');
303   }
304
305   /**
306    * Tests StylesCombo::getConfig().
307    */
308   public function testStylesComboGetConfig() {
309     $editor = Editor::load('filtered_html');
310     $stylescombo_plugin = $this->container->get('plugin.manager.ckeditor.plugin')->createInstance('stylescombo');
311
312     // Styles dropdown/button enabled: new setting should be present.
313     $settings = $editor->getSettings();
314     $settings['toolbar']['rows'][0][0]['items'][] = 'Styles';
315     $settings['plugins']['stylescombo']['styles'] = '';
316     $editor->setSettings($settings);
317     $editor->save();
318     $expected['stylesSet'] = [];
319     $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');
320
321     // Configure the optional "styles" setting in odd ways that shouldn't affect
322     // the end result.
323     $settings['plugins']['stylescombo']['styles'] = "   \n";
324     $editor->setSettings($settings);
325     $editor->save();
326     $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor));
327     $settings['plugins']['stylescombo']['styles'] = "\r\n  \n  \r  \n ";
328     $editor->setSettings($settings);
329     $editor->save();
330     $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');
331
332     // Now configure it properly, the end result should change.
333     $settings['plugins']['stylescombo']['styles'] = "h1.title|Title\np.mAgical.Callout|Callout";
334     $editor->setSettings($settings);
335     $editor->save();
336     $expected['stylesSet'] = [
337       ['name' => 'Title', 'element' => 'h1', 'attributes' => ['class' => 'title']],
338       ['name' => 'Callout', 'element' => 'p', 'attributes' => ['class' => 'mAgical Callout']],
339     ];
340     $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');
341
342     // Same configuration, but now interspersed with nonsense. Should yield the
343     // same result.
344     $settings['plugins']['stylescombo']['styles'] = "  h1 .title   |  Title \r \n\r  \np.mAgical  .Callout|Callout\r";
345     $editor->setSettings($settings);
346     $editor->save();
347     $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');
348
349     // Slightly different configuration: class names are optional.
350     $settings['plugins']['stylescombo']['styles'] = "      h1 |  Title ";
351     $editor->setSettings($settings);
352     $editor->save();
353     $expected['stylesSet'] = [['name' => 'Title', 'element' => 'h1']];
354     $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');
355
356     // Invalid syntax should cause stylesSet to be set to FALSE.
357     $settings['plugins']['stylescombo']['styles'] = "h1";
358     $editor->setSettings($settings);
359     $editor->save();
360     $expected['stylesSet'] = FALSE;
361     $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');
362   }
363
364   /**
365    * Tests language list availability in CKEditor.
366    */
367   public function testLanguages() {
368     // Get CKEditor supported language codes and spot-check.
369     $this->enableModules(['language']);
370     $this->installConfig(['language']);
371     $langcodes = $this->ckeditor->getLangcodes();
372
373     // Language codes transformed with browser mappings.
374     $this->assertTrue($langcodes['pt-pt'] == 'pt', '"pt" properly resolved');
375     $this->assertTrue($langcodes['zh-hans'] == 'zh-cn', '"zh-hans" properly resolved');
376
377     // Language code both in Drupal and CKEditor.
378     $this->assertTrue($langcodes['gl'] == 'gl', '"gl" properly resolved');
379
380     // Language codes only in CKEditor.
381     $this->assertTrue($langcodes['en-au'] == 'en-au', '"en-au" properly resolved');
382     $this->assertTrue($langcodes['sr-latn'] == 'sr-latn', '"sr-latn" properly resolved');
383
384     // No locale module, so even though languages are enabled, CKEditor should
385     // still be in English.
386     $this->assertCKEditorLanguage('en');
387   }
388
389   /**
390    * Tests that CKEditor plugins participate in JS translation.
391    */
392   public function testJSTranslation() {
393     $this->enableModules(['language', 'locale']);
394     $this->installSchema('locale', 'locales_source');
395     $this->installSchema('locale', 'locales_location');
396     $this->installSchema('locale', 'locales_target');
397     $editor = Editor::load('filtered_html');
398     $this->ckeditor->getJSSettings($editor);
399     $localeStorage = $this->container->get('locale.storage');
400     $string = $localeStorage->findString(['source' => 'Edit Link', 'context' => '']);
401     $this->assertTrue(!empty($string), 'String from JavaScript file saved.');
402
403     // With locale module, CKEditor should not adhere to the language selected.
404     $this->assertCKEditorLanguage();
405   }
406
407   /**
408    * Assert that CKEditor picks the expected language when French is default.
409    *
410    * @param string $langcode
411    *   Language code to assert for. Defaults to French. That is the default
412    *   language set in this assertion.
413    */
414   protected function assertCKEditorLanguage($langcode = 'fr') {
415     // Set French as the site default language.
416     ConfigurableLanguage::createFromLangcode('fr')->save();
417     $this->config('system.site')->set('default_langcode', 'fr')->save();
418
419     // Reset the language manager so new negotiations attempts will fall back on
420     // French. Reinject the language manager CKEditor to use the current one.
421     $this->container->get('language_manager')->reset();
422     $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor');
423
424     // Test that we now get the expected language.
425     $editor = Editor::load('filtered_html');
426     $settings = $this->ckeditor->getJSSettings($editor);
427     $this->assertEqual($settings['language'], $langcode);
428   }
429
430   protected function getDefaultInternalConfig() {
431     return [
432       'customConfig' => '',
433       'pasteFromWordPromptCleanup' => TRUE,
434       'resize_dir' => 'vertical',
435       'justifyClasses' => ['text-align-left', 'text-align-center', 'text-align-right', 'text-align-justify'],
436       'entities' => FALSE,
437       'disableNativeSpellChecker' => FALSE,
438     ];
439   }
440
441   protected function getDefaultAllowedContentConfig() {
442     return [
443       'h2' => ['attributes' => 'id', 'styles' => FALSE, 'classes' => FALSE],
444       'h3' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
445       'h4' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
446       'h5' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
447       'h6' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
448       'p' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
449       'br' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
450       'strong' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
451       'a' => ['attributes' => 'href,hreflang', 'styles' => FALSE, 'classes' => FALSE],
452       '*' => ['attributes' => 'lang,dir', 'styles' => FALSE, 'classes' => FALSE],
453     ];
454   }
455
456   protected function getDefaultDisallowedContentConfig() {
457     return [
458       '*' => ['attributes' => 'on*'],
459     ];
460   }
461
462   protected function getDefaultToolbarConfig() {
463     return [
464       [
465         'name' => 'Formatting',
466         'items' => ['Bold', 'Italic'],
467       ],
468       [
469         'name' => 'Links',
470         'items' => ['DrupalLink', 'DrupalUnlink'],
471       ],
472       [
473         'name' => 'Lists',
474         'items' => ['BulletedList', 'NumberedList'],
475       ],
476       [
477         'name' => 'Media',
478         'items' => ['Blockquote', 'DrupalImage'],
479       ],
480       [
481         'name' => 'Tools',
482         'items' => ['Source', ],
483       ],
484       '/',
485     ];
486   }
487
488   protected function getDefaultContentsCssConfig() {
489     return [
490       file_url_transform_relative(file_create_url('core/modules/ckeditor/css/ckeditor-iframe.css')),
491       file_url_transform_relative(file_create_url('core/modules/system/css/components/align.module.css')),
492     ];
493   }
494
495 }