CKEditorTest.php 21.5 KB
Newer Older
1 2
<?php

3
namespace Drupal\Tests\ckeditor\Kernel;
4

5
use Drupal\KernelTests\KernelTestBase;
6 7
use Drupal\language\Entity\ConfigurableLanguage;
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 19 20 21

  /**
   * Modules to enable.
   *
   * @var array
   */
22
  public static $modules = ['system', 'user', 'filter', 'editor', 'ckeditor', 'filter_test'];
23 24 25 26

  /**
   * An instance of the "CKEditor" text editor plugin.
   *
27
   * @var \Drupal\ckeditor\Plugin\Editor\CKEditor
28 29 30
   */
  protected $ckeditor;

31 32 33 34 35 36 37
  /**
   * The Editor Plugin Manager.
   *
   * @var \Drupal\editor\Plugin\EditorManager;
   */
  protected $manager;

38
  protected function setUp() {
39 40 41 42 43
    parent::setUp();

    // Install the Filter module.

    // Create text format, associate CKEditor.
44
    $filtered_html_format = FilterFormat::create([
45 46 47
      'format' => 'filtered_html',
      'name' => 'Filtered HTML',
      'weight' => 0,
48 49
      'filters' => [
        '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 60
      'format' => 'filtered_html',
      'editor' => 'ckeditor',
61
    ]);
62 63 64
    $editor->save();

    // Create "CKEditor" text editor plugin instance.
65
    $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor');
66 67 68 69 70
  }

  /**
   * Tests CKEditor::getJSSettings().
   */
71
  public function testGetJSSettings() {
72
    $editor = Editor::load('filtered_html');
73 74

    // Default toolbar.
75
    $expected_config = $this->getDefaultInternalConfig() + [
76 77 78 79
      'drupalImage_dialogTitleAdd' => 'Insert Image',
      'drupalImage_dialogTitleEdit' => 'Edit Image',
      'drupalLink_dialogTitleAdd' => 'Add Link',
      'drupalLink_dialogTitleEdit' => 'Edit Link',
80
      'allowedContent' => $this->getDefaultAllowedContentConfig(),
81
      'disallowedContent' => $this->getDefaultDisallowedContentConfig(),
82 83
      'toolbar' => $this->getDefaultToolbarConfig(),
      'contentsCss' => $this->getDefaultContentsCssConfig(),
84
      'extraPlugins' => 'drupalimage,drupallink',
85
      'language' => 'en',
86
      'stylesSet' => FALSE,
87
      'drupalExternalPlugins' => [
88 89
        'drupalimage' => file_url_transform_relative(file_create_url('core/modules/ckeditor/js/plugins/drupalimage/plugin.js')),
        '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 98

    // Customize the configuration: add button, have two contextually enabled
    // buttons, and configure a CKEditor plugin setting.
99
    $this->enableModules(['ckeditor_test']);
100 101
    $this->container->get('plugin.manager.editor')->clearCachedDefinitions();
    $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor');
102
    $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions();
103 104 105 106
    $settings = $editor->getSettings();
    $settings['toolbar']['rows'][0][0]['items'][] = 'Strike';
    $settings['toolbar']['rows'][0][0]['items'][] = 'Format';
    $editor->setSettings($settings);
107
    $editor->save();
108 109
    $expected_config['toolbar'][0]['items'][] = 'Strike';
    $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 113 114
    $expected_config['drupalExternalPlugins']['llama_contextual'] = file_url_transform_relative(file_create_url('core/modules/ckeditor/tests/modules/js/llama_contextual.js'));
    $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'));
    $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 119
    // Change the allowed HTML tags; the "allowedContent" and "format_tags"
    // 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 125 126 127
    $expected_config['allowedContent']['pre'] = ['attributes' => 'class', 'styles' => FALSE, 'classes' => TRUE];
    $expected_config['allowedContent']['h1'] = ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE];
    $expected_config['allowedContent']['blockquote'] = ['attributes' => 'class', 'styles' => FALSE, 'classes' => TRUE];
    $expected_config['allowedContent']['address'] = ['attributes' => 'class', 'styles' => FALSE, 'classes' => 'foo,bar-*'];
128 129
    $expected_config['format_tags'] = 'p;h1;h2;h3;h4;h5;h6;pre';
    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 145 146
      'settings' => [
        'restrictions' => [
          'allowed' => [
147
            'p' => TRUE,
148
            'a' => [
149
              'href' => TRUE,
150 151 152 153 154 155 156 157 158 159 160
              'rel' => ['nofollow' => TRUE],
              'class' => ['external' => TRUE],
              'target' => ['_blank' => FALSE],
            ],
            'span' => [
              'class' => ['dodo' => FALSE],
              'property' => ['dc:*' => TRUE],
              'rel' => ['foaf:*' => FALSE],
              'style' => ['underline' => FALSE, 'color' => FALSE, 'font-size' => TRUE],
            ],
            '*' => [
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 174
    $expected_config['allowedContent'] = [
      'p' => [
175 176 177
        'attributes' => TRUE,
        'styles' => FALSE,
        '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 186
        'attributes' => 'class,property,rel,style',
        '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 196 197
        'attributes' => FALSE,
        'styles' => FALSE,
        'classes' => FALSE,
198 199 200 201
      ],
    ];
    $expected_config['disallowedContent'] = [
      'span' => [
202 203
        'styles' => 'underline,color',
        'classes' => 'dodo',
204 205
      ],
      '*' => [
206
        'attributes' => 'on*',
207 208
      ],
    ];
209 210
    $expected_config['format_tags'] = 'p';
    ksort($expected_config);
211 212
    ksort($expected_config['allowedContent']);
    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 218
  }

  /**
   * Tests CKEditor::buildToolbarJSSetting().
   */
219
  public function testBuildToolbarJSSetting() {
220
    $editor = Editor::load('filtered_html');
221 222 223

    // Default toolbar.
    $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 228 229
    $settings = $editor->getSettings();
    $settings['toolbar']['rows'][0][0]['items'][] = 'Strike';
    $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 239 240
    $settings['toolbar']['rows'][0][0]['name'] = 'JunkScience';
    $settings['toolbar']['rows'][0][0]['items'][] = 'Llama';
    $editor->setSettings($settings);
241
    $editor->save();
242 243
    $expected[0]['name'] = 'JunkScience';
    $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 249
  }

  /**
   * Tests CKEditor::buildContentsCssJSSetting().
   */
250
  public function testBuildContentsCssJSSetting() {
251
    $editor = Editor::load('filtered_html');
252 253 254 255 256 257

    // Default toolbar.
    $expected = $this->getDefaultContentsCssConfig();
    $this->assertIdentical($expected, $this->ckeditor->buildContentsCssJSSetting($editor), '"contentsCss" configuration part of JS settings built correctly for default toolbar.');

    // 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 261
    $this->assertIdentical($expected, $this->ckeditor->buildContentsCssJSSetting($editor), '"contentsCss" configuration part of JS settings built correctly while a hook_ckeditor_css_alter() implementation exists.');

262 263 264 265 266 267 268 269 270 271 272 273
    // Enable LlamaCss plugin, which adds an additional CKEditor stylesheet.
    $this->container->get('plugin.manager.editor')->clearCachedDefinitions();
    $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor');
    $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions();
    $settings = $editor->getSettings();
    // LlamaCss: automatically enabled by adding its 'LlamaCSS' button.
    $settings['toolbar']['rows'][0][0]['items'][] = 'LlamaCSS';
    $editor->setSettings($settings);
    $editor->save();
    $expected[] = file_url_transform_relative(file_create_url(drupal_get_path('module', 'ckeditor_test') . '/css/llama.css'));
    $this->assertIdentical($expected, $this->ckeditor->buildContentsCssJSSetting($editor), '"contentsCss" configuration part of JS settings built correctly while a CKEditorPluginInterface implementation exists.');

274 275
    // Enable the Bartik theme, which specifies a CKEditor stylesheet.
    \Drupal::service('theme_handler')->install(['bartik']);
276
    $this->config('system.theme')->set('default', 'bartik')->save();
277 278 279 280
    $expected[] = file_url_transform_relative(file_create_url('core/themes/bartik/css/base/elements.css'));
    $expected[] = file_url_transform_relative(file_create_url('core/themes/bartik/css/components/captions.css'));
    $expected[] = file_url_transform_relative(file_create_url('core/themes/bartik/css/components/table.css'));
    $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 286
  }

  /**
   * Tests Internal::getConfig().
   */
287
  public function testInternalGetConfig() {
288
    $editor = Editor::load('filtered_html');
289
    $internal_plugin = $this->container->get('plugin.manager.ckeditor.plugin')->createInstance('internal');
290 291 292

    // Default toolbar.
    $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 299 300
    $settings = $editor->getSettings();
    $settings['toolbar']['rows'][0][0]['items'][] = 'Format';
    $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 307
  }

  /**
   * Tests StylesCombo::getConfig().
   */
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 314 315 316
    $settings = $editor->getSettings();
    $settings['toolbar']['rows'][0][0]['items'][] = 'Styles';
    $settings['plugins']['stylescombo']['styles'] = '';
    $editor->setSettings($settings);
317
    $editor->save();
318
    $expected['stylesSet'] = [];
319 320 321 322
    $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');

    // Configure the optional "styles" setting in odd ways that shouldn't affect
    // the end result.
323 324
    $settings['plugins']['stylescombo']['styles'] = "   \n";
    $editor->setSettings($settings);
325 326
    $editor->save();
    $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor));
327 328
    $settings['plugins']['stylescombo']['styles'] = "\r\n  \n  \r  \n ";
    $editor->setSettings($settings);
329 330 331 332
    $editor->save();
    $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');

    // Now configure it properly, the end result should change.
333 334
    $settings['plugins']['stylescombo']['styles'] = "h1.title|Title\np.mAgical.Callout|Callout";
    $editor->setSettings($settings);
335
    $editor->save();
336 337 338 339
    $expected['stylesSet'] = [
      ['name' => 'Title', 'element' => 'h1', 'attributes' => ['class' => 'title']],
      ['name' => 'Callout', 'element' => 'p', 'attributes' => ['class' => 'mAgical Callout']],
    ];
340 341 342 343
    $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');

    // Same configuration, but now interspersed with nonsense. Should yield the
    // same result.
344 345
    $settings['plugins']['stylescombo']['styles'] = "  h1 .title   |  Title \r \n\r  \np.mAgical  .Callout|Callout\r";
    $editor->setSettings($settings);
346 347 348
    $editor->save();
    $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');

349
    // Slightly different configuration: class names are optional.
350 351
    $settings['plugins']['stylescombo']['styles'] = "      h1 |  Title ";
    $editor->setSettings($settings);
352
    $editor->save();
353
    $expected['stylesSet'] = [['name' => 'Title', 'element' => 'h1']];
354 355
    $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');

356
    // Invalid syntax should cause stylesSet to be set to FALSE.
357 358
    $settings['plugins']['stylescombo']['styles'] = "h1";
    $editor->setSettings($settings);
359 360 361 362 363
    $editor->save();
    $expected['stylesSet'] = FALSE;
    $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');
  }

364 365 366
  /**
   * Tests language list availability in CKEditor.
   */
367
  public function testLanguages() {
368
    // Get CKEditor supported language codes and spot-check.
369 370
    $this->enableModules(['language']);
    $this->installConfig(['language']);
371 372 373 374 375 376 377 378 379 380 381 382
    $langcodes = $this->ckeditor->getLangcodes();

    // Language codes transformed with browser mappings.
    $this->assertTrue($langcodes['pt-pt'] == 'pt', '"pt" properly resolved');
    $this->assertTrue($langcodes['zh-hans'] == 'zh-cn', '"zh-hans" properly resolved');

    // Language code both in Drupal and CKEditor.
    $this->assertTrue($langcodes['gl'] == 'gl', '"gl" properly resolved');

    // Language codes only in CKEditor.
    $this->assertTrue($langcodes['en-au'] == 'en-au', '"en-au" properly resolved');
    $this->assertTrue($langcodes['sr-latn'] == 'sr-latn', '"sr-latn" properly resolved');
383 384 385 386

    // No locale module, so even though languages are enabled, CKEditor should
    // still be in English.
    $this->assertCKEditorLanguage('en');
387 388
  }

389 390 391
  /**
   * Tests that CKEditor plugins participate in JS translation.
   */
392
  public function testJSTranslation() {
393
    $this->enableModules(['language', 'locale']);
394 395
    $this->installSchema('locale', 'locales_source');
    $this->installSchema('locale', 'locales_location');
396 397
    $this->installSchema('locale', 'locales_target');
    $editor = Editor::load('filtered_html');
398 399
    $this->ckeditor->getJSSettings($editor);
    $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 404 405 406 407 408 409 410 411 412 413 414 415 416

    // With locale module, CKEditor should not adhere to the language selected.
    $this->assertCKEditorLanguage();
  }

  /**
   * Assert that CKEditor picks the expected language when French is default.
   *
   * @param string $langcode
   *   Language code to assert for. Defaults to French. That is the default
   *   language set in this assertion.
   */
  protected function assertCKEditorLanguage($langcode = 'fr') {
    // Set French as the site default language.
    ConfigurableLanguage::createFromLangcode('fr')->save();
417
    $this->config('system.site')->set('default_langcode', 'fr')->save();
418 419 420 421 422 423 424 425 426 427

    // Reset the language manager so new negotiations attempts will fall back on
    // French. Reinject the language manager CKEditor to use the current one.
    $this->container->get('language_manager')->reset();
    $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor');

    // Test that we now get the expected language.
    $editor = Editor::load('filtered_html');
    $settings = $this->ckeditor->getJSSettings($editor);
    $this->assertEqual($settings['language'], $langcode);
428 429
  }

430
  protected function getDefaultInternalConfig() {
431
    return [
432 433 434
      'customConfig' => '',
      'pasteFromWordPromptCleanup' => TRUE,
      '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 443 444 445 446 447 448 449 450 451 452 453
    return [
      'h2' => ['attributes' => 'id', 'styles' => FALSE, 'classes' => FALSE],
      'h3' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
      'h4' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
      'h5' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
      'h6' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
      'p' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
      'br' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
      'strong' => ['attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE],
      'a' => ['attributes' => 'href,hreflang', 'styles' => FALSE, 'classes' => FALSE],
      '*' => ['attributes' => 'lang,dir', 'styles' => FALSE, 'classes' => FALSE],
    ];
454 455
  }

456
  protected function getDefaultDisallowedContentConfig() {
457 458 459
    return [
      '*' => ['attributes' => 'on*'],
    ];
460 461
  }

462
  protected function getDefaultToolbarConfig() {
463 464
    return [
      [
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 491
      file_url_transform_relative(file_create_url('core/modules/ckeditor/css/ckeditor-iframe.css')),
      file_url_transform_relative(file_create_url('core/modules/system/css/components/align.module.css')),
492
    ];
493 494 495
  }

}