CKEditorTest.php 20.6 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\ckeditor\Tests\CKEditorTest.
6 7 8 9
 */

namespace Drupal\ckeditor\Tests;

10
use Drupal\simpletest\KernelTestBase;
11 12
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\editor\Entity\Editor;
13 14 15

/**
 * Tests for the 'CKEditor' text editor plugin.
16 17
 *
 * @group ckeditor
18
 */
19
class CKEditorTest extends KernelTestBase {
20 21 22 23 24 25

  /**
   * Modules to enable.
   *
   * @var array
   */
26
  public static $modules = array('system', 'user', 'filter', 'editor', 'ckeditor', 'filter_test');
27 28 29 30

  /**
   * An instance of the "CKEditor" text editor plugin.
   *
31
   * @var \Drupal\ckeditor\Plugin\Editor\CKEditor;
32 33 34
   */
  protected $ckeditor;

35 36 37 38 39 40 41
  /**
   * The Editor Plugin Manager.
   *
   * @var \Drupal\editor\Plugin\EditorManager;
   */
  protected $manager;

42
  protected function setUp() {
43 44 45 46 47 48 49 50 51 52 53 54 55
    parent::setUp();

    // Install the Filter module.
    $this->installSchema('system', 'url_alias');

    // Create text format, associate CKEditor.
    $filtered_html_format = entity_create('filter_format', array(
      'format' => 'filtered_html',
      'name' => 'Filtered HTML',
      'weight' => 0,
      'filters' => array(
        'filter_html' => array(
          'status' => 1,
56
          'settings' => array(
57
            'allowed_html' => '<h2 id> <h3> <h4> <h5> <h6> <p> <br> <strong> <a href hreflang>',
58
          )
59 60 61 62 63 64 65 66 67 68 69
        ),
      ),
    ));
    $filtered_html_format->save();
    $editor = entity_create('editor', array(
      'format' => 'filtered_html',
      'editor' => 'ckeditor',
    ));
    $editor->save();

    // Create "CKEditor" text editor plugin instance.
70
    $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor');
71 72 73 74 75 76 77 78 79 80
  }

  /**
   * Tests CKEditor::getJSSettings().
   */
  function testGetJSSettings() {
    $editor = entity_load('editor', 'filtered_html');

    // Default toolbar.
    $expected_config = $this->getDefaultInternalConfig() + array(
81 82 83 84
      'drupalImage_dialogTitleAdd' => 'Insert Image',
      'drupalImage_dialogTitleEdit' => 'Edit Image',
      'drupalLink_dialogTitleAdd' => 'Add Link',
      'drupalLink_dialogTitleEdit' => 'Edit Link',
85
      'allowedContent' => $this->getDefaultAllowedContentConfig(),
86
      'disallowedContent' => $this->getDefaultDisallowedContentConfig(),
87 88
      'toolbar' => $this->getDefaultToolbarConfig(),
      'contentsCss' => $this->getDefaultContentsCssConfig(),
89
      'extraPlugins' => 'drupalimage,drupallink',
90
      'language' => 'en',
91
      'stylesSet' => FALSE,
92 93 94 95
      'drupalExternalPlugins' => array(
        'drupalimage' => file_create_url('core/modules/ckeditor/js/plugins/drupalimage/plugin.js'),
        'drupallink' => file_create_url('core/modules/ckeditor/js/plugins/drupallink/plugin.js'),
      ),
96
    );
97
    $expected_config = $this->castSafeStrings($expected_config);
98
    ksort($expected_config);
99
    ksort($expected_config['allowedContent']);
100
    $this->assertIdentical($expected_config, $this->castSafeStrings($this->ckeditor->getJSSettings($editor)), 'Generated JS settings are correct for default configuration.');
101 102 103 104

    // Customize the configuration: add button, have two contextually enabled
    // buttons, and configure a CKEditor plugin setting.
    $this->enableModules(array('ckeditor_test'));
105 106
    $this->container->get('plugin.manager.editor')->clearCachedDefinitions();
    $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor');
107
    $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions();
108 109 110 111
    $settings = $editor->getSettings();
    $settings['toolbar']['rows'][0][0]['items'][] = 'Strike';
    $settings['toolbar']['rows'][0][0]['items'][] = 'Format';
    $editor->setSettings($settings);
112
    $editor->save();
113 114
    $expected_config['toolbar'][0]['items'][] = 'Strike';
    $expected_config['toolbar'][0]['items'][] = 'Format';
115
    $expected_config['format_tags'] = 'p;h2;h3;h4;h5;h6';
116
    $expected_config['extraPlugins'] .= ',llama_contextual,llama_contextual_and_button';
117 118 119
    $expected_config['drupalExternalPlugins']['llama_contextual'] = file_create_url('core/modules/ckeditor/tests/modules/js/llama_contextual.js');
    $expected_config['drupalExternalPlugins']['llama_contextual_and_button'] = file_create_url('core/modules/ckeditor/tests/modules/js/llama_contextual_and_button.js');
    $expected_config['contentsCss'][] = file_create_url('core/modules/ckeditor/tests/modules/ckeditor_test.css');
120
    ksort($expected_config);
121
    $this->assertIdentical($expected_config, $this->castSafeStrings($this->ckeditor->getJSSettings($editor)), 'Generated JS settings are correct for customized configuration.');
122

123 124
    // Change the allowed HTML tags; the "allowedContent" and "format_tags"
    // settings for CKEditor should automatically be updated as well.
125
    $format = $editor->getFilterFormat();
126
    $format->filters('filter_html')->settings['allowed_html'] .= '<pre class> <h1> <blockquote class="*"> <address class="foo bar-* *">';
127
    $format->save();
128

129
    $expected_config['allowedContent']['pre'] = array('attributes' => 'class', 'styles' => FALSE, 'classes' => TRUE);
130
    $expected_config['allowedContent']['h1'] = array('attributes' => FALSE, 'styles' => FALSE, 'classes' => FALSE);
131 132
    $expected_config['allowedContent']['blockquote'] = array('attributes' => 'class', 'styles' => FALSE, 'classes' => TRUE);
    $expected_config['allowedContent']['address'] = array('attributes' => 'class', 'styles' => FALSE, 'classes' => 'foo,bar-*');
133 134
    $expected_config['format_tags'] = 'p;h1;h2;h3;h4;h5;h6;pre';
    ksort($expected_config['allowedContent']);
135
    $this->assertIdentical($expected_config, $this->castSafeStrings($this->ckeditor->getJSSettings($editor)), 'Generated JS settings are correct for customized configuration.');
136 137 138 139

    // Disable the filter_html filter: allow *all *tags.
    $format->setFilterConfig('filter_html', array('status' => 0));
    $format->save();
140

141
    $expected_config['allowedContent'] = TRUE;
142
    $expected_config['disallowedContent'] = FALSE;
143
    $expected_config['format_tags'] = 'p;h1;h2;h3;h4;h5;h6;pre';
144
    $this->assertIdentical($expected_config, $this->castSafeStrings($this->ckeditor->getJSSettings($editor)), 'Generated JS settings are correct for customized configuration.');
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162

    // Enable the filter_test_restrict_tags_and_attributes filter.
    $format->setFilterConfig('filter_test_restrict_tags_and_attributes', array(
      'status' => 1,
      'settings' => array(
        'restrictions' => array(
          'allowed' => array(
            'p' => TRUE,
            'a' => array(
              'href' => TRUE,
              'rel' => array('nofollow' => TRUE),
              'class' => array('external' => TRUE),
              'target' => array('_blank' => FALSE),
            ),
            'span' => array(
              'class' => array('dodo' => FALSE),
              'property' => array('dc:*' => TRUE),
              'rel' => array('foaf:*' => FALSE),
163
              'style' => array('underline' => FALSE, 'color' => FALSE, 'font-size' => TRUE),
164 165 166
            ),
            '*' => array(
              'style' => FALSE,
167
              'on*' => FALSE,
168 169 170 171
              'class' => array('is-a-hipster-llama' => TRUE, 'and-more' => TRUE),
              'data-*' => TRUE,
            ),
            'del' => FALSE,
172
          ),
173 174 175 176
        ),
      ),
    ));
    $format->save();
177

178 179 180 181 182 183 184 185
    $expected_config['allowedContent'] = array(
      'p' => array(
        'attributes' => TRUE,
        'styles' => FALSE,
        'classes' => 'is-a-hipster-llama,and-more',
      ),
      'a' => array(
        'attributes' => 'href,rel,class,target',
186
        'styles' => FALSE,
187 188 189
        'classes' => 'external',
      ),
      'span' => array(
190 191
        'attributes' => 'class,property,rel,style',
        'styles' => 'font-size',
192
        'classes' => FALSE,
193 194 195
      ),
      '*' => array(
        'attributes' => 'class,data-*',
196
        'styles' => FALSE,
197 198 199 200 201 202 203 204
        'classes' => 'is-a-hipster-llama,and-more',
      ),
      'del' => array(
        'attributes' => FALSE,
        'styles' => FALSE,
        'classes' => FALSE,
      ),
    );
205 206 207 208 209 210 211 212 213
    $expected_config['disallowedContent'] = array(
      'span' => array(
        'styles' => 'underline,color',
        'classes' => 'dodo',
      ),
      '*' => array(
        'attributes' => 'on*',
      ),
    );
214 215
    $expected_config['format_tags'] = 'p';
    ksort($expected_config);
216 217
    ksort($expected_config['allowedContent']);
    ksort($expected_config['disallowedContent']);
218
    $this->assertIdentical($expected_config, $this->castSafeStrings($this->ckeditor->getJSSettings($editor)), 'Generated JS settings are correct for customized configuration.');
219 220 221 222 223 224 225 226 227 228
  }

  /**
   * Tests CKEditor::buildToolbarJSSetting().
   */
  function testBuildToolbarJSSetting() {
    $editor = entity_load('editor', 'filtered_html');

    // Default toolbar.
    $expected = $this->getDefaultToolbarConfig();
229
    $this->assertIdentical($expected, $this->castSafeStrings($this->ckeditor->buildToolbarJSSetting($editor)), '"toolbar" configuration part of JS settings built correctly for default toolbar.');
230 231

    // Customize the configuration.
232 233 234
    $settings = $editor->getSettings();
    $settings['toolbar']['rows'][0][0]['items'][] = 'Strike';
    $editor->setSettings($settings);
235
    $editor->save();
236
    $expected[0]['items'][] = 'Strike';
237
    $this->assertIdentical($expected, $this->castSafeStrings($this->ckeditor->buildToolbarJSSetting($editor)), '"toolbar" configuration part of JS settings built correctly for customized toolbar.');
238 239 240

    // Enable the editor_test module, customize further.
    $this->enableModules(array('ckeditor_test'));
241
    $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions();
242
    // Override the label of a toolbar component.
243 244 245
    $settings['toolbar']['rows'][0][0]['name'] = 'JunkScience';
    $settings['toolbar']['rows'][0][0]['items'][] = 'Llama';
    $editor->setSettings($settings);
246
    $editor->save();
247 248
    $expected[0]['name'] = 'JunkScience';
    $expected[0]['items'][] = 'Llama';
249
    $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.');
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
  }

  /**
   * Tests CKEditor::buildContentsCssJSSetting().
   */
  function testBuildContentsCssJSSetting() {
    $editor = entity_load('editor', 'filtered_html');

    // 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().
    $this->enableModules(array('ckeditor_test'));
    $expected[] = file_create_url('core/modules/ckeditor/tests/modules/ckeditor_test.css');
    $this->assertIdentical($expected, $this->ckeditor->buildContentsCssJSSetting($editor), '"contentsCss" configuration part of JS settings built correctly while a hook_ckeditor_css_alter() implementation exists.');

267 268
    // Enable the Bartik theme, which specifies a CKEditor stylesheet.
    \Drupal::service('theme_handler')->install(['bartik']);
269
    $this->config('system.theme')->set('default', 'bartik')->save();
270 271 272
    $expected[] = file_create_url('core/themes/bartik/css/base/elements.css');
    $expected[] = file_create_url('core/themes/bartik/css/components/captions.css');
    $expected[] = file_create_url('core/themes/bartik/css/components/table.css');
273
    $expected[] = file_create_url('core/themes/bartik/css/components/text-formatted.css');
274
    $this->assertIdentical($expected, $this->ckeditor->buildContentsCssJSSetting($editor), '"contentsCss" configuration part of JS settings built correctly while a theme providing a CKEditor stylesheet exists.');
275 276 277 278 279 280 281
  }

  /**
   * Tests Internal::getConfig().
   */
  function testInternalGetConfig() {
    $editor = entity_load('editor', 'filtered_html');
282
    $internal_plugin = $this->container->get('plugin.manager.ckeditor.plugin')->createInstance('internal');
283 284 285

    // Default toolbar.
    $expected = $this->getDefaultInternalConfig();
286
    $expected['disallowedContent'] = $this->getDefaultDisallowedContentConfig();
287
    $expected['allowedContent'] = $this->getDefaultAllowedContentConfig();
288
    $this->assertEqual($expected, $internal_plugin->getConfig($editor), '"Internal" plugin configuration built correctly for default toolbar.');
289 290

    // Format dropdown/button enabled: new setting should be present.
291 292 293
    $settings = $editor->getSettings();
    $settings['toolbar']['rows'][0][0]['items'][] = 'Format';
    $editor->setSettings($settings);
294
    $expected['format_tags'] = 'p;h2;h3;h4;h5;h6';
295
    $this->assertEqual($expected, $internal_plugin->getConfig($editor), '"Internal" plugin configuration built correctly for customized toolbar.');
296 297 298 299 300 301 302
  }

  /**
   * Tests StylesCombo::getConfig().
   */
  function testStylesComboGetConfig() {
    $editor = entity_load('editor', 'filtered_html');
303
    $stylescombo_plugin = $this->container->get('plugin.manager.ckeditor.plugin')->createInstance('stylescombo');
304 305

    // Styles dropdown/button enabled: new setting should be present.
306 307 308 309
    $settings = $editor->getSettings();
    $settings['toolbar']['rows'][0][0]['items'][] = 'Styles';
    $settings['plugins']['stylescombo']['styles'] = '';
    $editor->setSettings($settings);
310 311 312 313 314 315
    $editor->save();
    $expected['stylesSet'] = array();
    $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.
316 317
    $settings['plugins']['stylescombo']['styles'] = "   \n";
    $editor->setSettings($settings);
318 319
    $editor->save();
    $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor));
320 321
    $settings['plugins']['stylescombo']['styles'] = "\r\n  \n  \r  \n ";
    $editor->setSettings($settings);
322 323 324 325
    $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.
326 327
    $settings['plugins']['stylescombo']['styles'] = "h1.title|Title\np.mAgical.Callout|Callout";
    $editor->setSettings($settings);
328 329 330 331 332 333 334 335 336
    $editor->save();
    $expected['stylesSet'] = array(
      array('name' => 'Title', 'element' => 'h1', 'attributes' => array('class' => 'title')),
      array('name' => 'Callout', 'element' => 'p', 'attributes' => array('class' => 'mAgical Callout')),
    );
    $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.
337 338
    $settings['plugins']['stylescombo']['styles'] = "  h1 .title   |  Title \r \n\r  \np.mAgical  .Callout|Callout\r";
    $editor->setSettings($settings);
339 340 341
    $editor->save();
    $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');

342
    // Slightly different configuration: class names are optional.
343 344
    $settings['plugins']['stylescombo']['styles'] = "      h1 |  Title ";
    $editor->setSettings($settings);
345 346 347 348
    $editor->save();
    $expected['stylesSet'] = array(array('name' => 'Title', 'element' => 'h1'));
    $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');

349
    // Invalid syntax should cause stylesSet to be set to FALSE.
350 351
    $settings['plugins']['stylescombo']['styles'] = "h1";
    $editor->setSettings($settings);
352 353 354 355 356
    $editor->save();
    $expected['stylesSet'] = FALSE;
    $this->assertIdentical($expected, $stylescombo_plugin->getConfig($editor), '"StylesCombo" plugin configuration built correctly for customized toolbar.');
  }

357 358 359 360 361 362
  /**
   * Tests language list availability in CKEditor.
   */
  function testLanguages() {
    // Get CKEditor supported language codes and spot-check.
    $this->enableModules(array('language'));
363
    $this->installConfig(array('language'));
364 365 366 367 368 369 370 371 372 373 374 375
    $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');
376 377 378 379

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

382 383 384 385
  /**
   * Tests that CKEditor plugins participate in JS translation.
   */
  function testJSTranslation() {
386
    $this->enableModules(array('language', 'locale'));
387 388
    $this->installSchema('locale', 'locales_source');
    $this->installSchema('locale', 'locales_location');
389 390
    $this->installSchema('locale', 'locales_target');
    $editor = Editor::load('filtered_html');
391 392
    $this->ckeditor->getJSSettings($editor);
    $localeStorage = $this->container->get('locale.storage');
393
    $string = $localeStorage->findString(array('source' => 'Edit Link', 'context' => ''));
394
    $this->assertTrue(!empty($string), 'String from JavaScript file saved.');
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409

    // 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();
410
    $this->config('system.site')->set('default_langcode', 'fr')->save();
411 412 413 414 415 416 417 418 419 420

    // 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);
421 422
  }

423 424 425 426 427
  protected function getDefaultInternalConfig() {
    return array(
      'customConfig' => '',
      'pasteFromWordPromptCleanup' => TRUE,
      'resize_dir' => 'vertical',
428
      'justifyClasses' => array('text-align-left', 'text-align-center', 'text-align-right', 'text-align-justify'),
429
      'entities' => FALSE,
430 431 432
    );
  }

433
  protected function getDefaultAllowedContentConfig() {
434 435 436 437 438 439 440 441 442 443 444 445
    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],
    ];
446 447
  }

448 449 450 451 452 453
  protected function getDefaultDisallowedContentConfig() {
    return array(
      '*' => array('attributes' => 'on*'),
    );
  }

454 455
  protected function getDefaultToolbarConfig() {
    return array(
456
      array(
457
        'name' => 'Formatting',
458 459 460
        'items' => array('Bold', 'Italic',),
      ),
      array(
461
        'name' => 'Links',
462 463 464
        'items' => array('DrupalLink', 'DrupalUnlink',),
      ),
      array(
465
        'name' => 'Lists',
466 467 468
        'items' => array('BulletedList', 'NumberedList',),
      ),
      array(
469
        'name' => 'Media',
470 471 472
        'items' => array('Blockquote', 'DrupalImage',),
      ),
      array(
473
        'name' => 'Tools',
474 475 476
        'items' => array('Source',),
      ),
      '/',
477 478 479 480 481 482
    );
  }

  protected function getDefaultContentsCssConfig() {
    return array(
      file_create_url('core/modules/ckeditor/css/ckeditor-iframe.css'),
483
      file_create_url('core/modules/system/css/components/align.module.css'),
484 485 486 487
    );
  }

}