]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/tinymce/plugins/paste/plugin.js
WordPress 3.9-scripts
[autoinstalls/wordpress.git] / wp-includes / js / tinymce / plugins / paste / plugin.js
1 /**
2  * Compiled inline version. (Library mode)
3  */
4
5 /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
6 /*globals $code */
7
8 (function(exports, undefined) {
9         "use strict";
10
11         var modules = {};
12
13         function require(ids, callback) {
14                 var module, defs = [];
15
16                 for (var i = 0; i < ids.length; ++i) {
17                         module = modules[ids[i]] || resolve(ids[i]);
18                         if (!module) {
19                                 throw 'module definition dependecy not found: ' + ids[i];
20                         }
21
22                         defs.push(module);
23                 }
24
25                 callback.apply(null, defs);
26         }
27
28         function define(id, dependencies, definition) {
29                 if (typeof id !== 'string') {
30                         throw 'invalid module definition, module id must be defined and be a string';
31                 }
32
33                 if (dependencies === undefined) {
34                         throw 'invalid module definition, dependencies must be specified';
35                 }
36
37                 if (definition === undefined) {
38                         throw 'invalid module definition, definition function must be specified';
39                 }
40
41                 require(dependencies, function() {
42                         modules[id] = definition.apply(null, arguments);
43                 });
44         }
45
46         function defined(id) {
47                 return !!modules[id];
48         }
49
50         function resolve(id) {
51                 var target = exports;
52                 var fragments = id.split(/[.\/]/);
53
54                 for (var fi = 0; fi < fragments.length; ++fi) {
55                         if (!target[fragments[fi]]) {
56                                 return;
57                         }
58
59                         target = target[fragments[fi]];
60                 }
61
62                 return target;
63         }
64
65         function expose(ids) {
66                 for (var i = 0; i < ids.length; i++) {
67                         var target = exports;
68                         var id = ids[i];
69                         var fragments = id.split(/[.\/]/);
70
71                         for (var fi = 0; fi < fragments.length - 1; ++fi) {
72                                 if (target[fragments[fi]] === undefined) {
73                                         target[fragments[fi]] = {};
74                                 }
75
76                                 target = target[fragments[fi]];
77                         }
78
79                         target[fragments[fragments.length - 1]] = modules[id];
80                 }
81         }
82
83 // Included from: js/tinymce/plugins/paste/classes/Utils.js
84
85 /**
86  * Utils.js
87  *
88  * Copyright, Moxiecode Systems AB
89  * Released under LGPL License.
90  *
91  * License: http://www.tinymce.com/license
92  * Contributing: http://www.tinymce.com/contributing
93  */
94
95 /**
96  * This class contails various utility functions for the paste plugin.
97  *
98  * @class tinymce.pasteplugin.Clipboard
99  * @private
100  */
101 define("tinymce/pasteplugin/Utils", [
102         "tinymce/util/Tools",
103         "tinymce/html/DomParser",
104         "tinymce/html/Schema"
105 ], function(Tools, DomParser, Schema) {
106         function filter(content, items) {
107                 Tools.each(items, function(v) {
108                         if (v.constructor == RegExp) {
109                                 content = content.replace(v, '');
110                         } else {
111                                 content = content.replace(v[0], v[1]);
112                         }
113                 });
114
115                 return content;
116         }
117
118         /**
119          * Gets the innerText of the specified element. It will handle edge cases
120          * and works better than textContent on Gecko.
121          *
122          * @param {String} html HTML string to get text from.
123          * @return {String} String of text with line feeds.
124          */
125         function innerText(html) {
126                 var schema = new Schema(), domParser = new DomParser({}, schema), text = '';
127                 var shortEndedElements = schema.getShortEndedElements();
128                 var ignoreElements = Tools.makeMap('script noscript style textarea video audio iframe object', ' ');
129                 var blockElements = schema.getBlockElements();
130
131                 function walk(node) {
132                         var name = node.name, currentNode = node;
133
134                         if (name === 'br') {
135                                 text += '\n';
136                                 return;
137                         }
138
139                         // img/input/hr
140                         if (shortEndedElements[name]) {
141                                 text += ' ';
142                         }
143
144                         // Ingore script, video contents
145                         if (ignoreElements[name]) {
146                                 text += ' ';
147                                 return;
148                         }
149
150                         if (node.type == 3) {
151                                 text += node.value;
152                         }
153
154                         // Walk all children
155                         if (!node.shortEnded) {
156                                 if ((node = node.firstChild)) {
157                                         do {
158                                                 walk(node);
159                                         } while ((node = node.next));
160                                 }
161                         }
162
163                         // Add \n or \n\n for blocks or P
164                         if (blockElements[name] && currentNode.next) {
165                                 text += '\n';
166
167                                 if (name == 'p') {
168                                         text += '\n';
169                                 }
170                         }
171                 }
172
173                 walk(domParser.parse(html));
174
175                 return text;
176         }
177
178         return {
179                 filter: filter,
180                 innerText: innerText
181         };
182 });
183
184 // Included from: js/tinymce/plugins/paste/classes/Clipboard.js
185
186 /**
187  * Clipboard.js
188  *
189  * Copyright, Moxiecode Systems AB
190  * Released under LGPL License.
191  *
192  * License: http://www.tinymce.com/license
193  * Contributing: http://www.tinymce.com/contributing
194  */
195
196 /**
197  * This class contains logic for getting HTML contents out of the clipboard.
198  *
199  * We need to make a lot of ugly hacks to get the contents out of the clipboard since
200  * the W3C Clipboard API is broken in all browsers that have it: Gecko/WebKit/Blink.
201  * We might rewrite this the way those API:s stabilize. Browsers doesn't handle pasting
202  * from applications like Word the same way as it does when pasting into a contentEditable area
203  * so we need to do lots of extra work to try to get to this clipboard data.
204  *
205  * Current implementation steps:
206  *  1. On keydown with paste keys Ctrl+V or Shift+Insert create
207  *     a paste bin element and move focus to that element.
208  *  2. Wait for the browser to fire a "paste" event and get the contents out of the paste bin.
209  *  3. Check if the paste was successful if true, process the HTML.
210  *  (4). If the paste was unsuccessful use IE execCommand, Clipboard API, document.dataTransfer old WebKit API etc.
211  * 
212  * @class tinymce.pasteplugin.Clipboard
213  * @private
214  */
215 define("tinymce/pasteplugin/Clipboard", [
216         "tinymce/Env",
217         "tinymce/util/VK",
218         "tinymce/pasteplugin/Utils"
219 ], function(Env, VK, Utils) {
220         return function(editor) {
221                 var self = this, pasteBinElm, lastRng, keyboardPasteTimeStamp = 0;
222                 var pasteBinDefaultContent = '%MCEPASTEBIN%', keyboardPastePlainTextState;
223
224                 /**
225                  * Pastes the specified HTML. This means that the HTML is filtered and then
226                  * inserted at the current selection in the editor. It will also fire paste events
227                  * for custom user filtering.
228                  *
229                  * @param {String} html HTML code to paste into the current selection.
230                  */
231                 function pasteHtml(html) {
232                         var args, dom = editor.dom;
233
234                         args = editor.fire('BeforePastePreProcess', {content: html}); // Internal event used by Quirks
235                         args = editor.fire('PastePreProcess', args);
236                         html = args.content;
237
238                         if (!args.isDefaultPrevented()) {
239                                 // User has bound PastePostProcess events then we need to pass it through a DOM node
240                                 // This is not ideal but we don't want to let the browser mess up the HTML for example
241                                 // some browsers add &nbsp; to P tags etc
242                                 if (editor.hasEventListeners('PastePostProcess') && !args.isDefaultPrevented()) {
243                                         // We need to attach the element to the DOM so Sizzle selectors work on the contents
244                                         var tempBody = dom.add(editor.getBody(), 'div', {style: 'display:none'}, html);
245                                         args = editor.fire('PastePostProcess', {node: tempBody});
246                                         dom.remove(tempBody);
247                                         html = args.node.innerHTML;
248                                 }
249
250                                 if (!args.isDefaultPrevented()) {
251                                         editor.insertContent(html);
252                                 }
253                         }
254                 }
255
256                 /**
257                  * Pastes the specified text. This means that the plain text is processed
258                  * and converted into BR and P elements. It will fire paste events for custom filtering.
259                  *
260                  * @param {String} text Text to paste as the current selection location.
261                  */
262                 function pasteText(text) {
263                         text = editor.dom.encode(text).replace(/\r\n/g, '\n');
264
265                         var startBlock = editor.dom.getParent(editor.selection.getStart(), editor.dom.isBlock);
266
267                         // Create start block html for example <p attr="value">
268                         var forcedRootBlockName = editor.settings.forced_root_block;
269                         var forcedRootBlockStartHtml;
270                         if (forcedRootBlockName) {
271                                 forcedRootBlockStartHtml = editor.dom.createHTML(forcedRootBlockName, editor.settings.forced_root_block_attrs);
272                                 forcedRootBlockStartHtml = forcedRootBlockStartHtml.substr(0, forcedRootBlockStartHtml.length - 3) + '>';
273                         }
274
275                         if ((startBlock && /^(PRE|DIV)$/.test(startBlock.nodeName)) || !forcedRootBlockName) {
276                                 text = Utils.filter(text, [
277                                         [/\n/g, "<br>"]
278                                 ]);
279                         } else {
280                                 text = Utils.filter(text, [
281                                         [/\n\n/g, "</p>" + forcedRootBlockStartHtml],
282                                         [/^(.*<\/p>)(<p>)$/, forcedRootBlockStartHtml + '$1'],
283                                         [/\n/g, "<br />"]
284                                 ]);
285
286                                 if (text.indexOf('<p>') != -1) {
287                                         text = forcedRootBlockStartHtml + text;
288                                 }
289                         }
290
291                         pasteHtml(text);
292                 }
293
294                 /**
295                  * Creates a paste bin element as close as possible to the current caret location and places the focus inside that element
296                  * so that when the real paste event occurs the contents gets inserted into this element
297                  * instead of the current editor selection element.
298                  */
299                 function createPasteBin() {
300                         var dom = editor.dom, body = editor.getBody();
301                         var viewport = editor.dom.getViewPort(editor.getWin()), scrollTop = viewport.y, top = 20;
302                         var scrollContainer;
303
304                         lastRng = editor.selection.getRng();
305
306                         if (editor.inline) {
307                                 scrollContainer = editor.selection.getScrollContainer();
308
309                                 if (scrollContainer) {
310                                         scrollTop = scrollContainer.scrollTop;
311                                 }
312                         }
313
314                         // Calculate top cordinate this is needed to avoid scrolling to top of document
315                         // We want the paste bin to be as close to the caret as possible to avoid scrolling
316                         if (lastRng.getClientRects) {
317                                 var rects = lastRng.getClientRects();
318
319                                 if (rects.length) {
320                                         // Client rects gets us closes to the actual
321                                         // caret location in for example a wrapped paragraph block
322                                         top = scrollTop + (rects[0].top - dom.getPos(body).y);
323                                 } else {
324                                         top = scrollTop;
325
326                                         // Check if we can find a closer location by checking the range element
327                                         var container = lastRng.startContainer;
328                                         if (container) {
329                                                 if (container.nodeType == 3 && container.parentNode != body) {
330                                                         container = container.parentNode;
331                                                 }
332
333                                                 if (container.nodeType == 1) {
334                                                         top = dom.getPos(container, scrollContainer || body).y;
335                                                 }
336                                         }
337                                 }
338                         }
339
340                         // Create a pastebin
341                         pasteBinElm = dom.add(editor.getBody(), 'div', {
342                                 id: "mcepastebin",
343                                 contentEditable: true,
344                                 "data-mce-bogus": "1",
345                                 style: 'position: absolute; top: ' + top + 'px;' +
346                                         'width: 10px; height: 10px; overflow: hidden; opacity: 0'
347                         }, pasteBinDefaultContent);
348
349                         // Move paste bin out of sight since the controlSelection rect gets displayed otherwise on IE and Gecko
350                         if (Env.ie || Env.gecko) {
351                                 dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) == 'rtl' ? 0xFFFF : -0xFFFF);
352                         }
353
354                         // Prevent focus events from bubbeling fixed FocusManager issues
355                         dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function(e) {
356                                 e.stopPropagation();
357                         });
358
359                         pasteBinElm.focus();
360                         editor.selection.select(pasteBinElm, true);
361                 }
362
363                 /**
364                  * Removes the paste bin if it exists.
365                  */
366                 function removePasteBin() {
367                         if (pasteBinElm) {
368                                 var pasteBinClone;
369
370                                 // WebKit/Blink might clone the div so
371                                 // lets make sure we remove all clones
372                                 // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
373                                 while ((pasteBinClone = editor.dom.get('mcepastebin'))) {
374                                         editor.dom.remove(pasteBinClone);
375                                         editor.dom.unbind(pasteBinClone);
376                                 }
377
378                                 if (lastRng) {
379                                         editor.selection.setRng(lastRng);
380                                 }
381                         }
382
383                         keyboardPastePlainTextState = false;
384                         pasteBinElm = lastRng = null;
385                 }
386
387                 /**
388                  * Returns the contents of the paste bin as a HTML string.
389                  *
390                  * @return {String} Get the contents of the paste bin.
391                  */
392                 function getPasteBinHtml() {
393                         var html = pasteBinDefaultContent, pasteBinClones, i;
394
395                         // Since WebKit/Chrome might clone the paste bin when pasting
396                         // for example: <img style="float: right"> we need to check if any of them contains some useful html.
397                         // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
398                         pasteBinClones = editor.dom.select('div[id=mcepastebin]');
399                         i = pasteBinClones.length;
400                         while (i--) {
401                                 var cloneHtml = pasteBinClones[i].innerHTML;
402
403                                 if (html == pasteBinDefaultContent) {
404                                         html = '';
405                                 }
406
407                                 if (cloneHtml.length > html.length) {
408                                         html = cloneHtml;
409                                 }
410                         }
411
412                         return html;
413                 }
414
415                 /**
416                  * Gets various content types out of a datatransfer object.
417                  *
418                  * @param {DataTransfer} dataTransfer Event fired on paste.
419                  * @return {Object} Object with mime types and data for those mime types.
420                  */
421                 function getDataTransferItems(dataTransfer) {
422                         var data = {};
423
424                         if (dataTransfer && dataTransfer.types) {
425                                 // Use old WebKit API
426                                 var legacyText = dataTransfer.getData('Text');
427                                 if (legacyText && legacyText.length > 0) {
428                                         data['text/plain'] = legacyText;
429                                 }
430
431                                 for (var i = 0; i < dataTransfer.types.length; i++) {
432                                         var contentType = dataTransfer.types[i];
433                                         data[contentType] = dataTransfer.getData(contentType);
434                                 }
435                         }
436
437                         return data;
438                 }
439
440                 /**
441                  * Gets various content types out of the Clipboard API. It will also get the
442                  * plain text using older IE and WebKit API:s.
443                  *
444                  * @param {ClipboardEvent} clipboardEvent Event fired on paste.
445                  * @return {Object} Object with mime types and data for those mime types.
446                  */
447                 function getClipboardContent(clipboardEvent) {
448                         return getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);
449                 }
450
451                 /**
452                  * Checks if the clipboard contains image data if it does it will take that data
453                  * and convert it into a data url image and paste that image at the caret location.
454                  *
455                  * @param  {ClipboardEvent} e Paste event object.
456                  * @param  {Object} clipboardContent Collection of clipboard contents.
457                  * @return {Boolean} true/false if the image data was found or not.
458                  */
459                 function pasteImageData(e, clipboardContent) {
460                         function pasteImage(item) {
461                                 if (items[i].type == 'image/png') {
462                                         var reader = new FileReader();
463
464                                         reader.onload = function() {
465                                                 pasteHtml('<img src="' + reader.result + '">');
466                                         };
467
468                                         reader.readAsDataURL(item.getAsFile());
469
470                                         return true;
471                                 }
472                         }
473
474                         // If paste data images are disabled or there is HTML or plain text
475                         // contents then proceed with the normal paste process
476                         if (!editor.settings.paste_data_images || "text/html" in clipboardContent || "text/plain" in clipboardContent) {
477                                 return;
478                         }
479
480                         if (e.clipboardData) {
481                                 var items = e.clipboardData.items;
482
483                                 if (items) {
484                                         for (var i = 0; i < items.length; i++) {
485                                                 if (pasteImage(items[i])) {
486                                                         return true;
487                                                 }
488                                         }
489                                 }
490                         }
491                 }
492
493                 function getCaretRangeFromEvent(e) {
494                         var doc = editor.getDoc(), rng;
495
496                         if (doc.caretPositionFromPoint) {
497                                 var point = doc.caretPositionFromPoint(e.clientX, e.clientY);
498                                 rng = doc.createRange();
499                                 rng.setStart(point.offsetNode, point.offset);
500                                 rng.collapse(true);
501                         } else if (doc.caretRangeFromPoint) {
502                                 rng = doc.caretRangeFromPoint(e.clientX, e.clientY);
503                         }
504
505                         return rng;
506                 }
507
508                 function hasContentType(clipboardContent, mimeType) {
509                         return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
510                 }
511
512                 function registerEventHandlers() {
513                         editor.on('keydown', function(e) {
514                                 if (e.isDefaultPrevented()) {
515                                         return;
516                                 }
517
518                                 // Ctrl+V or Shift+Insert
519                                 if ((VK.metaKeyPressed(e) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) {
520                                         keyboardPastePlainTextState = e.shiftKey && e.keyCode == 86;
521
522                                         // Prevent undoManager keydown handler from making an undo level with the pastebin in it
523                                         e.stopImmediatePropagation();
524
525                                         keyboardPasteTimeStamp = new Date().getTime();
526
527                                         // IE doesn't support Ctrl+Shift+V and it doesn't even produce a paste event
528                                         // so lets fake a paste event and let IE use the execCommand/dataTransfer methods
529                                         if (Env.ie && keyboardPastePlainTextState) {
530                                                 e.preventDefault();
531                                                 editor.fire('paste', {ieFake: true});
532                                                 return;
533                                         }
534
535                                         removePasteBin();
536                                         createPasteBin();
537                                 }
538                         });
539
540                         editor.on('paste', function(e) {
541                                 var clipboardContent = getClipboardContent(e);
542                                 var isKeyBoardPaste = new Date().getTime() - keyboardPasteTimeStamp < 1000;
543                                 var plainTextMode = self.pasteFormat == "text" || keyboardPastePlainTextState;
544
545                                 if (e.isDefaultPrevented()) {
546                                         removePasteBin();
547                                         return;
548                                 }
549
550                                 if (pasteImageData(e, clipboardContent)) {
551                                         removePasteBin();
552                                         return;
553                                 }
554
555                                 // Not a keyboard paste prevent default paste and try to grab the clipboard contents using different APIs
556                                 if (!isKeyBoardPaste) {
557                                         e.preventDefault();
558                                 }
559
560                                 // Try IE only method if paste isn't a keyboard paste
561                                 if (Env.ie && (!isKeyBoardPaste || e.ieFake)) {
562                                         createPasteBin();
563
564                                         editor.dom.bind(pasteBinElm, 'paste', function(e) {
565                                                 e.stopPropagation();
566                                         });
567
568                                         editor.getDoc().execCommand('Paste', false, null);
569                                         clipboardContent["text/html"] = getPasteBinHtml();
570                                 }
571
572                                 setTimeout(function() {
573                                         var html = getPasteBinHtml();
574
575                                         // WebKit has a nice bug where it clones the paste bin if you paste from for example notepad
576                                         if (pasteBinElm && pasteBinElm.firstChild && pasteBinElm.firstChild.id === 'mcepastebin') {
577                                                 plainTextMode = true;
578                                         }
579
580                                         removePasteBin();
581
582                                         // Always use pastebin HTML if it's available since it contains Word contents
583                                         if (!plainTextMode && isKeyBoardPaste && html && html != pasteBinDefaultContent) {
584                                                 clipboardContent['text/html'] = html;
585                                         }
586
587                                         if (html == pasteBinDefaultContent || !isKeyBoardPaste) {
588                                                 html = clipboardContent['text/html'] || clipboardContent['text/plain'] || pasteBinDefaultContent;
589
590                                                 if (html == pasteBinDefaultContent) {
591                                                         if (!isKeyBoardPaste) {
592                                                                 editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.');
593                                                         }
594
595                                                         return;
596                                                 }
597                                         }
598
599                                         // Force plain text mode if we only got a text/plain content type
600                                         if (!hasContentType(clipboardContent, 'text/html') && hasContentType(clipboardContent, 'text/plain')) {
601                                                 plainTextMode = true;
602                                         }
603
604                                         if (plainTextMode) {
605                                                 pasteText(clipboardContent['text/plain'] || Utils.innerText(html));
606                                         } else {
607                                                 pasteHtml(html);
608                                         }
609                                 }, 0);
610                         });
611
612                         editor.on('dragstart', function(e) {
613                                 if (e.dataTransfer.types) {
614                                         try {
615                                                 e.dataTransfer.setData('mce-internal', editor.selection.getContent());
616                                         } catch (ex) {
617                                                 // IE 10 throws an error since it doesn't support custom data items
618                                         }
619                                 }
620                         });
621
622                         editor.on('drop', function(e) {
623                                 var rng = getCaretRangeFromEvent(e);
624
625                                 if (rng && !e.isDefaultPrevented()) {
626                                         var dropContent = getDataTransferItems(e.dataTransfer);
627                                         var content = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain'];
628
629                                         if (content) {
630                                                 e.preventDefault();
631
632                                                 editor.undoManager.transact(function() {
633                                                         if (dropContent['mce-internal']) {
634                                                                 editor.execCommand('Delete');
635                                                         }
636
637                                                         editor.selection.setRng(rng);
638
639                                                         if (!dropContent['text/html']) {
640                                                                 pasteText(content);
641                                                         } else {
642                                                                 pasteHtml(content);
643                                                         }
644                                                 });
645                                         }
646                                 }
647                         });
648                 }
649
650                 self.pasteHtml = pasteHtml;
651                 self.pasteText = pasteText;
652
653                 editor.on('preInit', function() {
654                         registerEventHandlers();
655
656                         // Remove all data images from paste for example from Gecko
657                         // except internal images like video elements
658                         editor.parser.addNodeFilter('img', function(nodes) {
659                                 if (!editor.settings.paste_data_images) {
660                                         var i = nodes.length;
661
662                                         while (i--) {
663                                                 var src = nodes[i].attributes.map.src;
664                                                 if (src && src.indexOf('data:image') === 0) {
665                                                         if (!nodes[i].attr('data-mce-object') && src !== Env.transparentSrc) {
666                                                                 nodes[i].remove();
667                                                         }
668                                                 }
669                                         }
670                                 }
671                         });
672                 });
673
674                 // Fix for #6504 we need to remove the paste bin on IE if the user paste in a file
675                 editor.on('PreProcess', function() {
676                         editor.dom.remove(editor.dom.get('mcepastebin'));
677                 });
678         };
679 });
680
681 // Included from: js/tinymce/plugins/paste/classes/WordFilter.js
682
683 /**
684  * WordFilter.js
685  *
686  * Copyright, Moxiecode Systems AB
687  * Released under LGPL License.
688  *
689  * License: http://www.tinymce.com/license
690  * Contributing: http://www.tinymce.com/contributing
691  */
692
693 /**
694  * This class parses word HTML into proper TinyMCE markup.
695  *
696  * @class tinymce.pasteplugin.Quirks
697  * @private
698  */
699 define("tinymce/pasteplugin/WordFilter", [
700         "tinymce/util/Tools",
701         "tinymce/html/DomParser",
702         "tinymce/html/Schema",
703         "tinymce/html/Serializer",
704         "tinymce/html/Node",
705         "tinymce/pasteplugin/Utils"
706 ], function(Tools, DomParser, Schema, Serializer, Node, Utils) {
707         /**
708          * Checks if the specified content is from any of the following sources: MS Word/Office 365/Google docs.
709          */
710         function isWordContent(content) {
711                 return (
712                         (/<font face="Times New Roman"|class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i).test(content) ||
713                         (/class="OutlineElement/).test(content) ||
714                         (/id="?docs\-internal\-guid\-/.test(content))
715                 );
716         }
717
718         function WordFilter(editor) {
719                 var settings = editor.settings;
720
721                 editor.on('BeforePastePreProcess', function(e) {
722                         var content = e.content, retainStyleProperties, validStyles;
723
724                         retainStyleProperties = settings.paste_retain_style_properties;
725                         if (retainStyleProperties) {
726                                 validStyles = Tools.makeMap(retainStyleProperties.split(/[, ]/));
727                         }
728
729                         /**
730                          * Converts fake bullet and numbered lists to real semantic OL/UL.
731                          *
732                          * @param {tinymce.html.Node} node Root node to convert children of.
733                          */
734                         function convertFakeListsToProperLists(node) {
735                                 var currentListNode, prevListNode, lastLevel = 1;
736
737                                 function convertParagraphToLi(paragraphNode, listStartTextNode, listName, start) {
738                                         var level = paragraphNode._listLevel || lastLevel;
739
740                                         // Handle list nesting
741                                         if (level != lastLevel) {
742                                                 if (level < lastLevel) {
743                                                         // Move to parent list
744                                                         if (currentListNode) {
745                                                                 currentListNode = currentListNode.parent.parent;
746                                                         }
747                                                 } else {
748                                                         // Create new list
749                                                         prevListNode = currentListNode;
750                                                         currentListNode = null;
751                                                 }
752                                         }
753
754                                         if (!currentListNode || currentListNode.name != listName) {
755                                                 prevListNode = prevListNode || currentListNode;
756                                                 currentListNode = new Node(listName, 1);
757
758                                                 if (start > 1) {
759                                                         currentListNode.attr('start', '' + start);
760                                                 }
761
762                                                 paragraphNode.wrap(currentListNode);
763                                         } else {
764                                                 currentListNode.append(paragraphNode);
765                                         }
766
767                                         paragraphNode.name = 'li';
768                                         listStartTextNode.value = '';
769
770                                         var nextNode = listStartTextNode.next;
771                                         if (nextNode && nextNode.type == 3) {
772                                                 nextNode.value = nextNode.value.replace(/^\u00a0+/, '');
773                                         }
774
775                                         // Append list to previous list if it exists
776                                         if (level > lastLevel && prevListNode) {
777                                                 prevListNode.lastChild.append(currentListNode);
778                                         }
779
780                                         lastLevel = level;
781                                 }
782
783                                 var paragraphs = node.getAll('p');
784
785                                 for (var i = 0; i < paragraphs.length; i++) {
786                                         node = paragraphs[i];
787
788                                         if (node.name == 'p' && node.firstChild) {
789                                                 // Find first text node in paragraph
790                                                 var nodeText = '';
791                                                 var listStartTextNode = node.firstChild;
792
793                                                 while (listStartTextNode) {
794                                                         nodeText = listStartTextNode.value;
795                                                         if (nodeText) {
796                                                                 break;
797                                                         }
798
799                                                         listStartTextNode = listStartTextNode.firstChild;
800                                                 }
801
802                                                 // Detect unordered lists look for bullets
803                                                 if (/^\s*[\u2022\u00b7\u00a7\u00d8\u25CF]\s*$/.test(nodeText)) {
804                                                         convertParagraphToLi(node, listStartTextNode, 'ul');
805                                                         continue;
806                                                 }
807
808                                                 // Detect ordered lists 1., a. or ixv.
809                                                 if (/^\s*\w+\.$/.test(nodeText)) {
810                                                         // Parse OL start number
811                                                         var matches = /([0-9])\./.exec(nodeText);
812                                                         var start = 1;
813                                                         if (matches) {
814                                                                 start = parseInt(matches[1], 10);
815                                                         }
816
817                                                         convertParagraphToLi(node, listStartTextNode, 'ol', start);
818                                                         continue;
819                                                 }
820
821                                                 currentListNode = null;
822                                         }
823                                 }
824                         }
825
826                         function filterStyles(node, styleValue) {
827                                 var outputStyles = {}, styles = editor.dom.parseStyle(styleValue);
828
829                                 // Parse out list indent level for lists
830                                 if (node.name === 'p') {
831                                         var matches = /mso-list:\w+ \w+([0-9]+)/.exec(styleValue);
832
833                                         if (matches) {
834                                                 node._listLevel = parseInt(matches[1], 10);
835                                         }
836                                 }
837
838                                 Tools.each(styles, function(value, name) {
839                                         // Convert various MS styles to W3C styles
840                                         switch (name) {
841                                                 case "horiz-align":
842                                                         name = "text-align";
843                                                         break;
844
845                                                 case "vert-align":
846                                                         name = "vertical-align";
847                                                         break;
848
849                                                 case "font-color":
850                                                 case "mso-foreground":
851                                                         name = "color";
852                                                         break;
853
854                                                 case "mso-background":
855                                                 case "mso-highlight":
856                                                         name = "background";
857                                                         break;
858
859                                                 case "font-weight":
860                                                 case "font-style":
861                                                         if (value != "normal") {
862                                                                 outputStyles[name] = value;
863                                                         }
864                                                         return;
865
866                                                 case "mso-element":
867                                                         // Remove track changes code
868                                                         if (/^(comment|comment-list)$/i.test(value)) {
869                                                                 node.remove();
870                                                                 return;
871                                                         }
872
873                                                         break;
874                                         }
875
876                                         if (name.indexOf('mso-comment') === 0) {
877                                                 node.remove();
878                                                 return;
879                                         }
880
881                                         // Never allow mso- prefixed names
882                                         if (name.indexOf('mso-') === 0) {
883                                                 return;
884                                         }
885
886                                         // Output only valid styles
887                                         if (retainStyleProperties == "all" || (validStyles && validStyles[name])) {
888                                                 outputStyles[name] = value;
889                                         }
890                                 });
891
892                                 // Convert bold style to "b" element
893                                 if (/(bold)/i.test(outputStyles["font-weight"])) {
894                                         delete outputStyles["font-weight"];
895                                         node.wrap(new Node("b", 1));
896                                 }
897
898                                 // Convert italic style to "i" element
899                                 if (/(italic)/i.test(outputStyles["font-style"])) {
900                                         delete outputStyles["font-style"];
901                                         node.wrap(new Node("i", 1));
902                                 }
903
904                                 // Serialize the styles and see if there is something left to keep
905                                 outputStyles = editor.dom.serializeStyle(outputStyles, node.name);
906                                 if (outputStyles) {
907                                         return outputStyles;
908                                 }
909
910                                 return null;
911                         }
912
913                         if (settings.paste_enable_default_filters === false) {
914                                 return;
915                         }
916
917                         // Detect is the contents is Word junk HTML
918                         if (isWordContent(e.content)) {
919                                 e.wordContent = true; // Mark it for other processors
920
921                                 // Remove basic Word junk
922                                 content = Utils.filter(content, [
923                                         // Word comments like conditional comments etc
924                                         /<!--[\s\S]+?-->/gi,
925
926                                         // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
927                                         // MS Office namespaced tags, and a few other tags
928                                         /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
929
930                                         // Convert <s> into <strike> for line-though
931                                         [/<(\/?)s>/gi, "<$1strike>"],
932
933                                         // Replace nsbp entites to char since it's easier to handle
934                                         [/&nbsp;/gi, "\u00a0"],
935
936                                         // Convert <span style="mso-spacerun:yes">___</span> to string of alternating
937                                         // breaking/non-breaking spaces of same length
938                                         [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
939                                                 function(str, spaces) {
940                                                         return (spaces.length > 0) ?
941                                                                 spaces.replace(/./, " ").slice(Math.floor(spaces.length / 2)).split("").join("\u00a0") : "";
942                                                 }
943                                         ]
944                                 ]);
945
946                                 var validElements = settings.paste_word_valid_elements;
947                                 if (!validElements) {
948                                         validElements = '-strong/b,-em/i,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,-p/div,' +
949                                                 '-table[width],-tr,-td[colspan|rowspan|width],-th,-thead,-tfoot,-tbody,-a[href|name],sub,sup,strike,br,del';
950                                 }
951
952                                 // Setup strict schema
953                                 var schema = new Schema({
954                                         valid_elements: validElements,
955                                         valid_children: '-li[p]'
956                                 });
957
958                                 // Add style/class attribute to all element rules since the user might have removed them from
959                                 // paste_word_valid_elements config option and we need to check them for properties
960                                 Tools.each(schema.elements, function(rule) {
961                                         if (!rule.attributes["class"]) {
962                                                 rule.attributes["class"] = {};
963                                                 rule.attributesOrder.push("class");
964                                         }
965
966                                         if (!rule.attributes.style) {
967                                                 rule.attributes.style = {};
968                                                 rule.attributesOrder.push("style");
969                                         }
970                                 });
971
972                                 // Parse HTML into DOM structure
973                                 var domParser = new DomParser({}, schema);
974
975                                 // Filter styles to remove "mso" specific styles and convert some of them
976                                 domParser.addAttributeFilter('style', function(nodes) {
977                                         var i = nodes.length, node;
978
979                                         while (i--) {
980                                                 node = nodes[i];
981                                                 node.attr('style', filterStyles(node, node.attr('style')));
982
983                                                 // Remove pointess spans
984                                                 if (node.name == 'span' && node.parent && !node.attributes.length) {
985                                                         node.unwrap();
986                                                 }
987                                         }
988                                 });
989
990                                 // Check the class attribute for comments or del items and remove those
991                                 domParser.addAttributeFilter('class', function(nodes) {
992                                         var i = nodes.length, node, className;
993
994                                         while (i--) {
995                                                 node = nodes[i];
996
997                                                 className = node.attr('class');
998                                                 if (/^(MsoCommentReference|MsoCommentText|msoDel)$/i.test(className)) {
999                                                         node.remove();
1000                                                 }
1001
1002                                                 node.attr('class', null);
1003                                         }
1004                                 });
1005
1006                                 // Remove all del elements since we don't want the track changes code in the editor
1007                                 domParser.addNodeFilter('del', function(nodes) {
1008                                         var i = nodes.length;
1009
1010                                         while (i--) {
1011                                                 nodes[i].remove();
1012                                         }
1013                                 });
1014
1015                                 // Keep some of the links and anchors
1016                                 domParser.addNodeFilter('a', function(nodes) {
1017                                         var i = nodes.length, node, href, name;
1018
1019                                         while (i--) {
1020                                                 node = nodes[i];
1021                                                 href = node.attr('href');
1022                                                 name = node.attr('name');
1023
1024                                                 if (href && href.indexOf('#_msocom_') != -1) {
1025                                                         node.remove();
1026                                                         continue;
1027                                                 }
1028
1029                                                 if (href && href.indexOf('file://') === 0) {
1030                                                         href = href.split('#')[1];
1031                                                         if (href) {
1032                                                                 href = '#' + href;
1033                                                         }
1034                                                 }
1035
1036                                                 if (!href && !name) {
1037                                                         node.unwrap();
1038                                                 } else {
1039                                                         if (name && name.indexOf('Toc') !== 0) {
1040                                                                 node.unwrap();
1041                                                                 continue;
1042                                                         }
1043
1044                                                         node.attr({
1045                                                                 href: href,
1046                                                                 name: name
1047                                                         });
1048                                                 }
1049                                         }
1050                                 });
1051
1052                                 // Parse into DOM structure
1053                                 var rootNode = domParser.parse(content);
1054
1055                                 // Process DOM
1056                                 convertFakeListsToProperLists(rootNode);
1057
1058                                 // Serialize DOM back to HTML
1059                                 e.content = new Serializer({}, schema).serialize(rootNode);
1060                         }
1061                 });
1062         }
1063
1064         WordFilter.isWordContent = isWordContent;
1065
1066         return WordFilter;
1067 });
1068
1069 // Included from: js/tinymce/plugins/paste/classes/Quirks.js
1070
1071 /**
1072  * Quirks.js
1073  *
1074  * Copyright, Moxiecode Systems AB
1075  * Released under LGPL License.
1076  *
1077  * License: http://www.tinymce.com/license
1078  * Contributing: http://www.tinymce.com/contributing
1079  */
1080
1081 /**
1082  * This class contains various fixes for browsers. These issues can not be feature
1083  * detected since we have no direct control over the clipboard. However we might be able
1084  * to remove some of these fixes once the browsers gets updated/fixed.
1085  *
1086  * @class tinymce.pasteplugin.Quirks
1087  * @private
1088  */
1089 define("tinymce/pasteplugin/Quirks", [
1090         "tinymce/Env",
1091         "tinymce/util/Tools",
1092         "tinymce/pasteplugin/WordFilter",
1093         "tinymce/pasteplugin/Utils"
1094 ], function(Env, Tools, WordFilter, Utils) {
1095         "use strict";
1096
1097         return function(editor) {
1098                 function addPreProcessFilter(filterFunc) {
1099                         editor.on('BeforePastePreProcess', function(e) {
1100                                 e.content = filterFunc(e.content);
1101                         });
1102                 }
1103
1104                 /**
1105                  * Removes WebKit fragment comments and converted-space spans.
1106                  *
1107                  * This:
1108                  *   <!--StartFragment-->a<span class="Apple-converted-space">&nbsp;</span>b<!--EndFragment-->
1109                  *
1110                  * Becomes:
1111                  *   a&nbsp;b
1112                  */
1113                 function removeWebKitFragments(html) {
1114                         html = Utils.filter(html, [
1115                                 /^[\s\S]*<!--StartFragment-->|<!--EndFragment-->[\s\S]*$/g, // WebKit fragment
1116                                 [/<span class="Apple-converted-space">\u00a0<\/span>/g, '\u00a0'], // WebKit &nbsp;
1117                                 /<br>$/i // Traling BR elements
1118                         ]);
1119
1120                         return html;
1121                 }
1122
1123                 /**
1124                  * Removes BR elements after block elements. IE9 has a nasty bug where it puts a BR element after each
1125                  * block element when pasting from word. This removes those elements.
1126                  *
1127                  * This:
1128                  *  <p>a</p><br><p>b</p>
1129                  *
1130                  * Becomes:
1131                  *  <p>a</p><p>b</p>
1132                  */
1133                 function removeExplorerBrElementsAfterBlocks(html) {
1134                         // Only filter word specific content
1135                         if (!WordFilter.isWordContent(html)) {
1136                                 return html;
1137                         }
1138
1139                         // Produce block regexp based on the block elements in schema
1140                         var blockElements = [];
1141
1142                         Tools.each(editor.schema.getBlockElements(), function(block, blockName) {
1143                                 blockElements.push(blockName);
1144                         });
1145
1146                         var explorerBlocksRegExp = new RegExp(
1147                                 '(?:<br>&nbsp;[\\s\\r\\n]+|<br>)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:<br>&nbsp;[\\s\\r\\n]+|<br>)*',
1148                                 'g'
1149                         );
1150
1151                         // Remove BR:s from: <BLOCK>X</BLOCK><BR>
1152                         html = Utils.filter(html, [
1153                                 [explorerBlocksRegExp, '$1']
1154                         ]);
1155
1156                         // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
1157                         html = Utils.filter(html, [
1158                                 [/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact
1159                                 [/<br>/g, ' '],            // Replace single br elements with space since they are word wrap BR:s
1160                                 [/<BR><BR>/g, '<br>']      // Replace back the double brs but into a single BR
1161                         ]);
1162
1163                         return html;
1164                 }
1165
1166                 /**
1167                  * WebKit has a nasty bug where the all computed styles gets added to style attributes when copy/pasting contents.
1168                  * This fix solves that by simply removing the whole style attribute.
1169                  *
1170                  * The paste_webkit_styles option can be set to specify what to keep:
1171                  *  paste_webkit_styles: "none" // Keep no styles
1172                  *  paste_webkit_styles: "all", // Keep all of them
1173                  *  paste_webkit_styles: "font-weight color" // Keep specific ones
1174                  *
1175                  * @param {String} content Content that needs to be processed.
1176                  * @return {String} Processed contents.
1177                  */
1178                 function removeWebKitStyles(content) {
1179                         // Passthrough all styles from Word and let the WordFilter handle that junk
1180                         if (WordFilter.isWordContent(content)) {
1181                                 return content;
1182                         }
1183
1184                         // Filter away styles that isn't matching the target node
1185
1186                         var webKitStyles = editor.getParam("paste_webkit_styles", "color font-size font-family background-color").split(/[, ]/);
1187
1188                         if (editor.settings.paste_remove_styles_if_webkit === false) {
1189                                 webKitStyles = "all";
1190                         }
1191
1192                         // Keep specific styles that doesn't match the current node computed style
1193                         if (webKitStyles != "all") {
1194                                 var dom = editor.dom, node = editor.selection.getNode();
1195
1196                                 content = content.replace(/ style=\"([^\"]+)\"/gi, function(a, value) {
1197                                         var inputStyles = dom.parseStyle(value, 'span'), outputStyles = {};
1198
1199                                         if (webKitStyles === "none") {
1200                                                 return '';
1201                                         }
1202
1203                                         for (var i = 0; i < webKitStyles.length; i++) {
1204                                                 if (dom.toHex(dom.getStyle(node, webKitStyles[i], true)) != inputStyles[webKitStyles[i]]) {
1205                                                         outputStyles[webKitStyles[i]] = inputStyles[webKitStyles[i]];
1206                                                 }
1207                                         }
1208
1209                                         outputStyles = dom.serializeStyle(outputStyles, 'span');
1210                                         if (outputStyles) {
1211                                                 return ' style="' + outputStyles + '"';
1212                                         }
1213
1214                                         return '';
1215                                 });
1216                         }
1217
1218                         return content;
1219                 }
1220
1221                 // Sniff browsers and apply fixes since we can't feature detect
1222                 if (Env.webkit) {
1223                         addPreProcessFilter(removeWebKitStyles);
1224                         addPreProcessFilter(removeWebKitFragments);
1225                 }
1226
1227                 if (Env.ie) {
1228                         addPreProcessFilter(removeExplorerBrElementsAfterBlocks);
1229                 }
1230         };
1231 });
1232
1233 // Included from: js/tinymce/plugins/paste/classes/Plugin.js
1234
1235 /**
1236  * Plugin.js
1237  *
1238  * Copyright, Moxiecode Systems AB
1239  * Released under LGPL License.
1240  *
1241  * License: http://www.tinymce.com/license
1242  * Contributing: http://www.tinymce.com/contributing
1243  */
1244
1245 /**
1246  * This class contains the tinymce plugin logic for the paste plugin.
1247  *
1248  * @class tinymce.pasteplugin.Plugin
1249  * @private
1250  */
1251 define("tinymce/pasteplugin/Plugin", [
1252         "tinymce/PluginManager",
1253         "tinymce/pasteplugin/Clipboard",
1254         "tinymce/pasteplugin/WordFilter",
1255         "tinymce/pasteplugin/Quirks"
1256 ], function(PluginManager, Clipboard, WordFilter, Quirks) {
1257         var userIsInformed;
1258
1259         PluginManager.add('paste', function(editor) {
1260                 var self = this, clipboard, settings = editor.settings;
1261
1262                 function togglePlainTextPaste() {
1263                         if (clipboard.pasteFormat == "text") {
1264                                 this.active(false);
1265                                 clipboard.pasteFormat = "html";
1266                         } else {
1267                                 clipboard.pasteFormat = "text";
1268                                 this.active(true);
1269
1270                                 if (!userIsInformed) {
1271                                         editor.windowManager.alert(
1272                                                 'Paste is now in plain text mode. Contents will now ' +
1273                                                 'be pasted as plain text until you toggle this option off.'
1274                                         );
1275
1276                                         userIsInformed = true;
1277                                 }
1278                         }
1279                 }
1280
1281                 self.clipboard = clipboard = new Clipboard(editor);
1282                 self.quirks = new Quirks(editor);
1283                 self.wordFilter = new WordFilter(editor);
1284
1285                 if (editor.settings.paste_as_text) {
1286                         self.clipboard.pasteFormat = "text";
1287                 }
1288
1289                 if (settings.paste_preprocess) {
1290                         editor.on('PastePreProcess', function(e) {
1291                                 settings.paste_preprocess.call(self, self, e);
1292                         });
1293                 }
1294
1295                 if (settings.paste_postprocess) {
1296                         editor.on('PastePostProcess', function(e) {
1297                                 settings.paste_postprocess.call(self, self, e);
1298                         });
1299                 }
1300
1301                 editor.addCommand('mceInsertClipboardContent', function(ui, value) {
1302                         if (value.content) {
1303                                 self.clipboard.pasteHtml(value.content);
1304                         }
1305
1306                         if (value.text) {
1307                                 self.clipboard.pasteText(value.text);
1308                         }
1309                 });
1310
1311                 // Block all drag/drop events
1312                 if (editor.paste_block_drop) {
1313                         editor.on('dragend dragover draggesture dragdrop drop drag', function(e) {
1314                                 e.preventDefault();
1315                                 e.stopPropagation();
1316                         });
1317                 }
1318
1319                 // Prevent users from dropping data images on Gecko
1320                 if (!editor.settings.paste_data_images) {
1321                         editor.on('drop', function(e) {
1322                                 var dataTransfer = e.dataTransfer;
1323
1324                                 if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
1325                                         e.preventDefault();
1326                                 }
1327                         });
1328                 }
1329
1330                 editor.addButton('pastetext', {
1331                         icon: 'pastetext',
1332                         tooltip: 'Paste as text',
1333                         onclick: togglePlainTextPaste,
1334                         active: self.clipboard.pasteFormat == "text"
1335                 });
1336
1337                 editor.addMenuItem('pastetext', {
1338                         text: 'Paste as text',
1339                         selectable: true,
1340                         active: clipboard.pasteFormat,
1341                         onclick: togglePlainTextPaste
1342                 });
1343         });
1344 });
1345
1346 expose(["tinymce/pasteplugin/Utils","tinymce/pasteplugin/Clipboard","tinymce/pasteplugin/WordFilter","tinymce/pasteplugin/Quirks","tinymce/pasteplugin/Plugin"]);
1347 })(this);