]> git.donarmstrong.com Git - roundcube.git/blob - program/js/tiny_mce/plugins/paste/editor_plugin_src.js
Imported Upstream version 0.5.2+dfsg
[roundcube.git] / program / js / tiny_mce / plugins / paste / editor_plugin_src.js
1 /**\r
2  * editor_plugin_src.js\r
3  *\r
4  * Copyright 2009, Moxiecode Systems AB\r
5  * Released under LGPL License.\r
6  *\r
7  * License: http://tinymce.moxiecode.com/license\r
8  * Contributing: http://tinymce.moxiecode.com/contributing\r
9  */\r
10 \r
11 (function() {\r
12         var each = tinymce.each,\r
13                 defs = {\r
14                         paste_auto_cleanup_on_paste : true,\r
15                         paste_enable_default_filters : true,\r
16                         paste_block_drop : false,\r
17                         paste_retain_style_properties : "none",\r
18                         paste_strip_class_attributes : "mso",\r
19                         paste_remove_spans : false,\r
20                         paste_remove_styles : false,\r
21                         paste_remove_styles_if_webkit : true,\r
22                         paste_convert_middot_lists : true,\r
23                         paste_convert_headers_to_strong : false,\r
24                         paste_dialog_width : "450",\r
25                         paste_dialog_height : "400",\r
26                         paste_text_use_dialog : false,\r
27                         paste_text_sticky : false,\r
28                         paste_text_sticky_default : false,\r
29                         paste_text_notifyalways : false,\r
30                         paste_text_linebreaktype : "p",\r
31                         paste_text_replacements : [\r
32                                 [/\u2026/g, "..."],\r
33                                 [/[\x93\x94\u201c\u201d]/g, '"'],\r
34                                 [/[\x60\x91\x92\u2018\u2019]/g, "'"]\r
35                         ]\r
36                 };\r
37 \r
38         function getParam(ed, name) {\r
39                 return ed.getParam(name, defs[name]);\r
40         }\r
41 \r
42         tinymce.create('tinymce.plugins.PastePlugin', {\r
43                 init : function(ed, url) {\r
44                         var t = this;\r
45 \r
46                         t.editor = ed;\r
47                         t.url = url;\r
48 \r
49                         // Setup plugin events\r
50                         t.onPreProcess = new tinymce.util.Dispatcher(t);\r
51                         t.onPostProcess = new tinymce.util.Dispatcher(t);\r
52 \r
53                         // Register default handlers\r
54                         t.onPreProcess.add(t._preProcess);\r
55                         t.onPostProcess.add(t._postProcess);\r
56 \r
57                         // Register optional preprocess handler\r
58                         t.onPreProcess.add(function(pl, o) {\r
59                                 ed.execCallback('paste_preprocess', pl, o);\r
60                         });\r
61 \r
62                         // Register optional postprocess\r
63                         t.onPostProcess.add(function(pl, o) {\r
64                                 ed.execCallback('paste_postprocess', pl, o);\r
65                         });\r
66 \r
67                         ed.onKeyDown.addToTop(function(ed, e) {\r
68                                 // Block ctrl+v from adding an undo level since the default logic in tinymce.Editor will add that\r
69                                 if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))\r
70                                         return false; // Stop other listeners\r
71                         });\r
72 \r
73                         // Initialize plain text flag\r
74                         ed.pasteAsPlainText = getParam(ed, 'paste_text_sticky_default');\r
75 \r
76                         // This function executes the process handlers and inserts the contents\r
77                         // force_rich overrides plain text mode set by user, important for pasting with execCommand\r
78                         function process(o, force_rich) {\r
79                                 var dom = ed.dom, rng, nodes;\r
80 \r
81                                 // Execute pre process handlers\r
82                                 t.onPreProcess.dispatch(t, o);\r
83 \r
84                                 // Create DOM structure\r
85                                 o.node = dom.create('div', 0, o.content);\r
86 \r
87                                 // If pasting inside the same element and the contents is only one block\r
88                                 // remove the block and keep the text since Firefox will copy parts of pre and h1-h6 as a pre element\r
89                                 if (tinymce.isGecko) {\r
90                                         rng = ed.selection.getRng(true);\r
91                                         if (rng.startContainer == rng.endContainer && rng.startContainer.nodeType == 3) {\r
92                                                 nodes = dom.select('p,h1,h2,h3,h4,h5,h6,pre', o.node);\r
93 \r
94                                                 // Is only one block node and it doesn't contain word stuff\r
95                                                 if (nodes.length == 1 && o.content.indexOf('__MCE_ITEM__') === -1)\r
96                                                         dom.remove(nodes.reverse(), true);\r
97                                         }\r
98                                 }\r
99 \r
100                                 // Execute post process handlers\r
101                                 t.onPostProcess.dispatch(t, o);\r
102 \r
103                                 // Serialize content\r
104                                 o.content = ed.serializer.serialize(o.node, {getInner : 1});\r
105 \r
106                                 // Plain text option active?\r
107                                 if ((!force_rich) && (ed.pasteAsPlainText)) {\r
108                                         t._insertPlainText(ed, dom, o.content);\r
109 \r
110                                         if (!getParam(ed, "paste_text_sticky")) {\r
111                                                 ed.pasteAsPlainText = false;\r
112                                                 ed.controlManager.setActive("pastetext", false);\r
113                                         }\r
114                                 } else {\r
115                                         t._insert(o.content);\r
116                                 }\r
117                         }\r
118 \r
119                         // Add command for external usage\r
120                         ed.addCommand('mceInsertClipboardContent', function(u, o) {\r
121                                 process(o, true);\r
122                         });\r
123 \r
124                         if (!getParam(ed, "paste_text_use_dialog")) {\r
125                                 ed.addCommand('mcePasteText', function(u, v) {\r
126                                         var cookie = tinymce.util.Cookie;\r
127 \r
128                                         ed.pasteAsPlainText = !ed.pasteAsPlainText;\r
129                                         ed.controlManager.setActive('pastetext', ed.pasteAsPlainText);\r
130 \r
131                                         if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) {\r
132                                                 if (getParam(ed, "paste_text_sticky")) {\r
133                                                         ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));\r
134                                                 } else {\r
135                                                         ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));\r
136                                                 }\r
137 \r
138                                                 if (!getParam(ed, "paste_text_notifyalways")) {\r
139                                                         cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31))\r
140                                                 }\r
141                                         }\r
142                                 });\r
143                         }\r
144 \r
145                         ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'});\r
146                         ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'});\r
147 \r
148                         // This function grabs the contents from the clipboard by adding a\r
149                         // hidden div and placing the caret inside it and after the browser paste\r
150                         // is done it grabs that contents and processes that\r
151                         function grabContent(e) {\r
152                                 var n, or, rng, oldRng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY, textContent;\r
153 \r
154                                 // Check if browser supports direct plaintext access\r
155                                 if (e.clipboardData || dom.doc.dataTransfer) {\r
156                                         textContent = (e.clipboardData || dom.doc.dataTransfer).getData('Text');\r
157 \r
158                                         if (ed.pasteAsPlainText) {\r
159                                                 e.preventDefault();\r
160                                                 process({content : textContent.replace(/\r?\n/g, '<br />')});\r
161                                                 return;\r
162                                         }\r
163                                 }\r
164 \r
165                                 if (dom.get('_mcePaste'))\r
166                                         return;\r
167 \r
168                                 // Create container to paste into\r
169                                 n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste', 'data-mce-bogus' : '1'}, '\uFEFF\uFEFF');\r
170 \r
171                                 // If contentEditable mode we need to find out the position of the closest element\r
172                                 if (body != ed.getDoc().body)\r
173                                         posY = dom.getPos(ed.selection.getStart(), body).y;\r
174                                 else\r
175                                         posY = body.scrollTop + dom.getViewPort().y;\r
176 \r
177                                 // Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles\r
178                                 dom.setStyles(n, {\r
179                                         position : 'absolute',\r
180                                         left : -10000,\r
181                                         top : posY,\r
182                                         width : 1,\r
183                                         height : 1,\r
184                                         overflow : 'hidden'\r
185                                 });\r
186 \r
187                                 if (tinymce.isIE) {\r
188                                         // Store away the old range\r
189                                         oldRng = sel.getRng();\r
190 \r
191                                         // Select the container\r
192                                         rng = dom.doc.body.createTextRange();\r
193                                         rng.moveToElementText(n);\r
194                                         rng.execCommand('Paste');\r
195 \r
196                                         // Remove container\r
197                                         dom.remove(n);\r
198 \r
199                                         // Check if the contents was changed, if it wasn't then clipboard extraction failed probably due\r
200                                         // to IE security settings so we pass the junk though better than nothing right\r
201                                         if (n.innerHTML === '\uFEFF\uFEFF') {\r
202                                                 ed.execCommand('mcePasteWord');\r
203                                                 e.preventDefault();\r
204                                                 return;\r
205                                         }\r
206 \r
207                                         // Restore the old range and clear the contents before pasting\r
208                                         sel.setRng(oldRng);\r
209                                         sel.setContent('');\r
210 \r
211                                         // For some odd reason we need to detach the the mceInsertContent call from the paste event\r
212                                         // It's like IE has a reference to the parent element that you paste in and the selection gets messed up\r
213                                         // when it tries to restore the selection\r
214                                         setTimeout(function() {\r
215                                                 // Process contents\r
216                                                 process({content : n.innerHTML});\r
217                                         }, 0);\r
218 \r
219                                         // Block the real paste event\r
220                                         return tinymce.dom.Event.cancel(e);\r
221                                 } else {\r
222                                         function block(e) {\r
223                                                 e.preventDefault();\r
224                                         };\r
225 \r
226                                         // Block mousedown and click to prevent selection change\r
227                                         dom.bind(ed.getDoc(), 'mousedown', block);\r
228                                         dom.bind(ed.getDoc(), 'keydown', block);\r
229 \r
230                                         or = ed.selection.getRng();\r
231 \r
232                                         // Move select contents inside DIV\r
233                                         n = n.firstChild;\r
234                                         rng = ed.getDoc().createRange();\r
235                                         rng.setStart(n, 0);\r
236                                         rng.setEnd(n, 2);\r
237                                         sel.setRng(rng);\r
238 \r
239                                         // Wait a while and grab the pasted contents\r
240                                         window.setTimeout(function() {\r
241                                                 var h = '', nl;\r
242 \r
243                                                 // Paste divs duplicated in paste divs seems to happen when you paste plain text so lets first look for that broken behavior in WebKit\r
244                                                 if (!dom.select('div.mcePaste > div.mcePaste').length) {\r
245                                                         nl = dom.select('div.mcePaste');\r
246 \r
247                                                         // WebKit will split the div into multiple ones so this will loop through then all and join them to get the whole HTML string\r
248                                                         each(nl, function(n) {\r
249                                                                 var child = n.firstChild;\r
250 \r
251                                                                 // WebKit inserts a DIV container with lots of odd styles\r
252                                                                 if (child && child.nodeName == 'DIV' && child.style.marginTop && child.style.backgroundColor) {\r
253                                                                         dom.remove(child, 1);\r
254                                                                 }\r
255 \r
256                                                                 // Remove apply style spans\r
257                                                                 each(dom.select('span.Apple-style-span', n), function(n) {\r
258                                                                         dom.remove(n, 1);\r
259                                                                 });\r
260 \r
261                                                                 // Remove bogus br elements\r
262                                                                 each(dom.select('br[data-mce-bogus]', n), function(n) {\r
263                                                                         dom.remove(n);\r
264                                                                 });\r
265 \r
266                                                                 // WebKit will make a copy of the DIV for each line of plain text pasted and insert them into the DIV\r
267                                                                 if (n.parentNode.className != 'mcePaste')\r
268                                                                         h += n.innerHTML;\r
269                                                         });\r
270                                                 } else {\r
271                                                         // Found WebKit weirdness so force the content into plain text mode\r
272                                                         h = '<pre>' + dom.encode(textContent).replace(/\r?\n/g, '<br />') + '</pre>';\r
273                                                 }\r
274 \r
275                                                 // Remove the nodes\r
276                                                 each(dom.select('div.mcePaste'), function(n) {\r
277                                                         dom.remove(n);\r
278                                                 });\r
279 \r
280                                                 // Restore the old selection\r
281                                                 if (or)\r
282                                                         sel.setRng(or);\r
283 \r
284                                                 process({content : h});\r
285 \r
286                                                 // Unblock events ones we got the contents\r
287                                                 dom.unbind(ed.getDoc(), 'mousedown', block);\r
288                                                 dom.unbind(ed.getDoc(), 'keydown', block);\r
289                                         }, 0);\r
290                                 }\r
291                         }\r
292 \r
293                         // Check if we should use the new auto process method                   \r
294                         if (getParam(ed, "paste_auto_cleanup_on_paste")) {\r
295                                 // Is it's Opera or older FF use key handler\r
296                                 if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) {\r
297                                         ed.onKeyDown.addToTop(function(ed, e) {\r
298                                                 if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))\r
299                                                         grabContent(e);\r
300                                         });\r
301                                 } else {\r
302                                         // Grab contents on paste event on Gecko and WebKit\r
303                                         ed.onPaste.addToTop(function(ed, e) {\r
304                                                 return grabContent(e);\r
305                                         });\r
306                                 }\r
307                         }\r
308 \r
309                         ed.onInit.add(function() {\r
310                                 ed.controlManager.setActive("pastetext", ed.pasteAsPlainText);\r
311 \r
312                                 // Block all drag/drop events\r
313                                 if (getParam(ed, "paste_block_drop")) {\r
314                                         ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) {\r
315                                                 e.preventDefault();\r
316                                                 e.stopPropagation();\r
317 \r
318                                                 return false;\r
319                                         });\r
320                                 }\r
321                         });\r
322 \r
323                         // Add legacy support\r
324                         t._legacySupport();\r
325                 },\r
326 \r
327                 getInfo : function() {\r
328                         return {\r
329                                 longname : 'Paste text/word',\r
330                                 author : 'Moxiecode Systems AB',\r
331                                 authorurl : 'http://tinymce.moxiecode.com',\r
332                                 infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste',\r
333                                 version : tinymce.majorVersion + "." + tinymce.minorVersion\r
334                         };\r
335                 },\r
336 \r
337                 _preProcess : function(pl, o) {\r
338                         var ed = this.editor,\r
339                                 h = o.content,\r
340                                 grep = tinymce.grep,\r
341                                 explode = tinymce.explode,\r
342                                 trim = tinymce.trim,\r
343                                 len, stripClass;\r
344 \r
345                         //console.log('Before preprocess:' + o.content);\r
346 \r
347                         function process(items) {\r
348                                 each(items, function(v) {\r
349                                         // Remove or replace\r
350                                         if (v.constructor == RegExp)\r
351                                                 h = h.replace(v, '');\r
352                                         else\r
353                                                 h = h.replace(v[0], v[1]);\r
354                                 });\r
355                         }\r
356                         \r
357                         if (ed.settings.paste_enable_default_filters == false) {\r
358                                 return;\r
359                         }\r
360 \r
361                         // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser\r
362                         if (tinymce.isIE && document.documentMode >= 9)\r
363                                 process([[/(?:<br>&nbsp;[\s\r\n]+|<br>)*(<\/?(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)[^>]*>)(?:<br>&nbsp;[\s\r\n]+|<br>)*/g, '$1']]);\r
364 \r
365                         // Detect Word content and process it more aggressive\r
366                         if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) {\r
367                                 o.wordContent = true;                   // Mark the pasted contents as word specific content\r
368                                 //console.log('Word contents detected.');\r
369 \r
370                                 // Process away some basic content\r
371                                 process([\r
372                                         /^\s*(&nbsp;)+/gi,                              // &nbsp; entities at the start of contents\r
373                                         /(&nbsp;|<br[^>]*>)+\s*$/gi             // &nbsp; entities at the end of contents\r
374                                 ]);\r
375 \r
376                                 if (getParam(ed, "paste_convert_headers_to_strong")) {\r
377                                         h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>");\r
378                                 }\r
379 \r
380                                 if (getParam(ed, "paste_convert_middot_lists")) {\r
381                                         process([\r
382                                                 [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'],                                    // Convert supportLists to a list item marker\r
383                                                 [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'],             // Convert mso-list and symbol spans to item markers\r
384                                                 [/(<p[^>]+(?:MsoListParagraph)[^>]+>)/gi, '$1__MCE_ITEM__']                             // Convert mso-list and symbol paragraphs to item markers (FF)\r
385                                         ]);\r
386                                 }\r
387 \r
388                                 process([\r
389                                         // Word comments like conditional comments etc\r
390                                         /<!--[\s\S]+?-->/gi,\r
391 \r
392                                         // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags\r
393                                         /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,\r
394 \r
395                                         // Convert <s> into <strike> for line-though\r
396                                         [/<(\/?)s>/gi, "<$1strike>"],\r
397 \r
398                                         // Replace nsbp entites to char since it's easier to handle\r
399                                         [/&nbsp;/gi, "\u00a0"]\r
400                                 ]);\r
401 \r
402                                 // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag.\r
403                                 // If JavaScript had a RegExp look-behind, we could have integrated this with the last process() array and got rid of the loop. But alas, it does not, so we cannot.\r
404                                 do {\r
405                                         len = h.length;\r
406                                         h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1");\r
407                                 } while (len != h.length);\r
408 \r
409                                 // Remove all spans if no styles is to be retained\r
410                                 if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) {\r
411                                         h = h.replace(/<\/?span[^>]*>/gi, "");\r
412                                 } else {\r
413                                         // We're keeping styles, so at least clean them up.\r
414                                         // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx\r
415 \r
416                                         process([\r
417                                                 // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length\r
418                                                 [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,\r
419                                                         function(str, spaces) {\r
420                                                                 return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : "";\r
421                                                         }\r
422                                                 ],\r
423 \r
424                                                 // Examine all styles: delete junk, transform some, and keep the rest\r
425                                                 [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi,\r
426                                                         function(str, tag, style) {\r
427                                                                 var n = [],\r
428                                                                         i = 0,\r
429                                                                         s = explode(trim(style).replace(/&quot;/gi, "'"), ";");\r
430 \r
431                                                                 // Examine each style definition within the tag's style attribute\r
432                                                                 each(s, function(v) {\r
433                                                                         var name, value,\r
434                                                                                 parts = explode(v, ":");\r
435 \r
436                                                                         function ensureUnits(v) {\r
437                                                                                 return v + ((v !== "0") && (/\d$/.test(v)))? "px" : "";\r
438                                                                         }\r
439 \r
440                                                                         if (parts.length == 2) {\r
441                                                                                 name = parts[0].toLowerCase();\r
442                                                                                 value = parts[1].toLowerCase();\r
443 \r
444                                                                                 // Translate certain MS Office styles into their CSS equivalents\r
445                                                                                 switch (name) {\r
446                                                                                         case "mso-padding-alt":\r
447                                                                                         case "mso-padding-top-alt":\r
448                                                                                         case "mso-padding-right-alt":\r
449                                                                                         case "mso-padding-bottom-alt":\r
450                                                                                         case "mso-padding-left-alt":\r
451                                                                                         case "mso-margin-alt":\r
452                                                                                         case "mso-margin-top-alt":\r
453                                                                                         case "mso-margin-right-alt":\r
454                                                                                         case "mso-margin-bottom-alt":\r
455                                                                                         case "mso-margin-left-alt":\r
456                                                                                         case "mso-table-layout-alt":\r
457                                                                                         case "mso-height":\r
458                                                                                         case "mso-width":\r
459                                                                                         case "mso-vertical-align-alt":\r
460                                                                                                 n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value);\r
461                                                                                                 return;\r
462 \r
463                                                                                         case "horiz-align":\r
464                                                                                                 n[i++] = "text-align:" + value;\r
465                                                                                                 return;\r
466 \r
467                                                                                         case "vert-align":\r
468                                                                                                 n[i++] = "vertical-align:" + value;\r
469                                                                                                 return;\r
470 \r
471                                                                                         case "font-color":\r
472                                                                                         case "mso-foreground":\r
473                                                                                                 n[i++] = "color:" + value;\r
474                                                                                                 return;\r
475 \r
476                                                                                         case "mso-background":\r
477                                                                                         case "mso-highlight":\r
478                                                                                                 n[i++] = "background:" + value;\r
479                                                                                                 return;\r
480 \r
481                                                                                         case "mso-default-height":\r
482                                                                                                 n[i++] = "min-height:" + ensureUnits(value);\r
483                                                                                                 return;\r
484 \r
485                                                                                         case "mso-default-width":\r
486                                                                                                 n[i++] = "min-width:" + ensureUnits(value);\r
487                                                                                                 return;\r
488 \r
489                                                                                         case "mso-padding-between-alt":\r
490                                                                                                 n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value);\r
491                                                                                                 return;\r
492 \r
493                                                                                         case "text-line-through":\r
494                                                                                                 if ((value == "single") || (value == "double")) {\r
495                                                                                                         n[i++] = "text-decoration:line-through";\r
496                                                                                                 }\r
497                                                                                                 return;\r
498 \r
499                                                                                         case "mso-zero-height":\r
500                                                                                                 if (value == "yes") {\r
501                                                                                                         n[i++] = "display:none";\r
502                                                                                                 }\r
503                                                                                                 return;\r
504                                                                                 }\r
505 \r
506                                                                                 // Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name\r
507                                                                                 if (/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?!align|decor|indent|trans)|top-bar|version|vnd|word-break)/.test(name)) {\r
508                                                                                         return;\r
509                                                                                 }\r
510 \r
511                                                                                 // If it reached this point, it must be a valid CSS style\r
512                                                                                 n[i++] = name + ":" + parts[1];         // Lower-case name, but keep value case\r
513                                                                         }\r
514                                                                 });\r
515 \r
516                                                                 // If style attribute contained any valid styles the re-write it; otherwise delete style attribute.\r
517                                                                 if (i > 0) {\r
518                                                                         return tag + ' style="' + n.join(';') + '"';\r
519                                                                 } else {\r
520                                                                         return tag;\r
521                                                                 }\r
522                                                         }\r
523                                                 ]\r
524                                         ]);\r
525                                 }\r
526                         }\r
527 \r
528                         // Replace headers with <strong>\r
529                         if (getParam(ed, "paste_convert_headers_to_strong")) {\r
530                                 process([\r
531                                         [/<h[1-6][^>]*>/gi, "<p><strong>"],\r
532                                         [/<\/h[1-6][^>]*>/gi, "</strong></p>"]\r
533                                 ]);\r
534                         }\r
535 \r
536                         process([\r
537                                 // Copy paste from Java like Open Office will produce this junk on FF\r
538                                 [/Version:[\d.]+\nStartHTML:\d+\nEndHTML:\d+\nStartFragment:\d+\nEndFragment:\d+/gi, '']\r
539                         ]);\r
540 \r
541                         // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso").\r
542                         // Note:-  paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation.\r
543                         stripClass = getParam(ed, "paste_strip_class_attributes");\r
544 \r
545                         if (stripClass !== "none") {\r
546                                 function removeClasses(match, g1) {\r
547                                                 if (stripClass === "all")\r
548                                                         return '';\r
549 \r
550                                                 var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "),\r
551                                                         function(v) {\r
552                                                                 return (/^(?!mso)/i.test(v));\r
553                                                         }\r
554                                                 );\r
555 \r
556                                                 return cls.length ? ' class="' + cls.join(" ") + '"' : '';\r
557                                 };\r
558 \r
559                                 h = h.replace(/ class="([^"]+)"/gi, removeClasses);\r
560                                 h = h.replace(/ class=([\-\w]+)/gi, removeClasses);\r
561                         }\r
562 \r
563                         // Remove spans option\r
564                         if (getParam(ed, "paste_remove_spans")) {\r
565                                 h = h.replace(/<\/?span[^>]*>/gi, "");\r
566                         }\r
567 \r
568                         //console.log('After preprocess:' + h);\r
569 \r
570                         o.content = h;\r
571                 },\r
572 \r
573                 /**\r
574                  * Various post process items.\r
575                  */\r
576                 _postProcess : function(pl, o) {\r
577                         var t = this, ed = t.editor, dom = ed.dom, styleProps;\r
578 \r
579                         if (ed.settings.paste_enable_default_filters == false) {\r
580                                 return;\r
581                         }\r
582                         \r
583                         if (o.wordContent) {\r
584                                 // Remove named anchors or TOC links\r
585                                 each(dom.select('a', o.node), function(a) {\r
586                                         if (!a.href || a.href.indexOf('#_Toc') != -1)\r
587                                                 dom.remove(a, 1);\r
588                                 });\r
589 \r
590                                 if (getParam(ed, "paste_convert_middot_lists")) {\r
591                                         t._convertLists(pl, o);\r
592                                 }\r
593 \r
594                                 // Process styles\r
595                                 styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties\r
596 \r
597                                 // Process only if a string was specified and not equal to "all" or "*"\r
598                                 if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) {\r
599                                         styleProps = tinymce.explode(styleProps.replace(/^none$/i, ""));\r
600 \r
601                                         // Retains some style properties\r
602                                         each(dom.select('*', o.node), function(el) {\r
603                                                 var newStyle = {}, npc = 0, i, sp, sv;\r
604 \r
605                                                 // Store a subset of the existing styles\r
606                                                 if (styleProps) {\r
607                                                         for (i = 0; i < styleProps.length; i++) {\r
608                                                                 sp = styleProps[i];\r
609                                                                 sv = dom.getStyle(el, sp);\r
610 \r
611                                                                 if (sv) {\r
612                                                                         newStyle[sp] = sv;\r
613                                                                         npc++;\r
614                                                                 }\r
615                                                         }\r
616                                                 }\r
617 \r
618                                                 // Remove all of the existing styles\r
619                                                 dom.setAttrib(el, 'style', '');\r
620 \r
621                                                 if (styleProps && npc > 0)\r
622                                                         dom.setStyles(el, newStyle); // Add back the stored subset of styles\r
623                                                 else // Remove empty span tags that do not have class attributes\r
624                                                         if (el.nodeName == 'SPAN' && !el.className)\r
625                                                                 dom.remove(el, true);\r
626                                         });\r
627                                 }\r
628                         }\r
629 \r
630                         // Remove all style information or only specifically on WebKit to avoid the style bug on that browser\r
631                         if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) {\r
632                                 each(dom.select('*[style]', o.node), function(el) {\r
633                                         el.removeAttribute('style');\r
634                                         el.removeAttribute('data-mce-style');\r
635                                 });\r
636                         } else {\r
637                                 if (tinymce.isWebKit) {\r
638                                         // We need to compress the styles on WebKit since if you paste <img border="0" /> it will become <img border="0" style="... lots of junk ..." />\r
639                                         // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles\r
640                                         each(dom.select('*', o.node), function(el) {\r
641                                                 el.removeAttribute('data-mce-style');\r
642                                         });\r
643                                 }\r
644                         }\r
645                 },\r
646 \r
647                 /**\r
648                  * Converts the most common bullet and number formats in Office into a real semantic UL/LI list.\r
649                  */\r
650                 _convertLists : function(pl, o) {\r
651                         var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html;\r
652 \r
653                         // Convert middot lists into real semantic lists\r
654                         each(dom.select('p', o.node), function(p) {\r
655                                 var sib, val = '', type, html, idx, parents;\r
656 \r
657                                 // Get text node value at beginning of paragraph\r
658                                 for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling)\r
659                                         val += sib.nodeValue;\r
660 \r
661                                 val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/&nbsp;/g, '\u00a0');\r
662 \r
663                                 // Detect unordered lists look for bullets\r
664                                 if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(val))\r
665                                         type = 'ul';\r
666 \r
667                                 // Detect ordered lists 1., a. or ixv.\r
668                                 if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(val))\r
669                                         type = 'ol';\r
670 \r
671                                 // Check if node value matches the list pattern: o&nbsp;&nbsp;\r
672                                 if (type) {\r
673                                         margin = parseFloat(p.style.marginLeft || 0);\r
674 \r
675                                         if (margin > lastMargin)\r
676                                                 levels.push(margin);\r
677 \r
678                                         if (!listElm || type != lastType) {\r
679                                                 listElm = dom.create(type);\r
680                                                 dom.insertAfter(listElm, p);\r
681                                         } else {\r
682                                                 // Nested list element\r
683                                                 if (margin > lastMargin) {\r
684                                                         listElm = li.appendChild(dom.create(type));\r
685                                                 } else if (margin < lastMargin) {\r
686                                                         // Find parent level based on margin value\r
687                                                         idx = tinymce.inArray(levels, margin);\r
688                                                         parents = dom.getParents(listElm.parentNode, type);\r
689                                                         listElm = parents[parents.length - 1 - idx] || listElm;\r
690                                                 }\r
691                                         }\r
692 \r
693                                         // Remove middot or number spans if they exists\r
694                                         each(dom.select('span', p), function(span) {\r
695                                                 var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, '');\r
696 \r
697                                                 // Remove span with the middot or the number\r
698                                                 if (type == 'ul' && /^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(html))\r
699                                                         dom.remove(span);\r
700                                                 else if (/^__MCE_ITEM__[\s\S]*\w+\.(&nbsp;|\u00a0)*\s*/.test(html))\r
701                                                         dom.remove(span);\r
702                                         });\r
703 \r
704                                         html = p.innerHTML;\r
705 \r
706                                         // Remove middot/list items\r
707                                         if (type == 'ul')\r
708                                                 html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*(&nbsp;|\u00a0)+\s*/, '');\r
709                                         else\r
710                                                 html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.(&nbsp;|\u00a0)+\s*/, '');\r
711 \r
712                                         // Create li and add paragraph data into the new li\r
713                                         li = listElm.appendChild(dom.create('li', 0, html));\r
714                                         dom.remove(p);\r
715 \r
716                                         lastMargin = margin;\r
717                                         lastType = type;\r
718                                 } else\r
719                                         listElm = lastMargin = 0; // End list element\r
720                         });\r
721 \r
722                         // Remove any left over makers\r
723                         html = o.node.innerHTML;\r
724                         if (html.indexOf('__MCE_ITEM__') != -1)\r
725                                 o.node.innerHTML = html.replace(/__MCE_ITEM__/g, '');\r
726                 },\r
727 \r
728                 /**\r
729                  * Inserts the specified contents at the caret position.\r
730                  */\r
731                 _insert : function(h, skip_undo) {\r
732                         var ed = this.editor, r = ed.selection.getRng();\r
733 \r
734                         // First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells.\r
735                         if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer)\r
736                                 ed.getDoc().execCommand('Delete', false, null);\r
737 \r
738                         ed.execCommand('mceInsertContent', false, h, {skip_undo : skip_undo});\r
739                 },\r
740 \r
741                 /**\r
742                  * Instead of the old plain text method which tried to re-create a paste operation, the\r
743                  * new approach adds a plain text mode toggle switch that changes the behavior of paste.\r
744                  * This function is passed the same input that the regular paste plugin produces.\r
745                  * It performs additional scrubbing and produces (and inserts) the plain text.\r
746                  * This approach leverages all of the great existing functionality in the paste\r
747                  * plugin, and requires minimal changes to add the new functionality.\r
748                  * Speednet - June 2009\r
749                  */\r
750                 _insertPlainText : function(ed, dom, h) {\r
751                         var i, len, pos, rpos, node, breakElms, before, after,\r
752                                 w = ed.getWin(),\r
753                                 d = ed.getDoc(),\r
754                                 sel = ed.selection,\r
755                                 is = tinymce.is,\r
756                                 inArray = tinymce.inArray,\r
757                                 linebr = getParam(ed, "paste_text_linebreaktype"),\r
758                                 rl = getParam(ed, "paste_text_replacements");\r
759 \r
760                         function process(items) {\r
761                                 each(items, function(v) {\r
762                                         if (v.constructor == RegExp)\r
763                                                 h = h.replace(v, "");\r
764                                         else\r
765                                                 h = h.replace(v[0], v[1]);\r
766                                 });\r
767                         };\r
768 \r
769                         if ((typeof(h) === "string") && (h.length > 0)) {\r
770                                 // If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line\r
771                                 if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(h)) {\r
772                                         process([\r
773                                                 /[\n\r]+/g\r
774                                         ]);\r
775                                 } else {\r
776                                         // Otherwise just get rid of carriage returns (only need linefeeds)\r
777                                         process([\r
778                                                 /\r+/g\r
779                                         ]);\r
780                                 }\r
781 \r
782                                 process([\r
783                                         [/<\/(?:p|h[1-6]|ul|ol|dl|table|div|blockquote|fieldset|pre|address|center)>/gi, "\n\n"],               // Block tags get a blank line after them\r
784                                         [/<br[^>]*>|<\/tr>/gi, "\n"],                           // Single linebreak for <br /> tags and table rows\r
785                                         [/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"],           // Table cells get tabs betweem them\r
786                                         /<[a-z!\/?][^>]*>/gi,                                           // Delete all remaining tags\r
787                                         [/&nbsp;/gi, " "],                                                      // Convert non-break spaces to regular spaces (remember, *plain text*)\r
788                                         [/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"],    // Cool little RegExp deletes whitespace around linebreak chars.\r
789                                         [/\n{3,}/g, "\n\n"],                                                    // Max. 2 consecutive linebreaks\r
790                                         /^\s+|\s+$/g                                                                    // Trim the front & back\r
791                                 ]);\r
792 \r
793                                 h = dom.decode(tinymce.html.Entities.encodeRaw(h));\r
794 \r
795                                 // Delete any highlighted text before pasting\r
796                                 if (!sel.isCollapsed()) {\r
797                                         d.execCommand("Delete", false, null);\r
798                                 }\r
799 \r
800                                 // Perform default or custom replacements\r
801                                 if (is(rl, "array") || (is(rl, "array"))) {\r
802                                         process(rl);\r
803                                 }\r
804                                 else if (is(rl, "string")) {\r
805                                         process(new RegExp(rl, "gi"));\r
806                                 }\r
807 \r
808                                 // Treat paragraphs as specified in the config\r
809                                 if (linebr == "none") {\r
810                                         process([\r
811                                                 [/\n+/g, " "]\r
812                                         ]);\r
813                                 }\r
814                                 else if (linebr == "br") {\r
815                                         process([\r
816                                                 [/\n/g, "<br />"]\r
817                                         ]);\r
818                                 }\r
819                                 else {\r
820                                         process([\r
821                                                 /^\s+|\s+$/g,\r
822                                                 [/\n\n/g, "</p><p>"],\r
823                                                 [/\n/g, "<br />"]\r
824                                         ]);\r
825                                 }\r
826 \r
827                                 // This next piece of code handles the situation where we're pasting more than one paragraph of plain\r
828                                 // text, and we are pasting the content into the middle of a block node in the editor.  The block\r
829                                 // node gets split at the selection point into "Para A" and "Para B" (for the purposes of explaining).\r
830                                 // The first paragraph of the pasted text is appended to "Para A", and the last paragraph of the\r
831                                 // pasted text is prepended to "Para B".  Any other paragraphs of pasted text are placed between\r
832                                 // "Para A" and "Para B".  This code solves a host of problems with the original plain text plugin and\r
833                                 // now handles styles correctly.  (Pasting plain text into a styled paragraph is supposed to make the\r
834                                 // plain text take the same style as the existing paragraph.)\r
835                                 if ((pos = h.indexOf("</p><p>")) != -1) {\r
836                                         rpos = h.lastIndexOf("</p><p>");\r
837                                         node = sel.getNode(); \r
838                                         breakElms = [];         // Get list of elements to break \r
839 \r
840                                         do {\r
841                                                 if (node.nodeType == 1) {\r
842                                                         // Don't break tables and break at body\r
843                                                         if (node.nodeName == "TD" || node.nodeName == "BODY") {\r
844                                                                 break;\r
845                                                         }\r
846 \r
847                                                         breakElms[breakElms.length] = node;\r
848                                                 }\r
849                                         } while (node = node.parentNode);\r
850 \r
851                                         // Are we in the middle of a block node?\r
852                                         if (breakElms.length > 0) {\r
853                                                 before = h.substring(0, pos);\r
854                                                 after = "";\r
855 \r
856                                                 for (i=0, len=breakElms.length; i<len; i++) {\r
857                                                         before += "</" + breakElms[i].nodeName.toLowerCase() + ">";\r
858                                                         after += "<" + breakElms[breakElms.length-i-1].nodeName.toLowerCase() + ">";\r
859                                                 }\r
860 \r
861                                                 if (pos == rpos) {\r
862                                                         h = before + after + h.substring(pos+7);\r
863                                                 }\r
864                                                 else {\r
865                                                         h = before + h.substring(pos+4, rpos+4) + after + h.substring(rpos+7);\r
866                                                 }\r
867                                         }\r
868                                 }\r
869 \r
870                                 // Insert content at the caret, plus add a marker for repositioning the caret\r
871                                 ed.execCommand("mceInsertRawHTML", false, h + '<span id="_plain_text_marker">&nbsp;</span>');\r
872 \r
873                                 // Reposition the caret to the marker, which was placed immediately after the inserted content.\r
874                                 // Needs to be done asynchronously (in window.setTimeout) or else it doesn't work in all browsers.\r
875                                 // The second part of the code scrolls the content up if the caret is positioned off-screen.\r
876                                 // This is only necessary for WebKit browsers, but it doesn't hurt to use for all.\r
877                                 window.setTimeout(function() {\r
878                                         var marker = dom.get('_plain_text_marker'),\r
879                                                 elm, vp, y, elmHeight;\r
880 \r
881                                         sel.select(marker, false);\r
882                                         d.execCommand("Delete", false, null);\r
883                                         marker = null;\r
884 \r
885                                         // Get element, position and height\r
886                                         elm = sel.getStart();\r
887                                         vp = dom.getViewPort(w);\r
888                                         y = dom.getPos(elm).y;\r
889                                         elmHeight = elm.clientHeight;\r
890 \r
891                                         // Is element within viewport if not then scroll it into view\r
892                                         if ((y < vp.y) || (y + elmHeight > vp.y + vp.h)) {\r
893                                                 d.body.scrollTop = y < vp.y ? y : y - vp.h + 25;\r
894                                         }\r
895                                 }, 0);\r
896                         }\r
897                 },\r
898 \r
899                 /**\r
900                  * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine.\r
901                  */\r
902                 _legacySupport : function() {\r
903                         var t = this, ed = t.editor;\r
904 \r
905                         // Register command(s) for backwards compatibility\r
906                         ed.addCommand("mcePasteWord", function() {\r
907                                 ed.windowManager.open({\r
908                                         file: t.url + "/pasteword.htm",\r
909                                         width: parseInt(getParam(ed, "paste_dialog_width")),\r
910                                         height: parseInt(getParam(ed, "paste_dialog_height")),\r
911                                         inline: 1\r
912                                 });\r
913                         });\r
914 \r
915                         if (getParam(ed, "paste_text_use_dialog")) {\r
916                                 ed.addCommand("mcePasteText", function() {\r
917                                         ed.windowManager.open({\r
918                                                 file : t.url + "/pastetext.htm",\r
919                                                 width: parseInt(getParam(ed, "paste_dialog_width")),\r
920                                                 height: parseInt(getParam(ed, "paste_dialog_height")),\r
921                                                 inline : 1\r
922                                         });\r
923                                 });\r
924                         }\r
925 \r
926                         // Register button for backwards compatibility\r
927                         ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"});\r
928                 }\r
929         });\r
930 \r
931         // Register plugin\r
932         tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin);\r
933 })();\r