CKEditorTest.php 20.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
<?php

/**
 * @file
 * Definition of \Drupal\ckeditor\Tests\CKEditorTest.
 */

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
57
58
          'settings' => array(
            'allowed_html' => '<h4> <h5> <h6> <p> <br> <strong> <a>',
          )
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
    ksort($expected_config);
98
99
100
101
102
    $this->assertIdentical($expected_config, $this->ckeditor->getJSSettings($editor), 'Generated JS settings are correct for default configuration.');

    // Customize the configuration: add button, have two contextually enabled
    // buttons, and configure a CKEditor plugin setting.
    $this->enableModules(array('ckeditor_test'));
103
104
    $this->container->get('plugin.manager.editor')->clearCachedDefinitions();
    $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor');
105
    $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions();
106
107
108
    // KernelTestBase::enableModules() unfortunately doesn't invoke
    // hook_rebuild() just like a "real" Drupal site would. Do it manually.
    \Drupal::moduleHandler()->invoke('ckeditor', 'rebuild');
109
110
111
112
    $settings = $editor->getSettings();
    $settings['toolbar']['rows'][0][0]['items'][] = 'Strike';
    $settings['toolbar']['rows'][0][0]['items'][] = 'Format';
    $editor->setSettings($settings);
113
    $editor->save();
114
115
    $expected_config['toolbar'][0]['items'][] = 'Strike';
    $expected_config['toolbar'][0]['items'][] = 'Format';
116
    $expected_config['format_tags'] = 'p;h4;h5;h6';
117
    $expected_config['extraPlugins'] .= ',llama_contextual,llama_contextual_and_button';
118
119
120
    $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');
121
122
    ksort($expected_config);
    $this->assertIdentical($expected_config, $this->ckeditor->getJSSettings($editor), 'Generated JS settings are correct for customized configuration.');
123

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

130
131
    $expected_config['allowedContent']['pre'] = array('attributes' => TRUE, 'styles' => FALSE, 'classes' => TRUE);
    $expected_config['allowedContent']['h3'] = array('attributes' => TRUE, 'styles' => FALSE, 'classes' => TRUE);
132
    $expected_config['format_tags'] = 'p;h3;h4;h5;h6;pre';
133
134
135
136
137
    $this->assertIdentical($expected_config, $this->ckeditor->getJSSettings($editor), 'Generated JS settings are correct for customized configuration.');

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

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

    // 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),
161
              'style' => array('underline' => FALSE, 'color' => FALSE, 'font-size' => TRUE),
162
163
164
            ),
            '*' => array(
              'style' => FALSE,
165
              'on*' => FALSE,
166
167
168
169
              'class' => array('is-a-hipster-llama' => TRUE, 'and-more' => TRUE),
              'data-*' => TRUE,
            ),
            'del' => FALSE,
170
          ),
171
172
173
174
        ),
      ),
    ));
    $format->save();
175

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

    // Assert that we're robust enough to withstand people messing with State
    // manually.
    \Drupal::state()->delete('ckeditor_internal_format_tags:' . $format->id());
    $this->assertIdentical($expected_config, $this->ckeditor->getJSSettings($editor), 'Even when somebody manually deleted the key-value pair in State with the pre-calculated format_tags setting, it returns "p" — because the <p> tag is always allowed.');
217
218
219
220
221
222
223
224
225
226
227
228
229
  }

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

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

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

    // Enable the editor_test module, customize further.
    $this->enableModules(array('ckeditor_test'));
239
    $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions();
240
    // Override the label of a toolbar component.
241
242
243
    $settings['toolbar']['rows'][0][0]['name'] = 'JunkScience';
    $settings['toolbar']['rows'][0][0]['items'][] = 'Llama';
    $editor->setSettings($settings);
244
    $editor->save();
245
246
    $expected[0]['name'] = 'JunkScience';
    $expected[0]['items'][] = 'Llama';
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
    $this->assertIdentical($expected, $this->ckeditor->buildToolbarJSSetting($editor), '"toolbar" configuration part of JS settings built correctly for customized toolbar with contrib module-provided CKEditor plugin.');
  }

  /**
   * 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.');

265
266
    // Enable the Bartik theme, which specifies a CKEditor stylesheet.
    \Drupal::service('theme_handler')->install(['bartik']);
267
    $this->config('system.theme')->set('default', 'bartik')->save();
268
269
270
271
272
273
    $expected[] = file_create_url('core/themes/bartik/css/base/elements.css');
    $expected[] = file_create_url('core/themes/bartik/css/base/typography.css');
    $expected[] = file_create_url('core/themes/bartik/css/components/captions.css');
    $expected[] = file_create_url('core/themes/bartik/css/components/content.css');
    $expected[] = file_create_url('core/themes/bartik/css/components/list.css');
    $expected[] = file_create_url('core/themes/bartik/css/components/table.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
289
290
    $this->assertIdentical($expected, $internal_plugin->getConfig($editor), '"Internal" plugin configuration built correctly for default toolbar.');

    // 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
295
296
297
298
299
300
301
302
    $expected['format_tags'] = 'p;h4;h5;h6';
    $this->assertIdentical($expected, $internal_plugin->getConfig($editor), '"Internal" plugin configuration built correctly for customized toolbar.');
  }

  /**
   * 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('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
434
435
436
437
438
439
440
441
442
443
444
  protected function getDefaultAllowedContentConfig() {
    return array(
      'h4' => array('attributes' => TRUE, 'styles' => FALSE, 'classes' => TRUE),
      'h5' => array('attributes' => TRUE, 'styles' => FALSE, 'classes' => TRUE),
      'h6' => array('attributes' => TRUE, 'styles' => FALSE, 'classes' => TRUE),
      'p' => array('attributes' => TRUE, 'styles' => FALSE, 'classes' => TRUE),
      'br' => array('attributes' => TRUE, 'styles' => FALSE, 'classes' => TRUE),
      'strong' => array('attributes' => TRUE, 'styles' => FALSE, 'classes' => TRUE),
      'a' => array('attributes' => TRUE, 'styles' => FALSE, 'classes' => TRUE),
    );
  }

445
446
447
448
449
450
  protected function getDefaultDisallowedContentConfig() {
    return array(
      '*' => array('attributes' => 'on*'),
    );
  }

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

  protected function getDefaultContentsCssConfig() {
    return array(
      file_create_url('core/modules/ckeditor/css/ckeditor-iframe.css'),
480
      file_create_url('core/modules/system/css/system.module.css'),
481
482
483
484
    );
  }

}