/
filter.js
1983 lines (1716 loc) · 62.7 KB
/
filter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function() {
'use strict';
var DTD = CKEDITOR.dtd,
copy = CKEDITOR.tools.copy,
trim = CKEDITOR.tools.trim,
TEST_VALUE = 'cke-test';
/**
* Highly configurable class which implements input data filtering mechanisms
* and core functions used for the activation of editor features.
*
* A filter instance is always available under the {@link CKEDITOR.editor#filter}
* property and is used by the editor in its core features like filtering input data,
* applying data transformations, validating whether a feature may be enabled for
* the current setup. It may be configured in two ways:
*
* * By the user, with the {@link CKEDITOR.config#allowedContent} setting.
* * Automatically, by loaded features (toolbar items, commands, etc.).
*
* In both cases additional allowed content rules may be added by
* setting the {@link CKEDITOR.config#extraAllowedContent}
* configuration option.
*
* **Note**: Filter rules will be extended with the following elements
* depending on the {@link CKEDITOR.config#enterMode} setting:
*
* * `'p br'` – for {@link CKEDITOR#ENTER_P},
* * `'div br'` – for {@link CKEDITOR#ENTER_DIV},
* * `'br'` – for {@link CKEDITOR#ENTER_BR}.
*
* **Read more** about the Advanced Content Filter in [guides](#!/guide/dev_advanced_content_filter).
*
* Filter may also be used as a standalone instance by passing
* {@link CKEDITOR.filter.allowedContentRules} instead of {@link CKEDITOR.editor}
* to the constructor:
*
* var filter = new CKEDITOR.filter( 'b' );
*
* filter.check( 'b' ); // -> true
* filter.check( 'i' ); // -> false
* filter.allow( 'i' );
* filter.check( 'i' ); // -> true
*
* @since 4.1
* @class
* @constructor Creates a filter class instance.
* @param {CKEDITOR.editor/CKEDITOR.filter.allowedContentRules} editorOrRules
*/
CKEDITOR.filter = function( editorOrRules ) {
/**
* Whether custom {@link CKEDITOR.config#allowedContent} was set.
*
* This property does not apply to the standalone filter.
*
* @readonly
* @property {Boolean} customConfig
*/
/**
* Array of rules added by the {@link #allow} method (including those
* loaded from {@link CKEDITOR.config#allowedContent} and
* {@link CKEDITOR.config#extraAllowedContent}).
*
* Rules in this array are in unified allowed content rules format.
*
* This property is useful for debugging issues with rules string parsing
* or for checking which rules were automatically added by editor features.
*
* @readonly
*/
this.allowedContent = [];
/**
* Whether the filter is disabled.
*
* To disable the filter, set {@link CKEDITOR.config#allowedContent} to `true`
* or use the {@link #disable} method.
*
* @readonly
*/
this.disabled = false;
/**
* Editor instance if not a standalone filter.
*
* @readonly
* @property {CKEDITOR.editor} [=null]
*/
this.editor = null;
/**
* Enter mode used by the filter when deciding how to strip disallowed elements.
*
* For editor filter it will be set to {@link CKEDITOR.config#enterMode} unless this
* is a blockless (see {@link CKEDITOR.editor#blockless}) editor — in this case
* {@link CKEDITOR#ENTER_BR} will be forced.
*
* For the standalone filter by default it will be set to {@link CKEDITOR#ENTER_P}.
*
* @readonly
* @property {Number} [=CKEDITOR.ENTER_P]
*/
this.enterMode = CKEDITOR.ENTER_P;
this._ = {
// Optimized allowed content rules.
rules: {},
// Object: element name => array of transformations groups.
transformations: {},
cachedTests: {}
};
if ( editorOrRules instanceof CKEDITOR.editor ) {
var editor = this.editor = editorOrRules;
this.customConfig = true;
var allowedContent = editor.config.allowedContent,
enterMode;
// Disable filter completely by setting config.allowedContent = true.
if ( allowedContent === true ) {
this.disabled = true;
return;
}
if ( !allowedContent )
this.customConfig = false;
// Force ENTER_BR for blockless editable.
this.enterMode = enterMode = ( editor.blockless ? CKEDITOR.ENTER_BR : editor.config.enterMode );
this.allow( 'br ' + ( enterMode == CKEDITOR.ENTER_P ? 'p' : enterMode == CKEDITOR.ENTER_DIV ? 'div' : '' ), 'default', 1 );
this.allow( allowedContent, 'config', 1 );
this.allow( editor.config.extraAllowedContent, 'extra', 1 );
//
// Add filter listeners to toHTML and toDataFormat events.
//
// Filter incoming "data".
// Add element filter before htmlDataProcessor.dataFilter
// when purifying input data to correct html.
this._.toHtmlListener = editor.on( 'toHtml', function( evt ) {
if ( this.applyTo( evt.data.dataValue, true, evt.data.dontFilter ) )
editor.fire( 'dataFiltered' );
}, this, null, 6 );
// Transform outcoming "data".
// Add element filter after htmlDataProcessor.htmlFilter
// when preparing output data HTML.
this._.toDataFormatListener = editor.on( 'toDataFormat', function( evt ) {
this.applyTo( evt.data.dataValue, false, true );
}, this, null, 11 );
}
// Rules object passed in editorOrRules argument - initialize standalone filter.
else {
this.customConfig = false;
this.allow( editorOrRules, 'default', 1 );
}
};
CKEDITOR.filter.prototype = {
/**
* Adds allowed content rules to the filter.
*
* Read about rules formats in [Allowed Content Rules guide](#!/guide/dev_allowed_content_rules).
*
* // Add a basic rule for custom image feature (e.g. 'MyImage' button).
* editor.filter.allow( 'img[!src,alt]', 'MyImage' );
*
* // Add rules for two header styles allowed by 'HeadersCombo'.
* var header1Style = new CKEDITOR.style( { element: 'h1' } ),
* header2Style = new CKEDITOR.style( { element: 'h2' } );
* editor.filter.allow( [ header1Style, header2Style ], 'HeadersCombo' );
*
* @param {CKEDITOR.filter.allowedContentRules} newRules Rule(s) to be added.
* @param {String} [featureName] Name of a feature that allows this content (most often plugin/button/command name).
* @param {Boolean} [overrideCustom] By default this method will reject any rules
* if {@link CKEDITOR.config#allowedContent} is defined to avoid overriding it.
* Pass `true` to force rules addition.
* @returns {Boolean} Whether the rules were accepted.
*/
allow: function( newRules, featureName, overrideCustom ) {
if ( this.disabled )
return false;
// Don't override custom user's configuration if not explicitly requested.
if ( this.customConfig && !overrideCustom )
return false;
if ( !newRules )
return false;
// Clear cache, because new rules could change results of checks.
this._.cachedChecks = {};
var i, ret;
if ( typeof newRules == 'string' )
newRules = parseRulesString( newRules );
else if ( newRules instanceof CKEDITOR.style )
newRules = convertStyleToRules( newRules );
else if ( CKEDITOR.tools.isArray( newRules ) ) {
for ( i = 0; i < newRules.length; ++i )
ret = this.allow( newRules[ i ], featureName, overrideCustom );
return ret; // Return last status.
}
var groupName, rule,
rulesToOptimize = [];
for ( groupName in newRules ) {
rule = newRules[ groupName ];
// { 'p h1': true } => { 'p h1': {} }.
if ( typeof rule == 'boolean' )
rule = {};
// { 'p h1': func } => { 'p h1': { match: func } }.
else if ( typeof rule == 'function' )
rule = { match: rule };
// Clone (shallow) rule, because we'll modify it later.
else
rule = copy( rule );
// If this is not an unnamed rule ({ '$1' => { ... } })
// move elements list to property.
if ( groupName.charAt( 0 ) != '$' )
rule.elements = groupName;
if ( featureName )
rule.featureName = featureName.toLowerCase();
standardizeRule( rule );
// Save rule and remember to optimize it.
this.allowedContent.push( rule );
rulesToOptimize.push( rule );
}
optimizeRules( this._.rules, rulesToOptimize );
return true;
},
/**
* Applies this filter to passed {@link CKEDITOR.htmlParser.fragment} or {@link CKEDITOR.htmlParser.element}.
* The result of filtering is a DOM tree without disallowed content.
*
* // Create standalone filter passing 'p' and 'b' elements.
* var filter = new CKEDITOR.filter( 'p b' ),
* // Parse HTML string to pseudo DOM structure.
* fragment = CKEDITOR.htmlParser.fragment.fromHtml( '<p><b>foo</b> <i>bar</i></p>' ),
* writer = new CKEDITOR.htmlParser.basicWriter();
*
* filter.applyTo( fragment );
* fragment.writeHtml( writer );
* writer.getHtml(); // -> '<p><b>foo</b> bar</p>'
*
* @param {CKEDITOR.htmlParser.fragment/CKEDITOR.htmlParser.element} fragment Node to be filtered.
* @param {Boolean} [toHtml] Set to `true` if the filter is used together with {@link CKEDITOR.htmlDataProcessor#toHtml}.
* @param {Boolean} [transformOnly] If set to `true` only transformations will be applied. Content
* will not be filtered with allowed content rules.
* @returns {Boolean} Whether some part of the `fragment` was removed by the filter.
*/
applyTo: function( fragment, toHtml, transformOnly ) {
var toBeRemoved = [],
rules = !transformOnly && this._.rules,
transformations = this._.transformations,
filterFn = getFilterFunction( this ),
protectedRegexs = this.editor && this.editor.config.protectedSource,
isModified = false;
// Filter all children, skip root (fragment or editable-like wrapper used by data processor).
fragment.forEach( function( el ) {
if ( el.type == CKEDITOR.NODE_ELEMENT ) {
if ( filterFn( el, rules, transformations, toBeRemoved, toHtml ) )
isModified = true;
}
else if ( el.type == CKEDITOR.NODE_COMMENT && el.value.match( /^\{cke_protected\}(?!\{C\})/ ) ) {
if ( !filterProtectedElement( el, protectedRegexs, filterFn, rules, transformations, toHtml ) )
toBeRemoved.push( el );
}
}, null, true );
if ( toBeRemoved.length )
isModified = true;
var node, element, check,
toBeChecked = [],
enterTag = [ 'p', 'br', 'div' ][ this.enterMode - 1 ];
// Remove elements in reverse order - from leaves to root, to avoid conflicts.
while ( ( node = toBeRemoved.pop() ) ) {
if ( node.type == CKEDITOR.NODE_ELEMENT )
removeElement( node, enterTag, toBeChecked );
// This is a comment securing rejected element - remove it completely.
else
node.remove();
}
// Check elements that have been marked as possibly invalid.
while ( ( check = toBeChecked.pop() ) ) {
element = check.el;
// Element has been already removed.
if ( !element.parent )
continue;
switch ( check.check ) {
// Check if element itself is correct.
case 'it':
// Check if element included in $removeEmpty has no children.
if ( DTD.$removeEmpty[ element.name ] && !element.children.length )
removeElement( element, enterTag, toBeChecked );
// Check if that is invalid element.
else if ( !validateElement( element ) )
removeElement( element, enterTag, toBeChecked );
break;
// Check if element is in correct context. If not - remove element.
case 'el-up':
// Check if e.g. li is a child of body after ul has been removed.
if ( element.parent.type != CKEDITOR.NODE_DOCUMENT_FRAGMENT &&
!DTD[ element.parent.name ][ element.name ]
)
removeElement( element, enterTag, toBeChecked );
break;
// Check if element is in correct context. If not - remove parent.
case 'parent-down':
if ( element.parent.type != CKEDITOR.NODE_DOCUMENT_FRAGMENT &&
!DTD[ element.parent.name ][ element.name ]
)
removeElement( element.parent, enterTag, toBeChecked );
break;
}
}
return isModified;
},
/**
* Checks whether a {@link CKEDITOR.feature} can be enabled. Unlike {@link #addFeature},
* this method always checks the feature, even when the default configuration
* for {@link CKEDITOR.config#allowedContent} is used.
*
* // TODO example
*
* @param {CKEDITOR.feature} feature The feature to be tested.
* @returns {Boolean} Whether this feature can be enabled.
*/
checkFeature: function( feature ) {
if ( this.disabled )
return true;
if ( !feature )
return true;
// Some features may want to register other feature.
// E.g. button may return command bound to it.
if ( feature.toFeature )
feature = feature.toFeature( this.editor );
return !feature.requiredContent || this.check( feature.requiredContent );
},
/**
* Disables Advanced Content Filter.
*
* This method is meant to be used by plugins which are not
* compatible with the filter and in other cases in which the filter
* has to be disabled during the initialization phase or runtime.
*
* In other cases the filter can be disabled by setting
* {@link CKEDITOR.config#allowedContent} to `true`.
*/
disable: function() {
this.disabled = true;
if ( this._.toHtmlListener )
this._.toHtmlListener.removeListener();
if ( this._.toDataFormatListener )
this._.toDataFormatListener.removeListener();
},
/**
* Adds an array of {@link CKEDITOR.feature} content forms. All forms
* will then be transformed to the first form which is allowed by the filter.
*
* editor.filter.allow( 'i; span{!font-style}' );
* editor.filter.addContentForms( [
* 'em',
* 'i',
* [ 'span', function( el ) {
* return el.styles[ 'font-style' ] == 'italic';
* } ]
* ] );
* // Now <em> and <span style="font-style:italic"> will be replaced with <i>
* // because this is the first allowed form.
* // <span> is allowed too, but it is the last form and
* // additionaly, the editor cannot transform an element based on
* // the array+function form).
*
* This method is used by the editor to register {@link CKEDITOR.feature#contentForms}
* when adding a feature with {@link #addFeature} or {@link CKEDITOR.editor#addFeature}.
*
* @param {Array} forms The feature's content forms.
*/
addContentForms: function( forms ) {
if ( this.disabled )
return;
if ( !forms )
return;
var i, form,
transfGroups = [],
preferredForm;
// First, find preferred form - this is, first allowed.
for ( i = 0; i < forms.length && !preferredForm; ++i ) {
form = forms[ i ];
// Check only strings and styles - array format isn't supported by #check().
if ( ( typeof form == 'string' || form instanceof CKEDITOR.style ) && this.check( form ) )
preferredForm = form;
}
// This feature doesn't have preferredForm, so ignore it.
if ( !preferredForm )
return;
for ( i = 0; i < forms.length; ++i )
transfGroups.push( getContentFormTransformationGroup( forms[ i ], preferredForm ) );
this.addTransformations( transfGroups );
},
/**
* Checks whether a feature can be enabled for the HTML restrictions in place
* for the current CKEditor instance, based on the HTML the feature might
* generate and the minimal HTML the feature needs to be able to generate.
*
* // TODO example
*
* @param {CKEDITOR.feature} feature
* @returns {Boolean} Whether this feature can be enabled.
*/
addFeature: function( feature ) {
if ( this.disabled )
return true;
if ( !feature )
return true;
// Some features may want to register other feature.
// E.g. button may return command bound to it.
if ( feature.toFeature )
feature = feature.toFeature( this.editor );
// If default configuration (will be checked inside #allow()),
// then add allowed content rules.
this.allow( feature.allowedContent, feature.name );
this.addTransformations( feature.contentTransformations );
this.addContentForms( feature.contentForms );
// If custom configuration, then check if required content is allowed.
if ( this.customConfig && feature.requiredContent )
return this.check( feature.requiredContent );
return true;
},
/**
* Adds an array of content transformation groups. One group
* may contain many transformation rules, but only the first
* matching rule in a group is executed.
*
* A single transformation rule is an object with four properties:
*
* * `check` (optional) – if set and {@link CKEDITOR.filter} does
* not accept this allowed content rule, this transformation rule
* will not be executed (it does not *match*). This value is passed
* to {@link #check}.
* * `element` (optional) – this string property tells the filter on which
* element this transformation can be run. It is optional, because
* the element name can be obtained from `check` (if it is a String format)
* or `left` (if it is a {@link CKEDITOR.style} instance).
* * `left` (optional) – a function accepting an element or a {@link CKEDITOR.style}
* instance verifying whether the transformation should be
* executed on this specific element. If it returns `false` or if an element
* does not match this style, this transformation rule does not *match*.
* * `right` – a function accepting an element and {@link CKEDITOR.filter.transformationsTools}
* or a string containing the name of the {@link CKEDITOR.filter.transformationsTools} method
* that should be called on an element.
*
* A shorthand format is also available. A transformation rule can be defined by
* a single string `'check:right'`. The string before `':'` will be used as
* the `check` property and the second part as the `right` property.
*
* Transformation rules can be grouped. The filter will try to apply
* the first rule in a group. If it *matches*, the filter will ignore subsequent rules and
* will move to the next group. If it does not *match*, the next rule will be checked.
*
* Examples:
*
* editor.filter.addTransformations( [
* // First group.
* [
* // First rule. If table{width} is allowed, it
* // executes {@link CKEDITOR.filter.transformationsTools#sizeToStyle} on a table element.
* 'table{width}: sizeToStyle',
* // Second rule should not be executed if the first was.
* 'table[width]: sizeToAttribute'
* ],
* // Second group.
* [
* // This rule will add the foo="1" attribute to all images that
* // do not have it.
* {
* element: 'img',
* left: function( el ) {
* return !el.attributes.foo;
* },
* right: function( el, tools ) {
* el.attributes.foo = '1';
* }
* }
* ]
* ] );
*
* // Case 1:
* // config.allowedContent = 'table{height,width}; tr td'.
* //
* // '<table style="height:100px; width:200px">...</table>' -> '<table style="height:100px; width:200px">...</table>'
* // '<table height="100" width="200">...</table>' -> '<table style="height:100px; width:200px">...</table>'
*
* // Case 2:
* // config.allowedContent = 'table[height,width]; tr td'.
* //
* // '<table style="height:100px; width:200px">...</table>' -> '<table height="100" width="200">...</table>'
* // '<table height="100" width="200">...</table>' -> '<table height="100" width="200"">...</table>'
*
* // Case 3:
* // config.allowedContent = 'table{width,height}[height,width]; tr td'.
* //
* // '<table style="height:100px; width:200px">...</table>' -> '<table style="height:100px; width:200px">...</table>'
* // '<table height="100" width="200">...</table>' -> '<table style="height:100px; width:200px">...</table>'
* //
* // Note: Both forms are allowed (size set by style and by attributes), but only
* // the first transformation is applied — the size is always transformed to a style.
* // This is because only the first transformation matching allowed content rules is applied.
*
* This method is used by the editor to add {@link CKEDITOR.feature#contentTransformations}
* when adding a feature by {@link #addFeature} or {@link CKEDITOR.editor#addFeature}.
*
* @param {Array} transformations
*/
addTransformations: function( transformations ) {
if ( this.disabled )
return;
if ( !transformations )
return;
var optimized = this._.transformations,
group, i;
for ( i = 0; i < transformations.length; ++i ) {
group = optimizeTransformationsGroup( transformations[ i ] );
if ( !optimized[ group.name ] )
optimized[ group.name ] = [];
optimized[ group.name ].push( group.rules );
}
},
/**
* Checks whether the content defined in the `test` argument is allowed
* by this filter.
*
* If `strictCheck` is set to `false` (default value), this method checks
* if all parts of the `test` (styles, attributes, and classes) are
* accepted by the filter. If `strictCheck` is set to `true`, the test
* must also contain the required attributes, styles, and classes.
*
* For example:
*
* // Rule: 'img[!src,alt]'.
* filter.check( 'img[alt]' ); // -> true
* filter.check( 'img[alt]', true, true ); // -> false
*
* Second `check()` call returned `false` because `src` is required.
*
* @param {CKEDITOR.filter.contentRule} test
* @param {Boolean} [applyTransformations=true] Whether to use registered transformations.
* @param {Boolean} [strictCheck] Whether the filter should check if an element with exactly
* these properties is allowed.
* @returns {Boolean} Returns `true` if the content is allowed.
*/
check: function( test, applyTransformations, strictCheck ) {
if ( this.disabled )
return true;
var element, result, cacheKey;
if ( typeof test == 'string' ) {
cacheKey = test + '<' + ( applyTransformations === false ? '0' : '1' ) + ( strictCheck ? '1' : '0' ) + '>';
// Check if result of this check hasn't been already cached.
if ( cacheKey in this._.cachedChecks )
return this._.cachedChecks[ cacheKey ];
// Create test element from string.
element = mockElementFromString( test );
} else
// Create test element from CKEDITOR.style.
element = mockElementFromStyle( test );
// Make a deep copy.
var clone = CKEDITOR.tools.clone( element ),
toBeRemoved = [],
transformations, i;
// Apply transformations to original element.
// Transformations will be applied to clone by the filter function.
if ( applyTransformations !== false && ( transformations = this._.transformations[ element.name ] ) ) {
for ( i = 0; i < transformations.length; ++i )
applyTransformationsGroup( this, element, transformations[ i ] );
// Transformations could modify styles or classes, so they need to be copied
// to attributes object.
updateAttributes( element );
}
// Filter clone of mocked element.
// Do not run transformations.
getFilterFunction( this )( clone, this._.rules, applyTransformations === false ? false : this._.transformations, toBeRemoved, false, !strictCheck, !strictCheck );
// Element has been marked for removal.
if ( toBeRemoved.length > 0 )
result = false;
// Compare only left to right, because clone may be only trimmed version of original element.
else if ( !CKEDITOR.tools.objectCompare( element.attributes, clone.attributes, true ) )
result = false;
else
result = true;
// Cache result of this test - we can build cache only for string tests.
if ( typeof test == 'string' )
this._.cachedChecks[ cacheKey ] = result;
return result;
}
};
// Apply ACR to an element
// @param rule
// @param element
// @param status Object containing status of element's filtering.
// @param {Boolean} isSpecific True if this is specific element's rule, false if generic.
// @param {Boolean} skipRequired If true don't check if element has all required properties.
function applyRule( rule, element, status, isSpecific, skipRequired ) {
var name = element.name;
// This generic rule doesn't apply to this element - skip it.
if ( !isSpecific && typeof rule.elements == 'function' && !rule.elements( name ) )
return;
// This rule doesn't match this element - skip it.
if ( rule.match ) {
if ( !rule.match( element ) )
return;
}
// If element doesn't have all required styles/attrs/classes
// this rule doesn't match it.
if ( !skipRequired && !hasAllRequired( rule, element ) )
return;
// If this rule doesn't validate properties only mark element as valid.
if ( !rule.propertiesOnly )
status.valid = true;
// Apply rule only when all attrs/styles/classes haven't been marked as valid.
if ( !status.allAttributes )
status.allAttributes = applyRuleToHash( rule.attributes, element.attributes, status.validAttributes );
if ( !status.allStyles )
status.allStyles = applyRuleToHash( rule.styles, element.styles, status.validStyles );
if ( !status.allClasses )
status.allClasses = applyRuleToArray( rule.classes, element.classes, status.validClasses );
}
// Apply itemsRule to items (only classes are kept in array).
// Push accepted items to validItems array.
// Return true when all items are valid.
function applyRuleToArray( itemsRule, items, validItems ) {
if ( !itemsRule )
return false;
// True means that all elements of array are accepted (the asterix was used for classes).
if ( itemsRule === true )
return true;
for ( var i = 0, l = items.length, item; i < l; ++i ) {
item = items[ i ];
if ( !validItems[ item ] )
validItems[ item ] = itemsRule( item );
}
return false;
}
function applyRuleToHash( itemsRule, items, validItems ) {
if ( !itemsRule )
return false;
if ( itemsRule === true )
return true;
for ( var name in items ) {
if ( !validItems[ name ] )
validItems[ name ] = itemsRule( name, items[ name ] );
}
return false;
}
// Convert CKEDITOR.style to filter's rule.
function convertStyleToRules( style ) {
var styleDef = style.getDefinition(),
rules = {},
rule,
attrs = styleDef.attributes;
rules[ styleDef.element ] = rule = {
styles: styleDef.styles,
requiredStyles: styleDef.styles && CKEDITOR.tools.objectKeys( styleDef.styles )
};
if ( attrs ) {
attrs = copy( attrs );
rule.classes = attrs[ 'class' ] ? attrs[ 'class' ].split( /\s+/ ) : null;
rule.requiredClasses = rule.classes;
delete attrs[ 'class' ];
rule.attributes = attrs;
rule.requiredAttributes = attrs && CKEDITOR.tools.objectKeys( attrs );
}
return rules;
}
// Convert all validator formats (string, array, object, boolean) to hash or boolean:
// * true is returned for '*'/true validator,
// * false is returned for empty validator (no validator at all (false/null) or e.g. empty array),
// * object is returned in other cases.
function convertValidatorToHash( validator, delimiter ) {
if ( !validator )
return false;
if ( validator === true )
return validator;
if ( typeof validator == 'string' ) {
validator = trim( validator );
if ( validator == '*' )
return true;
else
return CKEDITOR.tools.convertArrayToObject( validator.split( delimiter ) );
}
else if ( CKEDITOR.tools.isArray( validator ) ) {
if ( validator.length )
return CKEDITOR.tools.convertArrayToObject( validator );
else
return false;
}
// If object.
else {
var obj = {},
len = 0;
for ( var i in validator ) {
obj[ i ] = validator[ i ];
len++
}
return len ? obj : false;
}
}
// Extract required properties from "required" validator and "all" properties.
// Remove exclamation marks from "all" properties.
//
// E.g.:
// requiredClasses = { cl1: true }
// (all) classes = { cl1: true, cl2: true, '!cl3': true }
//
// result:
// returned = { cl1: true, cl3: true }
// all = { cl1: true, cl2: true, cl3: true }
//
// This function returns false if nothing is required.
function extractRequired( required, all ) {
var unbang = [],
empty = true,
i;
if ( required )
empty = false;
else
required = {};
for ( i in all ) {
if ( i.charAt( 0 ) == '!' ) {
i = i.slice( 1 );
unbang.push( i );
required[ i ] = true;
empty = false;
}
}
while ( ( i = unbang.pop() ) ) {
all[ i ] = all[ '!' + i ];
delete all[ '!' + i ];
}
return empty ? false : required;
}
// Filter element protected with a comment.
// Returns true if protected content is ok, false otherwise.
function filterProtectedElement( comment, protectedRegexs, filterFn, rules, transformations, toHtml ) {
var source = decodeURIComponent( comment.value.replace( /^\{cke_protected\}/, '' ) ),
protectedFrag,
toBeRemoved = [],
node, i, match;
// Protected element's and protected source's comments look exactly the same.
// Check if what we have isn't a protected source instead of protected script/noscript.
if ( protectedRegexs ) {
for ( i = 0; i < protectedRegexs.length; ++i ) {
if ( ( match = source.match( protectedRegexs[ i ] ) ) &&
match[ 0 ].length == source.length // Check whether this pattern matches entire source
// to avoid '<script>alert("<? 1 ?>")</script>' matching
// the PHP's protectedSource regexp.
)
return true;
}
}
protectedFrag = CKEDITOR.htmlParser.fragment.fromHtml( source );
if ( protectedFrag.children.length == 1 && ( node = protectedFrag.children[ 0 ] ).type == CKEDITOR.NODE_ELEMENT )
filterFn( node, rules, transformations, toBeRemoved, toHtml );
// If protected element has been marked to be removed, return 'false' - comment was rejected.
return !toBeRemoved.length;
}
// Returns function that accepts {@link CKEDITOR.htmlParser.element}
// and filters it basing on allowed content rules registered by
// {@link #allow} method.
//
// @param {CKEDITOR.filter} that
function getFilterFunction( that ) {
// Return cached function.
if ( that._.filterFunction )
return that._.filterFunction;
var unprotectElementsNamesRegexp = /^cke:(object|embed|param)$/,
protectElementsNamesRegexp = /^(object|embed|param)$/;
// Return and cache created function.
// @param {CKEDITOR.htmlParser.element}
// @param [optimizedRules] Rules to be used.
// @param [transformations] Transformations to be applied.
// @param {Array} toBeRemoved Array into which elements rejected by the filter will be pushed.
// @param {Boolean} [toHtml] Set to true if filter used together with htmlDP#toHtml
// @param {Boolean} [skipRequired] Whether element's required properties shouldn't be verified.
// @param {Boolean} [skipFinalValidation] Whether to not perform final element validation (a,img).
// @returns {Boolean} Whether content has been modified.
return that._.filterFunction = function( element, optimizedRules, transformations, toBeRemoved, toHtml, skipRequired, skipFinalValidation ) {
var name = element.name,
i, l, trans,
isModified = false;
// Unprotect elements names previously protected by htmlDataProcessor
// (see protectElementNames and protectSelfClosingElements functions).
// Note: body, title, etc. are not protected by htmlDataP (or are protected and then unprotected).
if ( toHtml )
element.name = name = name.replace( unprotectElementsNamesRegexp, '$1' );
// If transformations are set apply all groups.
if ( ( transformations = transformations && transformations[ name ] ) ) {
populateProperties( element );
for ( i = 0; i < transformations.length; ++i )
applyTransformationsGroup( that, element, transformations[ i ] );
// Update style and class attrs, because that won't be done after applying rules.
if ( !optimizedRules )
updateAttributes( element );
}
if ( optimizedRules ) {
// Name could be changed by transformations.
name = element.name;
var rules = optimizedRules.elements[ name ],
genericRules = optimizedRules.generic,
status = {
// Whether any of rules accepted element.
// If not - it will be stripped.
valid: false,
// Objects containing accepted attributes, classes and styles.
validAttributes: {},
validClasses: {},
validStyles: {},
// Whether all are valid.
// If we know that all element's attrs/classes/styles are valid
// we can skip their validation, to improve performance.
allAttributes: false,
allClasses: false,
allStyles: false
};
// Early return - if there are no rules for this element (specific or generic), remove it.
if ( !rules && !genericRules ) {
toBeRemoved.push( element );
return true;
}
// Could not be done yet if there were no transformations and if this
// is real (not mocked) object.
populateProperties( element );
if ( rules ) {
for ( i = 0, l = rules.length; i < l; ++i )
applyRule( rules[ i ], element, status, true, skipRequired );
}
if ( genericRules ) {
for ( i = 0, l = genericRules.length; i < l; ++i )
applyRule( genericRules[ i ], element, status, false, skipRequired );
}
// Finally, if after running all filter rules it still hasn't been allowed - remove it.
if ( !status.valid ) {
toBeRemoved.push( element );
return true;
}
// Update element's attributes based on status of filtering.
if ( updateElement( element, status ) )
isModified = true;
if ( !skipFinalValidation && !validateElement( element ) ) {
toBeRemoved.push( element );
return true;
}
}
// Protect previously unprotected elements.
if ( toHtml )
element.name = element.name.replace( protectElementsNamesRegexp, 'cke:$1' );
return isModified;
};
}
// Check whether element has all properties (styles,classes,attrs) required by a rule.
function hasAllRequired( rule, element ) {
if ( rule.nothingRequired )
return true;
var i, reqs, existing;
if ( ( reqs = rule.requiredClasses ) ) {
existing = element.classes;
for ( i = 0; i < reqs.length; ++i ) {
if ( CKEDITOR.tools.indexOf( existing, reqs[ i ] ) == -1 )
return false;
}
}
return hasAllRequiredInHash( element.styles, rule.requiredStyles ) &&
hasAllRequiredInHash( element.attributes, rule.requiredAttributes );
}
// Check whether all items in required (array) exist in existing (object).
function hasAllRequiredInHash( existing, required ) {
if ( !required )