Version 1
[yaffs-website] / web / core / modules / ckeditor / src / Plugin / CKEditorPlugin / Internal.php
1 <?php
2
3 namespace Drupal\ckeditor\Plugin\CKEditorPlugin;
4
5 use Drupal\ckeditor\CKEditorPluginBase;
6 use Drupal\ckeditor\CKEditorPluginContextualInterface;
7 use Drupal\ckeditor\CKEditorPluginManager;
8 use Drupal\Component\Utility\Html;
9 use Drupal\Core\Cache\Cache;
10 use Drupal\Core\Cache\CacheBackendInterface;
11 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
12 use Drupal\editor\Entity\Editor;
13 use Drupal\filter\Plugin\FilterInterface;
14 use Symfony\Component\DependencyInjection\ContainerInterface;
15
16 /**
17  * Defines the "internal" plugin (i.e. core plugins part of our CKEditor build).
18  *
19  * @CKEditorPlugin(
20  *   id = "internal",
21  *   label = @Translation("CKEditor core")
22  * )
23  */
24 class Internal extends CKEditorPluginBase implements ContainerFactoryPluginInterface, CKEditorPluginContextualInterface {
25
26   /**
27    * The cache backend.
28    *
29    * @var \Drupal\Core\Cache\CacheBackendInterface
30    */
31   protected $cache;
32
33   /**
34    * Constructs a \Drupal\ckeditor\Plugin\CKEditorPlugin\Internal object.
35    *
36    * @param array $configuration
37    *   A configuration array containing information about the plugin instance.
38    * @param string $plugin_id
39    *   The plugin_id for the plugin instance.
40    * @param mixed $plugin_definition
41    *   The plugin implementation definition.
42    * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
43    *   The cache backend.
44    */
45   public function __construct(array $configuration, $plugin_id, $plugin_definition, CacheBackendInterface $cache_backend) {
46     $this->cache = $cache_backend;
47     parent::__construct($configuration, $plugin_id, $plugin_definition);
48   }
49
50   /**
51    * Creates an instance of the plugin.
52    *
53    * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
54    *   The container to pull out services used in the plugin.
55    * @param array $configuration
56    *   A configuration array containing information about the plugin instance.
57    * @param string $plugin_id
58    *   The plugin ID for the plugin instance.
59    * @param mixed $plugin_definition
60    *   The plugin implementation definition.
61    *
62    * @return static
63    *   Returns an instance of this plugin.
64    */
65   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
66     return new static(
67       $configuration,
68       $plugin_id,
69       $plugin_definition,
70       $container->get('cache.default')
71     );
72   }
73
74   /**
75    * {@inheritdoc}
76    */
77   public function isInternal() {
78     return TRUE;
79   }
80
81   /**
82    * {@inheritdoc}
83    */
84   public function isEnabled(Editor $editor) {
85     // This plugin represents the core CKEditor plugins. They're always enabled:
86     // its configuration is always necessary.
87     return TRUE;
88   }
89
90   /**
91    * {@inheritdoc}
92    */
93   public function getFile() {
94     // This plugin is already part of Drupal core's CKEditor build.
95     return FALSE;
96   }
97
98   /**
99    * {@inheritdoc}
100    */
101   public function getConfig(Editor $editor) {
102     // Reasonable defaults that provide expected basic behavior.
103     $config = [
104       'customConfig' => '', // Don't load CKEditor's config.js file.
105       'pasteFromWordPromptCleanup' => TRUE,
106       'resize_dir' => 'vertical',
107       'justifyClasses' => ['text-align-left', 'text-align-center', 'text-align-right', 'text-align-justify'],
108       'entities' => FALSE,
109       'disableNativeSpellChecker' => FALSE,
110     ];
111
112     // Add the allowedContent setting, which ensures CKEditor only allows tags
113     // and attributes that are allowed by the text format for this text editor.
114     list($config['allowedContent'], $config['disallowedContent']) = $this->generateACFSettings($editor);
115
116     // Add the format_tags setting, if its button is enabled.
117     $toolbar_buttons = CKEditorPluginManager::getEnabledButtons($editor);
118     if (in_array('Format', $toolbar_buttons)) {
119       $config['format_tags'] = $this->generateFormatTagsSetting($editor);
120     }
121
122     return $config;
123   }
124
125   /**
126    * {@inheritdoc}
127    */
128   public function getButtons() {
129     $button = function($name, $direction = 'ltr') {
130       // In the markup below, we mostly use the name (which may include spaces),
131       // but in one spot we use it as a CSS class, so strip spaces.
132       // Note: this uses str_replace() instead of Html::cleanCssIdentifier()
133       // because we must provide these class names exactly how CKEditor expects
134       // them in its library, which cleanCssIdentifier() does not do.
135       $class_name = str_replace(' ', '', $name);
136       return [
137         '#type' => 'inline_template',
138         '#template' => '<a href="#" class="cke-icon-only cke_{{ direction }}" role="button" title="{{ name }}" aria-label="{{ name }}"><span class="cke_button_icon cke_button__{{ classname }}_icon">{{ name }}</span></a>',
139         '#context' => [
140           'direction' => $direction,
141           'name' => $name,
142           'classname' => $class_name,
143         ],
144       ];
145     };
146
147     return [
148       // "basicstyles" plugin.
149       'Bold' => [
150         'label' => $this->t('Bold'),
151         'image_alternative' => $button('bold'),
152         'image_alternative_rtl' => $button('bold', 'rtl'),
153       ],
154       'Italic' => [
155         'label' => $this->t('Italic'),
156         'image_alternative' => $button('italic'),
157         'image_alternative_rtl' => $button('italic', 'rtl'),
158       ],
159       'Underline' => [
160         'label' => $this->t('Underline'),
161         'image_alternative' => $button('underline'),
162         'image_alternative_rtl' => $button('underline', 'rtl'),
163       ],
164       'Strike' => [
165         'label' => $this->t('Strike-through'),
166         'image_alternative' => $button('strike'),
167         'image_alternative_rtl' => $button('strike', 'rtl'),
168       ],
169       'Superscript' => [
170         'label' => $this->t('Superscript'),
171         'image_alternative' => $button('super script'),
172         'image_alternative_rtl' => $button('super script', 'rtl'),
173       ],
174       'Subscript' => [
175         'label' => $this->t('Subscript'),
176         'image_alternative' => $button('sub script'),
177         'image_alternative_rtl' => $button('sub script', 'rtl'),
178       ],
179       // "removeformat" plugin.
180       'RemoveFormat' => [
181         'label' => $this->t('Remove format'),
182         'image_alternative' => $button('remove format'),
183         'image_alternative_rtl' => $button('remove format', 'rtl'),
184       ],
185       // "justify" plugin.
186       'JustifyLeft' => [
187         'label' => $this->t('Align left'),
188         'image_alternative' => $button('justify left'),
189         'image_alternative_rtl' => $button('justify left', 'rtl'),
190       ],
191       'JustifyCenter' => [
192         'label' => $this->t('Align center'),
193         'image_alternative' => $button('justify center'),
194         'image_alternative_rtl' => $button('justify center', 'rtl'),
195       ],
196       'JustifyRight' => [
197         'label' => $this->t('Align right'),
198         'image_alternative' => $button('justify right'),
199         'image_alternative_rtl' => $button('justify right', 'rtl'),
200       ],
201       'JustifyBlock' => [
202         'label' => $this->t('Justify'),
203         'image_alternative' => $button('justify block'),
204         'image_alternative_rtl' => $button('justify block', 'rtl'),
205       ],
206       // "list" plugin.
207       'BulletedList' => [
208         'label' => $this->t('Bullet list'),
209         'image_alternative' => $button('bulleted list'),
210         'image_alternative_rtl' => $button('bulleted list', 'rtl'),
211       ],
212       'NumberedList' => [
213         'label' => $this->t('Numbered list'),
214         'image_alternative' => $button('numbered list'),
215         'image_alternative_rtl' => $button('numbered list', 'rtl'),
216       ],
217       // "indent" plugin.
218       'Outdent' => [
219         'label' => $this->t('Outdent'),
220         'image_alternative' => $button('outdent'),
221         'image_alternative_rtl' => $button('outdent', 'rtl'),
222       ],
223       'Indent' => [
224         'label' => $this->t('Indent'),
225         'image_alternative' => $button('indent'),
226         'image_alternative_rtl' => $button('indent', 'rtl'),
227       ],
228       // "undo" plugin.
229       'Undo' => [
230         'label' => $this->t('Undo'),
231         'image_alternative' => $button('undo'),
232         'image_alternative_rtl' => $button('undo', 'rtl'),
233       ],
234       'Redo' => [
235         'label' => $this->t('Redo'),
236         'image_alternative' => $button('redo'),
237         'image_alternative_rtl' => $button('redo', 'rtl'),
238       ],
239       // "blockquote" plugin.
240       'Blockquote' => [
241         'label' => $this->t('Blockquote'),
242         'image_alternative' => $button('blockquote'),
243         'image_alternative_rtl' => $button('blockquote', 'rtl'),
244       ],
245       // "horizontalrule" plugin
246       'HorizontalRule' => [
247         'label' => $this->t('Horizontal rule'),
248         'image_alternative' => $button('horizontal rule'),
249         'image_alternative_rtl' => $button('horizontal rule', 'rtl'),
250       ],
251       // "clipboard" plugin.
252       'Cut' => [
253         'label' => $this->t('Cut'),
254         'image_alternative' => $button('cut'),
255         'image_alternative_rtl' => $button('cut', 'rtl'),
256       ],
257       'Copy' => [
258         'label' => $this->t('Copy'),
259         'image_alternative' => $button('copy'),
260         'image_alternative_rtl' => $button('copy', 'rtl'),
261       ],
262       'Paste' => [
263         'label' => $this->t('Paste'),
264         'image_alternative' => $button('paste'),
265         'image_alternative_rtl' => $button('paste', 'rtl'),
266       ],
267       // "pastetext" plugin.
268       'PasteText' => [
269         'label' => $this->t('Paste Text'),
270         'image_alternative' => $button('paste text'),
271         'image_alternative_rtl' => $button('paste text', 'rtl'),
272       ],
273       // "pastefromword" plugin.
274       'PasteFromWord' => [
275         'label' => $this->t('Paste from Word'),
276         'image_alternative' => $button('paste from word'),
277         'image_alternative_rtl' => $button('paste from word', 'rtl'),
278       ],
279       // "specialchar" plugin.
280       'SpecialChar' => [
281         'label' => $this->t('Character map'),
282         'image_alternative' => $button('special char'),
283         'image_alternative_rtl' => $button('special char', 'rtl'),
284       ],
285       'Format' => [
286         'label' => $this->t('HTML block format'),
287         'image_alternative' => [
288           '#type' => 'inline_template',
289           '#template' => '<a href="#" role="button" aria-label="{{ format_text }}"><span class="ckeditor-button-dropdown">{{ format_text }}<span class="ckeditor-button-arrow"></span></span></a>',
290           '#context' => [
291             'format_text' => $this->t('Format'),
292           ],
293         ],
294       ],
295       // "table" plugin.
296       'Table' => [
297         'label' => $this->t('Table'),
298         'image_alternative' => $button('table'),
299         'image_alternative_rtl' => $button('table', 'rtl'),
300       ],
301       // "showblocks" plugin.
302       'ShowBlocks' => [
303         'label' => $this->t('Show blocks'),
304         'image_alternative' => $button('show blocks'),
305         'image_alternative_rtl' => $button('show blocks', 'rtl'),
306       ],
307       // "sourcearea" plugin.
308       'Source' => [
309         'label' => $this->t('Source code'),
310         'image_alternative' => $button('source'),
311         'image_alternative_rtl' => $button('source', 'rtl'),
312       ],
313       // "maximize" plugin.
314       'Maximize' => [
315         'label' => $this->t('Maximize'),
316         'image_alternative' => $button('maximize'),
317         'image_alternative_rtl' => $button('maximize', 'rtl'),
318       ],
319       // No plugin, separator "button" for toolbar builder UI use only.
320       '-' => [
321         'label' => $this->t('Separator'),
322         'image_alternative' => [
323           '#type' => 'inline_template',
324           '#template' => '<a href="#" role="button" aria-label="{{ button_separator_text }}" class="ckeditor-separator"></a>',
325           '#context' => [
326             'button_separator_text' => $this->t('Button separator'),
327           ],
328         ],
329         'attributes' => [
330           'class' => ['ckeditor-button-separator'],
331           'data-drupal-ckeditor-type' => 'separator',
332         ],
333         'multiple' => TRUE,
334       ],
335     ];
336   }
337
338   /**
339    * Builds the "format_tags" configuration part of the CKEditor JS settings.
340    *
341    * @see getConfig()
342    *
343    * @param \Drupal\editor\Entity\Editor $editor
344    *   A configured text editor object.
345    *
346    * @return array
347    *   An array containing the "format_tags" configuration.
348    */
349   protected function generateFormatTagsSetting(Editor $editor) {
350     // When no text format is associated yet, assume no tag is allowed.
351     // @see \Drupal\Editor\EditorInterface::hasAssociatedFilterFormat()
352     if (!$editor->hasAssociatedFilterFormat()) {
353       return [];
354     }
355
356     $format = $editor->getFilterFormat();
357     $cid = 'ckeditor_internal_format_tags:' . $format->id();
358
359     if ($cached = $this->cache->get($cid)) {
360       $format_tags = $cached->data;
361     }
362     else {
363       // The <p> tag is always allowed â€” HTML without <p> tags is nonsensical.
364       $format_tags = ['p'];
365
366       // Given the list of possible format tags, automatically determine whether
367       // the current text format allows this tag, and thus whether it should show
368       // up in the "Format" dropdown.
369       $possible_format_tags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre'];
370       foreach ($possible_format_tags as $tag) {
371         $input = '<' . $tag . '>TEST</' . $tag . '>';
372         $output = trim(check_markup($input, $editor->id()));
373         if (Html::load($output)->getElementsByTagName($tag)->length !== 0) {
374           $format_tags[] = $tag;
375         }
376       }
377       $format_tags = implode(';', $format_tags);
378
379       // Cache the "format_tags" configuration. This cache item is infinitely
380       // valid; it only changes whenever the text format is changed, hence it's
381       // tagged with the text format's cache tag.
382       $this->cache->set($cid, $format_tags, Cache::PERMANENT, $format->getCacheTags());
383     }
384
385     return $format_tags;
386   }
387
388   /**
389    * Builds the ACF part of the CKEditor JS settings.
390    *
391    * This ensures that CKEditor obeys the HTML restrictions defined by Drupal's
392    * filter system, by enabling CKEditor's Advanced Content Filter (ACF)
393    * functionality: http://ckeditor.com/blog/CKEditor-4.1-RC-Released.
394    *
395    * @see getConfig()
396    *
397    * @param \Drupal\editor\Entity\Editor $editor
398    *   A configured text editor object.
399    *
400    * @return array
401    *   An array with two values:
402    *   - the first value is the "allowedContent" setting: a well-formatted array
403    *     or TRUE. The latter indicates that anything is allowed.
404    *   - the second value is the "disallowedContent" setting: a well-formatted
405    *     array or FALSE. The latter indicates that nothing is disallowed.
406    */
407   protected function generateACFSettings(Editor $editor) {
408     // When no text format is associated yet, assume nothing is disallowed, so
409     // set allowedContent to true.
410     if (!$editor->hasAssociatedFilterFormat()) {
411       return TRUE;
412     }
413
414     $format = $editor->getFilterFormat();
415     $filter_types = $format->getFilterTypes();
416
417     // When nothing is disallowed, set allowedContent to true.
418     if (!in_array(FilterInterface::TYPE_HTML_RESTRICTOR, $filter_types)) {
419       return [TRUE, FALSE];
420     }
421     // Generate setting that accurately reflects allowed tags and attributes.
422     else {
423       $get_attribute_values = function($attribute_values, $allowed_values) {
424         $values = array_keys(array_filter($attribute_values, function($value) use ($allowed_values) {
425           if ($allowed_values) {
426             return $value !== FALSE;
427           }
428           else {
429             return $value === FALSE;
430           }
431         }));
432         if (count($values)) {
433           return implode(',', $values);
434         }
435         else {
436           return NULL;
437         }
438       };
439
440       $html_restrictions = $format->getHtmlRestrictions();
441       // When all HTML is allowed, also set allowedContent to true and
442       // disallowedContent to false.
443       if ($html_restrictions === FALSE) {
444         return [TRUE, FALSE];
445       }
446       $allowed = [];
447       $disallowed = [];
448       if (isset($html_restrictions['forbidden_tags'])) {
449         foreach ($html_restrictions['forbidden_tags'] as $tag) {
450           $disallowed[$tag] = TRUE;
451         }
452       }
453       foreach ($html_restrictions['allowed'] as $tag => $attributes) {
454         // Tell CKEditor the tag is allowed, but no attributes.
455         if ($attributes === FALSE) {
456           $allowed[$tag] = [
457             'attributes' => FALSE,
458             'styles' => FALSE,
459             'classes' => FALSE,
460           ];
461         }
462         // Tell CKEditor the tag is allowed, as well as any attribute on it. The
463         // "style" and "class" attributes are handled separately by CKEditor:
464         // they are disallowed even if you specify it in the list of allowed
465         // attributes, unless you state specific values for them that are
466         // allowed. Or, in this case: any value for them is allowed.
467         elseif ($attributes === TRUE) {
468           $allowed[$tag] = [
469             'attributes' => TRUE,
470             'styles' => TRUE,
471             'classes' => TRUE,
472           ];
473           // We've just marked that any value for the "style" and "class"
474           // attributes is allowed. However, that may not be the case: the "*"
475           // tag may still apply restrictions.
476           // Since CKEditor's ACF follows the following principle:
477           //     Once validated, an element or its property cannot be
478           //     invalidated by another rule.
479           // That means that the most permissive setting wins. Which means that
480           // it will still be allowed by CKEditor, for instance, to define any
481           // style, no matter what the "*" tag's restrictions may be. If there
482           // is a setting for either the "style" or "class" attribute, it cannot
483           // possibly be more permissive than what was set above. Hence, inherit
484           // from the "*" tag where possible.
485           if (isset($html_restrictions['allowed']['*'])) {
486             $wildcard = $html_restrictions['allowed']['*'];
487             if (isset($wildcard['style'])) {
488               if (!is_array($wildcard['style'])) {
489                 $allowed[$tag]['styles'] = $wildcard['style'];
490               }
491               else {
492                 $allowed_styles = $get_attribute_values($wildcard['style'], TRUE);
493                 if (isset($allowed_styles)) {
494                   $allowed[$tag]['styles'] = $allowed_styles;
495                 }
496                 else {
497                   unset($allowed[$tag]['styles']);
498                 }
499               }
500             }
501             if (isset($wildcard['class'])) {
502               if (!is_array($wildcard['class'])) {
503                 $allowed[$tag]['classes'] = $wildcard['class'];
504               }
505               else {
506                 $allowed_classes = $get_attribute_values($wildcard['class'], TRUE);
507                 if (isset($allowed_classes)) {
508                   $allowed[$tag]['classes'] = $allowed_classes;
509                 }
510                 else {
511                   unset($allowed[$tag]['classes']);
512                 }
513               }
514             }
515           }
516         }
517         // Tell CKEditor the tag is allowed, along with some tags.
518         elseif (is_array($attributes)) {
519           // Set defaults (these will be overridden below if more specific
520           // values are present).
521           $allowed[$tag] = [
522             'attributes' => FALSE,
523             'styles' => FALSE,
524             'classes' => FALSE,
525           ];
526           // Configure allowed attributes, allowed "style" attribute values and
527           // allowed "class" attribute values.
528           // CKEditor only allows specific values for the "class" and "style"
529           // attributes; so ignore restrictions on other attributes, which
530           // Drupal filters may provide.
531           // NOTE: A Drupal contrib module can subclass this class, override the
532           // getConfig() method, and override the JavaScript at
533           // Drupal.editors.ckeditor to somehow make validation of values for
534           // attributes other than "class" and "style" work.
535           $allowed_attributes = array_filter($attributes, function($value) {
536             return $value !== FALSE;
537           });
538           if (count($allowed_attributes)) {
539             $allowed[$tag]['attributes'] = implode(',', array_keys($allowed_attributes));
540           }
541           if (isset($allowed_attributes['style'])) {
542             if (is_bool($allowed_attributes['style'])) {
543               $allowed[$tag]['styles'] = $allowed_attributes['style'];
544             }
545             elseif (is_array($allowed_attributes['style'])) {
546               $allowed_classes = $get_attribute_values($allowed_attributes['style'], TRUE);
547               if (isset($allowed_classes)) {
548                 $allowed[$tag]['styles'] = $allowed_classes;
549               }
550             }
551           }
552           if (isset($allowed_attributes['class'])) {
553             if (is_bool($allowed_attributes['class'])) {
554               $allowed[$tag]['classes'] = $allowed_attributes['class'];
555             }
556             elseif (is_array($allowed_attributes['class'])) {
557               $allowed_classes = $get_attribute_values($allowed_attributes['class'], TRUE);
558               if (isset($allowed_classes)) {
559                 $allowed[$tag]['classes'] = $allowed_classes;
560               }
561             }
562           }
563
564           // Handle disallowed attributes analogously. However, to handle *dis-
565           // allowed* attribute values, we must look at *allowed* attributes'
566           // disallowed attribute values! After all, a disallowed attribute
567           // implies that all of its possible attribute values are disallowed,
568           // thus we must look at the disallowed attribute values on allowed
569           // attributes.
570           $disallowed_attributes = array_filter($attributes, function($value) {
571             return $value === FALSE;
572           });
573           if (count($disallowed_attributes)) {
574             // No need to blacklist the 'class' or 'style' attributes; CKEditor
575             // handles them separately (if no specific class or style attribute
576             // values are allowed, then those attributes are disallowed).
577             if (isset($disallowed_attributes['class'])) {
578               unset($disallowed_attributes['class']);
579             }
580             if (isset($disallowed_attributes['style'])) {
581               unset($disallowed_attributes['style']);
582             }
583             $disallowed[$tag]['attributes'] = implode(',', array_keys($disallowed_attributes));
584           }
585           if (isset($allowed_attributes['style']) && is_array($allowed_attributes['style'])) {
586             $disallowed_styles = $get_attribute_values($allowed_attributes['style'], FALSE);
587             if (isset($disallowed_styles)) {
588               $disallowed[$tag]['styles'] = $disallowed_styles;
589             }
590           }
591           if (isset($allowed_attributes['class']) && is_array($allowed_attributes['class'])) {
592             $disallowed_classes = $get_attribute_values($allowed_attributes['class'], FALSE);
593             if (isset($disallowed_classes)) {
594               $disallowed[$tag]['classes'] = $disallowed_classes;
595             }
596           }
597         }
598       }
599
600       ksort($allowed);
601       ksort($disallowed);
602
603       return [$allowed, $disallowed];
604     }
605   }
606
607 }