JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
vanilla ckeditor-3.5
[ckeditor.git] / _source / plugins / htmldataprocessor / plugin.js
1 /*\r
2 Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.\r
3 For licensing, see LICENSE.html or http://ckeditor.com/license\r
4 */\r
5 \r
6 (function()\r
7 {\r
8         // Regex to scan for   at the end of blocks, which are actually placeholders.\r
9         // Safari transforms the   to \xa0. (#4172)\r
10         var tailNbspRegex = /^[\t\r\n ]*(?: |\xa0)$/;\r
11 \r
12         var protectedSourceMarker = '{cke_protected}';\r
13 \r
14         // Return the last non-space child node of the block (#4344).\r
15         function lastNoneSpaceChild( block )\r
16         {\r
17                 var lastIndex = block.children.length,\r
18                         last = block.children[ lastIndex - 1 ];\r
19                 while (  last && last.type == CKEDITOR.NODE_TEXT && !CKEDITOR.tools.trim( last.value ) )\r
20                         last = block.children[ --lastIndex ];\r
21                 return last;\r
22         }\r
23 \r
24         function trimFillers( block, fromSource )\r
25         {\r
26                 // If the current node is a block, and if we're converting from source or\r
27                 // we're not in IE then search for and remove any tailing BR node.\r
28                 //\r
29                 // Also, any   at the end of blocks are fillers, remove them as well.\r
30                 // (#2886)\r
31                 var children = block.children, lastChild = lastNoneSpaceChild( block );\r
32                 if ( lastChild )\r
33                 {\r
34                         if ( ( fromSource || !CKEDITOR.env.ie ) && lastChild.type == CKEDITOR.NODE_ELEMENT && lastChild.name == 'br' )\r
35                                 children.pop();\r
36                         if ( lastChild.type == CKEDITOR.NODE_TEXT && tailNbspRegex.test( lastChild.value ) )\r
37                                 children.pop();\r
38                 }\r
39         }\r
40 \r
41         function blockNeedsExtension( block, fromSource, extendEmptyBlock )\r
42         {\r
43                 if( !fromSource && ( !extendEmptyBlock ||\r
44                         typeof extendEmptyBlock == 'function' && ( extendEmptyBlock( block ) === false ) ) )\r
45                         return false;\r
46 \r
47         // 1. For IE version >=8,  empty blocks are displayed correctly themself in wysiwiyg;\r
48         // 2. For the rest, at least table cell and list item need no filler space.\r
49         // (#6248)\r
50         if ( fromSource && CKEDITOR.env.ie &&\r
51                 ( document.documentMode > 7\r
52                 || block.name in CKEDITOR.dtd.tr\r
53                 || block.name in CKEDITOR.dtd.$listItem ) )\r
54             return false;\r
55 \r
56                 var lastChild = lastNoneSpaceChild( block );\r
57 \r
58                 return !lastChild || lastChild &&\r
59                                 ( lastChild.type == CKEDITOR.NODE_ELEMENT && lastChild.name == 'br'\r
60                                 // Some of the controls in form needs extension too,\r
61                                 // to move cursor at the end of the form. (#4791)\r
62                                 || block.name == 'form' && lastChild.name == 'input' );\r
63         }\r
64 \r
65         function getBlockExtension( isOutput, emptyBlockFiller )\r
66         {\r
67                 return function( node )\r
68                 {\r
69                         trimFillers( node, !isOutput );\r
70 \r
71                         if ( blockNeedsExtension( node, !isOutput, emptyBlockFiller ) )\r
72                         {\r
73                                 if ( isOutput || CKEDITOR.env.ie )\r
74                                         node.add( new CKEDITOR.htmlParser.text( '\xa0' ) );\r
75                                 else\r
76                                         node.add( new CKEDITOR.htmlParser.element( 'br', {} ) );\r
77                         }\r
78                 };\r
79         }\r
80 \r
81         var dtd = CKEDITOR.dtd;\r
82 \r
83         // Find out the list of block-like tags that can contain <br>.\r
84         var blockLikeTags = CKEDITOR.tools.extend( {}, dtd.$block, dtd.$listItem, dtd.$tableContent );\r
85         for ( var i in blockLikeTags )\r
86         {\r
87                 if ( ! ( 'br' in dtd[i] ) )\r
88                         delete blockLikeTags[i];\r
89         }\r
90         // We just avoid filler in <pre> right now.\r
91         // TODO: Support filler for <pre>, line break is also occupy line height.\r
92         delete blockLikeTags.pre;\r
93         var defaultDataFilterRules =\r
94         {\r
95                 elements : {},\r
96                 attributeNames :\r
97                 [\r
98                         // Event attributes (onXYZ) must not be directly set. They can become\r
99                         // active in the editing area (IE|WebKit).\r
100                         [ ( /^on/ ), 'data-cke-pa-on' ]\r
101                 ]\r
102         };\r
103 \r
104         var defaultDataBlockFilterRules = { elements : {} };\r
105 \r
106         for ( i in blockLikeTags )\r
107                 defaultDataBlockFilterRules.elements[ i ] = getBlockExtension();\r
108 \r
109         var defaultHtmlFilterRules =\r
110                 {\r
111                         elementNames :\r
112                         [\r
113                                 // Remove the "cke:" namespace prefix.\r
114                                 [ ( /^cke:/ ), '' ],\r
115 \r
116                                 // Ignore <?xml:namespace> tags.\r
117                                 [ ( /^\?xml:namespace$/ ), '' ]\r
118                         ],\r
119 \r
120                         attributeNames :\r
121                         [\r
122                                 // Attributes saved for changes and protected attributes.\r
123                                 [ ( /^data-cke-(saved|pa)-/ ), '' ],\r
124 \r
125                                 // All "data-cke" attributes are to be ignored.\r
126                                 [ ( /^data-cke.*/ ), '' ],\r
127 \r
128                                 [ 'hidefocus', '' ]\r
129                         ],\r
130 \r
131                         elements :\r
132                         {\r
133                                 $ : function( element )\r
134                                 {\r
135                                         var attribs = element.attributes;\r
136 \r
137                                         if ( attribs )\r
138                                         {\r
139                                                 // Elements marked as temporary are to be ignored.\r
140                                                 if ( attribs[ 'data-cke-temp' ] )\r
141                                                         return false;\r
142 \r
143                                                 // Remove duplicated attributes - #3789.\r
144                                                 var attributeNames = [ 'name', 'href', 'src' ],\r
145                                                         savedAttributeName;\r
146                                                 for ( var i = 0 ; i < attributeNames.length ; i++ )\r
147                                                 {\r
148                                                         savedAttributeName = 'data-cke-saved-' + attributeNames[ i ];\r
149                                                         savedAttributeName in attribs && ( delete attribs[ attributeNames[ i ] ] );\r
150                                                 }\r
151                                         }\r
152 \r
153                                         return element;\r
154                                 },\r
155 \r
156                                 embed : function( element )\r
157                                 {\r
158                                         var parent = element.parent;\r
159 \r
160                                         // If the <embed> is child of a <object>, copy the width\r
161                                         // and height attributes from it.\r
162                                         if ( parent && parent.name == 'object' )\r
163                                         {\r
164                                                 var parentWidth = parent.attributes.width,\r
165                                                         parentHeight = parent.attributes.height;\r
166                                                 parentWidth && ( element.attributes.width = parentWidth );\r
167                                                 parentHeight && ( element.attributes.height = parentHeight );\r
168                                         }\r
169                                 },\r
170                                 // Restore param elements into self-closing.\r
171                                 param : function( param )\r
172                                 {\r
173                                         param.children = [];\r
174                                         param.isEmpty = true;\r
175                                         return param;\r
176                                 },\r
177 \r
178                                 // Remove empty link but not empty anchor.(#3829)\r
179                                 a : function( element )\r
180                                 {\r
181                                         if ( !( element.children.length ||\r
182                                                         element.attributes.name ||\r
183                                                         element.attributes[ 'data-cke-saved-name' ] ) )\r
184                                         {\r
185                                                 return false;\r
186                                         }\r
187                                 },\r
188 \r
189                                 // Remove dummy span in webkit.\r
190                                 span: function( element )\r
191                                 {\r
192                                         if ( element.attributes[ 'class' ] == 'Apple-style-span' )\r
193                                                 delete element.name;\r
194                                 },\r
195 \r
196                                 html : function( element )\r
197                                 {\r
198                                         delete element.attributes.contenteditable;\r
199                                         delete element.attributes[ 'class' ];\r
200                                 },\r
201 \r
202                                 body : function( element )\r
203                                 {\r
204                                         delete element.attributes.spellcheck;\r
205                                         delete element.attributes.contenteditable;\r
206                                 },\r
207 \r
208                                 style : function( element )\r
209                                 {\r
210                                         var child = element.children[ 0 ];\r
211                                         child && child.value && ( child.value = CKEDITOR.tools.trim( child.value ));\r
212 \r
213                                         if ( !element.attributes.type )\r
214                                                 element.attributes.type = 'text/css';\r
215                                 },\r
216 \r
217                                 title : function( element )\r
218                                 {\r
219                                         var titleText = element.children[ 0 ];\r
220                                         titleText && ( titleText.value = element.attributes[ 'data-cke-title' ] || '' );\r
221                                 }\r
222                         },\r
223 \r
224                         attributes :\r
225                         {\r
226                                 'class' : function( value, element )\r
227                                 {\r
228                                         // Remove all class names starting with "cke_".\r
229                                         return CKEDITOR.tools.ltrim( value.replace( /(?:^|\s+)cke_[^\s]*/g, '' ) ) || false;\r
230                                 }\r
231                         },\r
232 \r
233                         comment : function( contents )\r
234                         {\r
235                                 // If this is a comment for protected source.\r
236                                 if ( contents.substr( 0, protectedSourceMarker.length ) == protectedSourceMarker )\r
237                                 {\r
238                                         // Remove the extra marker for real comments from it.\r
239                                         if ( contents.substr( protectedSourceMarker.length, 3 ) == '{C}' )\r
240                                                 contents = contents.substr( protectedSourceMarker.length + 3 );\r
241                                         else\r
242                                                 contents = contents.substr( protectedSourceMarker.length );\r
243 \r
244                                         return new CKEDITOR.htmlParser.cdata( decodeURIComponent( contents ) );\r
245                                 }\r
246 \r
247                                 return contents;\r
248                         }\r
249                 };\r
250 \r
251         if ( CKEDITOR.env.ie )\r
252         {\r
253                 // IE outputs style attribute in capital letters. We should convert\r
254                 // them back to lower case.\r
255                 defaultHtmlFilterRules.attributes.style = function( value, element )\r
256                 {\r
257                         return value.toLowerCase();\r
258                 };\r
259         }\r
260 \r
261         function protectReadOnly( element )\r
262         {\r
263                 element.attributes.contenteditable = "false";\r
264         }\r
265         function unprotectReadyOnly( element )\r
266         {\r
267                 delete element.attributes.contenteditable;\r
268         }\r
269         // Disable form elements editing mode provided by some browers. (#5746)\r
270         for ( i in { input : 1, textarea : 1 } )\r
271         {\r
272                 defaultDataFilterRules.elements[ i ] = protectReadOnly;\r
273                 defaultHtmlFilterRules.elements[ i ] = unprotectReadyOnly;\r
274         }\r
275 \r
276         var protectAttributeRegex = /<((?:a|area|img|input)\b[\s\S]*?\s)((href|src|name)\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|(?:[^ "'>]+)))([^>]*)>/gi,\r
277                 findSavedSrcRegex = /\sdata-cke-saved-src\s*=/;\r
278 \r
279         var protectElementsRegex = /(?:<style(?=[ >])[^>]*>[\s\S]*<\/style>)|(?:<(:?link|meta|base)[^>]*>)/gi,\r
280                 encodedElementsRegex = /<cke:encoded>([^<]*)<\/cke:encoded>/gi;\r
281 \r
282         var protectElementNamesRegex = /(<\/?)((?:object|embed|param|html|body|head|title)[^>]*>)/gi,\r
283                 unprotectElementNamesRegex = /(<\/?)cke:((?:html|body|head|title)[^>]*>)/gi;\r
284 \r
285         var protectSelfClosingRegex = /<cke:(param|embed)([^>]*?)\/?>(?!\s*<\/cke:\1)/gi;\r
286 \r
287         function protectAttributes( html )\r
288         {\r
289                 return html.replace( protectAttributeRegex, function( tag, beginning, fullAttr, attrName, end )\r
290                         {\r
291                                 // We should not rewrite the _cke_saved_src attribute (#5218)\r
292                                 if ( attrName == 'src' && findSavedSrcRegex.test( tag ) )\r
293                                         return tag;\r
294                                 else\r
295                                         return '<' + beginning + fullAttr + ' data-cke-saved-' + fullAttr + end + '>';\r
296                         });\r
297         }\r
298 \r
299         function protectElements( html )\r
300         {\r
301                 return html.replace( protectElementsRegex, function( match )\r
302                         {\r
303                                 return '<cke:encoded>' + encodeURIComponent( match ) + '</cke:encoded>';\r
304                         });\r
305         }\r
306 \r
307         function unprotectElements( html )\r
308         {\r
309                 return html.replace( encodedElementsRegex, function( match, encoded )\r
310                         {\r
311                                 return decodeURIComponent( encoded );\r
312                         });\r
313         }\r
314 \r
315         function protectElementsNames( html )\r
316         {\r
317                 return html.replace( protectElementNamesRegex, '$1cke:$2');\r
318         }\r
319 \r
320         function unprotectElementNames( html )\r
321         {\r
322                 return html.replace( unprotectElementNamesRegex, '$1$2' );\r
323         }\r
324 \r
325         function protectSelfClosingElements( html )\r
326         {\r
327                 return html.replace( protectSelfClosingRegex, '<cke:$1$2></cke:$1>' );\r
328         }\r
329 \r
330         function protectPreFormatted( html )\r
331         {\r
332                 return html.replace( /(<pre\b[^>]*>)(\r\n|\n)/g, '$1$2$2' );\r
333         }\r
334 \r
335         function protectRealComments( html )\r
336         {\r
337                 return html.replace( /<!--(?!{cke_protected})[\s\S]+?-->/g, function( match )\r
338                         {\r
339                                 return '<!--' + protectedSourceMarker +\r
340                                                 '{C}' +\r
341                                                 encodeURIComponent( match ).replace( /--/g, '%2D%2D' ) +\r
342                                                 '-->';\r
343                         });\r
344         }\r
345 \r
346         function unprotectRealComments( html )\r
347         {\r
348                 return html.replace( /<!--\{cke_protected\}\{C\}([\s\S]+?)-->/g, function( match, data )\r
349                         {\r
350                                 return decodeURIComponent( data );\r
351                         });\r
352         }\r
353 \r
354         function protectSource( data, protectRegexes )\r
355         {\r
356                 var protectedHtml = [],\r
357                         tempRegex = /<\!--\{cke_temp(comment)?\}(\d*?)-->/g;\r
358 \r
359                 var regexes =\r
360                         [\r
361                                 // Script tags will also be forced to be protected, otherwise\r
362                                 // IE will execute them.\r
363                                 ( /<script[\s\S]*?<\/script>/gi ),\r
364 \r
365                                 // <noscript> tags (get lost in IE and messed up in FF).\r
366                                 /<noscript[\s\S]*?<\/noscript>/gi\r
367                         ]\r
368                         .concat( protectRegexes );\r
369 \r
370                 // First of any other protection, we must protect all comments\r
371                 // to avoid loosing them (of course, IE related).\r
372                 // Note that we use a different tag for comments, as we need to\r
373                 // transform them when applying filters.\r
374                 data = data.replace( (/<!--[\s\S]*?-->/g), function( match )\r
375                         {\r
376                                 return  '<!--{cke_tempcomment}' + ( protectedHtml.push( match ) - 1 ) + '-->';\r
377                         });\r
378 \r
379                 for ( var i = 0 ; i < regexes.length ; i++ )\r
380                 {\r
381                         data = data.replace( regexes[i], function( match )\r
382                                 {\r
383                                         match = match.replace( tempRegex,               // There could be protected source inside another one. (#3869).\r
384                                                 function( $, isComment, id )\r
385                                                 {\r
386                                                         return protectedHtml[ id ];\r
387                                                 }\r
388                                         );\r
389                                         return  '<!--{cke_temp}' + ( protectedHtml.push( match ) - 1 ) + '-->';\r
390                                 });\r
391                 }\r
392                 data = data.replace( tempRegex, function( $, isComment, id )\r
393                         {\r
394                                 return '<!--' + protectedSourceMarker +\r
395                                                 ( isComment ? '{C}' : '' ) +\r
396                                                 encodeURIComponent( protectedHtml[ id ] ).replace( /--/g, '%2D%2D' ) +\r
397                                                 '-->';\r
398                         }\r
399                 );\r
400                 return data;\r
401         }\r
402 \r
403         CKEDITOR.plugins.add( 'htmldataprocessor',\r
404         {\r
405                 requires : [ 'htmlwriter' ],\r
406 \r
407                 init : function( editor )\r
408                 {\r
409                         var dataProcessor = editor.dataProcessor = new CKEDITOR.htmlDataProcessor( editor );\r
410 \r
411                         dataProcessor.writer.forceSimpleAmpersand = editor.config.forceSimpleAmpersand;\r
412 \r
413                         dataProcessor.dataFilter.addRules( defaultDataFilterRules );\r
414                         dataProcessor.dataFilter.addRules( defaultDataBlockFilterRules );\r
415                         dataProcessor.htmlFilter.addRules( defaultHtmlFilterRules );\r
416 \r
417                         var defaultHtmlBlockFilterRules = { elements : {} };\r
418                         for ( i in blockLikeTags )\r
419                                 defaultHtmlBlockFilterRules.elements[ i ] = getBlockExtension( true, editor.config.fillEmptyBlocks );\r
420 \r
421                         dataProcessor.htmlFilter.addRules( defaultHtmlBlockFilterRules );\r
422                 },\r
423 \r
424                 onLoad : function()\r
425                 {\r
426                         ! ( 'fillEmptyBlocks' in CKEDITOR.config ) && ( CKEDITOR.config.fillEmptyBlocks = 1 );\r
427                 }\r
428         });\r
429 \r
430         CKEDITOR.htmlDataProcessor = function( editor )\r
431         {\r
432                 this.editor = editor;\r
433 \r
434                 this.writer = new CKEDITOR.htmlWriter();\r
435                 this.dataFilter = new CKEDITOR.htmlParser.filter();\r
436                 this.htmlFilter = new CKEDITOR.htmlParser.filter();\r
437         };\r
438 \r
439         CKEDITOR.htmlDataProcessor.prototype =\r
440         {\r
441                 toHtml : function( data, fixForBody )\r
442                 {\r
443                         // The source data is already HTML, but we need to clean\r
444                         // it up and apply the filter.\r
445 \r
446                         data = protectSource( data, this.editor.config.protectedSource );\r
447 \r
448                         // Before anything, we must protect the URL attributes as the\r
449                         // browser may changing them when setting the innerHTML later in\r
450                         // the code.\r
451                         data = protectAttributes( data );\r
452 \r
453                         // Protect elements than can't be set inside a DIV. E.g. IE removes\r
454                         // style tags from innerHTML. (#3710)\r
455                         data = protectElements( data );\r
456 \r
457                         // Certain elements has problem to go through DOM operation, protect\r
458                         // them by prefixing 'cke' namespace. (#3591)\r
459                         data = protectElementsNames( data );\r
460 \r
461                         // All none-IE browsers ignore self-closed custom elements,\r
462                         // protecting them into open-close. (#3591)\r
463                         data = protectSelfClosingElements( data );\r
464 \r
465                         // Compensate one leading line break after <pre> open as browsers\r
466                         // eat it up. (#5789)\r
467                         data = protectPreFormatted( data );\r
468 \r
469                         // Call the browser to help us fixing a possibly invalid HTML\r
470                         // structure.\r
471                         var div = new CKEDITOR.dom.element( 'div' );\r
472                         // Add fake character to workaround IE comments bug. (#3801)\r
473                         div.setHtml( 'a' + data );\r
474                         data = div.getHtml().substr( 1 );\r
475 \r
476                         // Unprotect "some" of the protected elements at this point.\r
477                         data = unprotectElementNames( data );\r
478 \r
479                         data = unprotectElements( data );\r
480 \r
481                         // Restore the comments that have been protected, in this way they\r
482                         // can be properly filtered.\r
483                         data = unprotectRealComments( data );\r
484 \r
485                         // Now use our parser to make further fixes to the structure, as\r
486                         // well as apply the filter.\r
487                         var fragment = CKEDITOR.htmlParser.fragment.fromHtml( data, fixForBody ),\r
488                                 writer = new CKEDITOR.htmlParser.basicWriter();\r
489 \r
490                         fragment.writeHtml( writer, this.dataFilter );\r
491                         data = writer.getHtml( true );\r
492 \r
493                         // Protect the real comments again.\r
494                         data = protectRealComments( data );\r
495 \r
496                         return data;\r
497                 },\r
498 \r
499                 toDataFormat : function( html, fixForBody )\r
500                 {\r
501                         var writer = this.writer,\r
502                                 fragment = CKEDITOR.htmlParser.fragment.fromHtml( html, fixForBody );\r
503 \r
504                         writer.reset();\r
505 \r
506                         fragment.writeHtml( writer, this.htmlFilter );\r
507 \r
508                         return writer.getHtml( true );\r
509                 }\r
510         };\r
511 })();\r
512 \r
513 /**\r
514  * Whether to force using "&" instead of "&amp;amp;" in elements attributes\r
515  * values, it's not recommended to change this setting for compliance with the\r
516  * W3C XHTML 1.0 standards (<a href="http://www.w3.org/TR/xhtml1/#C_12">C.12, XHTML 1.0</a>).\r
517  * @name CKEDITOR.config.forceSimpleAmpersand\r
518  * @name CKEDITOR.config.forceSimpleAmpersand\r
519  * @type Boolean\r
520  * @default false\r
521  * @example\r
522  * config.forceSimpleAmpersand = false;\r
523  */\r
524 \r
525 /**\r
526  * Whether a filler text (non-breaking space entity - &nbsp;) will be inserted into empty block elements in HTML output,\r
527  * this is used to render block elements properly with line-height; When a function is instead specified,\r
528  * it'll be passed a {@link CKEDITOR.htmlParser.element} to decide whether adding the filler text\r
529  * by expecting a boolean return value.\r
530  * @name CKEDITOR.config.fillEmptyBlocks\r
531  * @since 3.5\r
532  * @type Boolean\r
533  * @default true\r
534  * @example\r
535  * config.fillEmptyBlocks = false;      // Prevent filler nodes in all empty blocks.\r
536  *\r
537  * // Prevent filler node only in float cleaners.\r
538  * config.fillEmptyBlocks = function( element )\r
539  * {\r
540  *      if ( element.attributes[ 'class' ].indexOf ( 'clear-both' ) != -1 )\r
541  *              return false;\r
542  * }\r
543  */\r