]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/tinymce/plugins/paste/plugin.js
WordPress 4.4-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                 var i, target, id, fragments, privateModules;
67
68                 for (i = 0; i < ids.length; i++) {
69                         target = exports;
70                         id = ids[i];
71                         fragments = id.split(/[.\/]/);
72
73                         for (var fi = 0; fi < fragments.length - 1; ++fi) {
74                                 if (target[fragments[fi]] === undefined) {
75                                         target[fragments[fi]] = {};
76                                 }
77
78                                 target = target[fragments[fi]];
79                         }
80
81                         target[fragments[fragments.length - 1]] = modules[id];
82                 }
83                 
84                 // Expose private modules for unit tests
85                 if (exports.AMDLC_TESTS) {
86                         privateModules = exports.privateModules || {};
87
88                         for (id in modules) {
89                                 privateModules[id] = modules[id];
90                         }
91
92                         for (i = 0; i < ids.length; i++) {
93                                 delete privateModules[ids[i]];
94                         }
95
96                         exports.privateModules = privateModules;
97                 }
98         }
99
100 // Included from: js/tinymce/plugins/paste/classes/Utils.js
101
102 /**
103  * Utils.js
104  *
105  * Released under LGPL License.
106  * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
107  *
108  * License: http://www.tinymce.com/license
109  * Contributing: http://www.tinymce.com/contributing
110  */
111
112 /**
113  * This class contails various utility functions for the paste plugin.
114  *
115  * @class tinymce.pasteplugin.Utils
116  */
117 define("tinymce/pasteplugin/Utils", [
118         "tinymce/util/Tools",
119         "tinymce/html/DomParser",
120         "tinymce/html/Schema"
121 ], function(Tools, DomParser, Schema) {
122         function filter(content, items) {
123                 Tools.each(items, function(v) {
124                         if (v.constructor == RegExp) {
125                                 content = content.replace(v, '');
126                         } else {
127                                 content = content.replace(v[0], v[1]);
128                         }
129                 });
130
131                 return content;
132         }
133
134         /**
135          * Gets the innerText of the specified element. It will handle edge cases
136          * and works better than textContent on Gecko.
137          *
138          * @param {String} html HTML string to get text from.
139          * @return {String} String of text with line feeds.
140          */
141         function innerText(html) {
142                 var schema = new Schema(), domParser = new DomParser({}, schema), text = '';
143                 var shortEndedElements = schema.getShortEndedElements();
144                 var ignoreElements = Tools.makeMap('script noscript style textarea video audio iframe object', ' ');
145                 var blockElements = schema.getBlockElements();
146
147                 function walk(node) {
148                         var name = node.name, currentNode = node;
149
150                         if (name === 'br') {
151                                 text += '\n';
152                                 return;
153                         }
154
155                         // img/input/hr
156                         if (shortEndedElements[name]) {
157                                 text += ' ';
158                         }
159
160                         // Ingore script, video contents
161                         if (ignoreElements[name]) {
162                                 text += ' ';
163                                 return;
164                         }
165
166                         if (node.type == 3) {
167                                 text += node.value;
168                         }
169
170                         // Walk all children
171                         if (!node.shortEnded) {
172                                 if ((node = node.firstChild)) {
173                                         do {
174                                                 walk(node);
175                                         } while ((node = node.next));
176                                 }
177                         }
178
179                         // Add \n or \n\n for blocks or P
180                         if (blockElements[name] && currentNode.next) {
181                                 text += '\n';
182
183                                 if (name == 'p') {
184                                         text += '\n';
185                                 }
186                         }
187                 }
188
189                 html = filter(html, [
190                         /<!\[[^\]]+\]>/g // Conditional comments
191                 ]);
192
193                 walk(domParser.parse(html));
194
195                 return text;
196         }
197
198         /**
199          * Trims the specified HTML by removing all WebKit fragments, all elements wrapping the body trailing BR elements etc.
200          *
201          * @param {String} html Html string to trim contents on.
202          * @return {String} Html contents that got trimmed.
203          */
204         function trimHtml(html) {
205                 function trimSpaces(all, s1, s2) {
206                         // WebKit &nbsp; meant to preserve multiple spaces but instead inserted around all inline tags,
207                         // including the spans with inline styles created on paste
208                         if (!s1 && !s2) {
209                                 return ' ';
210                         }
211
212                         return '\u00a0';
213                 }
214
215                 html = filter(html, [
216                         /^[\s\S]*<body[^>]*>\s*|\s*<\/body[^>]*>[\s\S]*$/g, // Remove anything but the contents within the BODY element
217                         /<!--StartFragment-->|<!--EndFragment-->/g, // Inner fragments (tables from excel on mac)
218                         [/( ?)<span class="Apple-converted-space">\u00a0<\/span>( ?)/g, trimSpaces],
219                         /<br>$/i // Trailing BR elements
220                 ]);
221
222                 return html;
223         }
224
225         return {
226                 filter: filter,
227                 innerText: innerText,
228                 trimHtml: trimHtml
229         };
230 });
231
232 // Included from: js/tinymce/plugins/paste/classes/Clipboard.js
233
234 /**
235  * Clipboard.js
236  *
237  * Released under LGPL License.
238  * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
239  *
240  * License: http://www.tinymce.com/license
241  * Contributing: http://www.tinymce.com/contributing
242  */
243
244 /**
245  * This class contains logic for getting HTML contents out of the clipboard.
246  *
247  * We need to make a lot of ugly hacks to get the contents out of the clipboard since
248  * the W3C Clipboard API is broken in all browsers that have it: Gecko/WebKit/Blink.
249  * We might rewrite this the way those API:s stabilize. Browsers doesn't handle pasting
250  * from applications like Word the same way as it does when pasting into a contentEditable area
251  * so we need to do lots of extra work to try to get to this clipboard data.
252  *
253  * Current implementation steps:
254  *  1. On keydown with paste keys Ctrl+V or Shift+Insert create
255  *     a paste bin element and move focus to that element.
256  *  2. Wait for the browser to fire a "paste" event and get the contents out of the paste bin.
257  *  3. Check if the paste was successful if true, process the HTML.
258  *  (4). If the paste was unsuccessful use IE execCommand, Clipboard API, document.dataTransfer old WebKit API etc.
259  *
260  * @class tinymce.pasteplugin.Clipboard
261  * @private
262  */
263 define("tinymce/pasteplugin/Clipboard", [
264         "tinymce/Env",
265         "tinymce/dom/RangeUtils",
266         "tinymce/util/VK",
267         "tinymce/pasteplugin/Utils"
268 ], function(Env, RangeUtils, VK, Utils) {
269         return function(editor) {
270                 var self = this, pasteBinElm, lastRng, keyboardPasteTimeStamp = 0, draggingInternally = false;
271                 var pasteBinDefaultContent = '%MCEPASTEBIN%', keyboardPastePlainTextState;
272                 var mceInternalUrlPrefix = 'data:text/mce-internal,';
273
274                 /**
275                  * Pastes the specified HTML. This means that the HTML is filtered and then
276                  * inserted at the current selection in the editor. It will also fire paste events
277                  * for custom user filtering.
278                  *
279                  * @param {String} html HTML code to paste into the current selection.
280                  */
281                 function pasteHtml(html) {
282                         var args, dom = editor.dom;
283
284                         args = editor.fire('BeforePastePreProcess', {content: html}); // Internal event used by Quirks
285                         args = editor.fire('PastePreProcess', args);
286                         html = args.content;
287
288                         if (!args.isDefaultPrevented()) {
289                                 // User has bound PastePostProcess events then we need to pass it through a DOM node
290                                 // This is not ideal but we don't want to let the browser mess up the HTML for example
291                                 // some browsers add &nbsp; to P tags etc
292                                 if (editor.hasEventListeners('PastePostProcess') && !args.isDefaultPrevented()) {
293                                         // We need to attach the element to the DOM so Sizzle selectors work on the contents
294                                         var tempBody = dom.add(editor.getBody(), 'div', {style: 'display:none'}, html);
295                                         args = editor.fire('PastePostProcess', {node: tempBody});
296                                         dom.remove(tempBody);
297                                         html = args.node.innerHTML;
298                                 }
299
300                                 if (!args.isDefaultPrevented()) {
301                                         editor.insertContent(html, {merge: editor.settings.paste_merge_formats !== false, data: {paste: true}});
302                                 }
303                         }
304                 }
305
306                 /**
307                  * Pastes the specified text. This means that the plain text is processed
308                  * and converted into BR and P elements. It will fire paste events for custom filtering.
309                  *
310                  * @param {String} text Text to paste as the current selection location.
311                  */
312                 function pasteText(text) {
313                         text = editor.dom.encode(text).replace(/\r\n/g, '\n');
314
315                         var startBlock = editor.dom.getParent(editor.selection.getStart(), editor.dom.isBlock);
316
317                         // Create start block html for example <p attr="value">
318                         var forcedRootBlockName = editor.settings.forced_root_block;
319                         var forcedRootBlockStartHtml;
320                         if (forcedRootBlockName) {
321                                 forcedRootBlockStartHtml = editor.dom.createHTML(forcedRootBlockName, editor.settings.forced_root_block_attrs);
322                                 forcedRootBlockStartHtml = forcedRootBlockStartHtml.substr(0, forcedRootBlockStartHtml.length - 3) + '>';
323                         }
324
325                         if ((startBlock && /^(PRE|DIV)$/.test(startBlock.nodeName)) || !forcedRootBlockName) {
326                                 text = Utils.filter(text, [
327                                         [/\n/g, "<br>"]
328                                 ]);
329                         } else {
330                                 text = Utils.filter(text, [
331                                         [/\n\n/g, "</p>" + forcedRootBlockStartHtml],
332                                         [/^(.*<\/p>)(<p>)$/, forcedRootBlockStartHtml + '$1'],
333                                         [/\n/g, "<br />"]
334                                 ]);
335
336                                 if (text.indexOf('<p>') != -1) {
337                                         text = forcedRootBlockStartHtml + text;
338                                 }
339                         }
340
341                         pasteHtml(text);
342                 }
343
344                 /**
345                  * Creates a paste bin element as close as possible to the current caret location and places the focus inside that element
346                  * so that when the real paste event occurs the contents gets inserted into this element
347                  * instead of the current editor selection element.
348                  */
349                 function createPasteBin() {
350                         var dom = editor.dom, body = editor.getBody();
351                         var viewport = editor.dom.getViewPort(editor.getWin()), scrollTop = viewport.y, top = 20;
352                         var scrollContainer;
353
354                         lastRng = editor.selection.getRng();
355
356                         if (editor.inline) {
357                                 scrollContainer = editor.selection.getScrollContainer();
358
359                                 // Can't always rely on scrollTop returning a useful value.
360                                 // It returns 0 if the browser doesn't support scrollTop for the element or is non-scrollable
361                                 if (scrollContainer && scrollContainer.scrollTop > 0) {
362                                         scrollTop = scrollContainer.scrollTop;
363                                 }
364                         }
365
366                         /**
367                          * Returns the rect of the current caret if the caret is in an empty block before a
368                          * BR we insert a temporary invisible character that we get the rect this way we always get a proper rect.
369                          *
370                          * TODO: This might be useful in core.
371                          */
372                         function getCaretRect(rng) {
373                                 var rects, textNode, node, container = rng.startContainer;
374
375                                 rects = rng.getClientRects();
376                                 if (rects.length) {
377                                         return rects[0];
378                                 }
379
380                                 if (!rng.collapsed || container.nodeType != 1) {
381                                         return;
382                                 }
383
384                                 node = container.childNodes[lastRng.startOffset];
385
386                                 // Skip empty whitespace nodes
387                                 while (node && node.nodeType == 3 && !node.data.length) {
388                                         node = node.nextSibling;
389                                 }
390
391                                 if (!node) {
392                                         return;
393                                 }
394
395                                 // Check if the location is |<br>
396                                 // TODO: Might need to expand this to say |<table>
397                                 if (node.tagName == 'BR') {
398                                         textNode = dom.doc.createTextNode('\uFEFF');
399                                         node.parentNode.insertBefore(textNode, node);
400
401                                         rng = dom.createRng();
402                                         rng.setStartBefore(textNode);
403                                         rng.setEndAfter(textNode);
404
405                                         rects = rng.getClientRects();
406                                         dom.remove(textNode);
407                                 }
408
409                                 if (rects.length) {
410                                         return rects[0];
411                                 }
412                         }
413
414                         // Calculate top cordinate this is needed to avoid scrolling to top of document
415                         // We want the paste bin to be as close to the caret as possible to avoid scrolling
416                         if (lastRng.getClientRects) {
417                                 var rect = getCaretRect(lastRng);
418
419                                 if (rect) {
420                                         // Client rects gets us closes to the actual
421                                         // caret location in for example a wrapped paragraph block
422                                         top = scrollTop + (rect.top - dom.getPos(body).y);
423                                 } else {
424                                         top = scrollTop;
425
426                                         // Check if we can find a closer location by checking the range element
427                                         var container = lastRng.startContainer;
428                                         if (container) {
429                                                 if (container.nodeType == 3 && container.parentNode != body) {
430                                                         container = container.parentNode;
431                                                 }
432
433                                                 if (container.nodeType == 1) {
434                                                         top = dom.getPos(container, scrollContainer || body).y;
435                                                 }
436                                         }
437                                 }
438                         }
439
440                         // Create a pastebin
441                         pasteBinElm = dom.add(editor.getBody(), 'div', {
442                                 id: "mcepastebin",
443                                 contentEditable: true,
444                                 "data-mce-bogus": "all",
445                                 style: 'position: absolute; top: ' + top + 'px;' +
446                                         'width: 10px; height: 10px; overflow: hidden; opacity: 0'
447                         }, pasteBinDefaultContent);
448
449                         // Move paste bin out of sight since the controlSelection rect gets displayed otherwise on IE and Gecko
450                         if (Env.ie || Env.gecko) {
451                                 dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) == 'rtl' ? 0xFFFF : -0xFFFF);
452                         }
453
454                         // Prevent focus events from bubbeling fixed FocusManager issues
455                         dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function(e) {
456                                 e.stopPropagation();
457                         });
458
459                         pasteBinElm.focus();
460                         editor.selection.select(pasteBinElm, true);
461                 }
462
463                 /**
464                  * Removes the paste bin if it exists.
465                  */
466                 function removePasteBin() {
467                         if (pasteBinElm) {
468                                 var pasteBinClone;
469
470                                 // WebKit/Blink might clone the div so
471                                 // lets make sure we remove all clones
472                                 // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
473                                 while ((pasteBinClone = editor.dom.get('mcepastebin'))) {
474                                         editor.dom.remove(pasteBinClone);
475                                         editor.dom.unbind(pasteBinClone);
476                                 }
477
478                                 if (lastRng) {
479                                         editor.selection.setRng(lastRng);
480                                 }
481                         }
482
483                         pasteBinElm = lastRng = null;
484                 }
485
486                 /**
487                  * Returns the contents of the paste bin as a HTML string.
488                  *
489                  * @return {String} Get the contents of the paste bin.
490                  */
491                 function getPasteBinHtml() {
492                         var html = '', pasteBinClones, i, clone, cloneHtml;
493
494                         // Since WebKit/Chrome might clone the paste bin when pasting
495                         // for example: <img style="float: right"> we need to check if any of them contains some useful html.
496                         // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
497                         pasteBinClones = editor.dom.select('div[id=mcepastebin]');
498                         for (i = 0; i < pasteBinClones.length; i++) {
499                                 clone = pasteBinClones[i];
500
501                                 // Pasting plain text produces pastebins in pastebinds makes sence right!?
502                                 if (clone.firstChild && clone.firstChild.id == 'mcepastebin') {
503                                         clone = clone.firstChild;
504                                 }
505
506                                 cloneHtml = clone.innerHTML;
507                                 if (html != pasteBinDefaultContent) {
508                                         html += cloneHtml;
509                                 }
510                         }
511
512                         return html;
513                 }
514
515                 /**
516                  * Some Windows 10/Edge versions will return a double encoded string. This checks if the
517                  * content has this odd encoding and decodes it.
518                  */
519                 function decodeEdgeData(data) {
520                         var i, out, fingerprint, code;
521
522                         // Check if data is encoded
523                         fingerprint = [25942, 29554, 28521, 14958];
524                         for (i = 0; i < fingerprint.length; i++) {
525                                 if (data.charCodeAt(i) != fingerprint[i]) {
526                                         return data;
527                                 }
528                         }
529
530                         // Decode UTF-16 to UTF-8
531                         out = '';
532                         for (i = 0; i < data.length; i++) {
533                                 code = data.charCodeAt(i);
534
535                                 /*eslint no-bitwise:0*/
536                                 out += String.fromCharCode((code & 0x00FF));
537                                 out += String.fromCharCode((code & 0xFF00) >> 8);
538                         }
539
540                         // Decode UTF-8
541                         return decodeURIComponent(escape(out));
542                 }
543
544                 /**
545                  * Extracts HTML contents from within a fragment.
546                  */
547                 function extractFragment(data) {
548                         var idx, startFragment, endFragment;
549
550                         startFragment = '<!--StartFragment-->';
551                         idx = data.indexOf(startFragment);
552                         if (idx !== -1) {
553                                 data = data.substr(idx + startFragment.length);
554                         }
555
556                         endFragment = '<!--EndFragment-->';
557                         idx = data.indexOf(endFragment);
558                         if (idx !== -1) {
559                                 data = data.substr(0, idx);
560                         }
561
562                         return data;
563                 }
564
565                 /**
566                  * Gets various content types out of a datatransfer object.
567                  *
568                  * @param {DataTransfer} dataTransfer Event fired on paste.
569                  * @return {Object} Object with mime types and data for those mime types.
570                  */
571                 function getDataTransferItems(dataTransfer) {
572                         var items = {};
573
574                         if (dataTransfer) {
575                                 // Use old WebKit/IE API
576                                 if (dataTransfer.getData) {
577                                         var legacyText = dataTransfer.getData('Text');
578                                         if (legacyText && legacyText.length > 0) {
579                                                 if (legacyText.indexOf(mceInternalUrlPrefix) == -1) {
580                                                         items['text/plain'] = legacyText;
581                                                 }
582                                         }
583                                 }
584
585                                 if (dataTransfer.types) {
586                                         for (var i = 0; i < dataTransfer.types.length; i++) {
587                                                 var contentType = dataTransfer.types[i],
588                                                         data = dataTransfer.getData(contentType);
589
590                                                 if (contentType == 'text/html') {
591                                                         data = extractFragment(decodeEdgeData(data));
592                                                 }
593
594                                                 items[contentType] = data;
595                                         }
596                                 }
597                         }
598
599                         return items;
600                 }
601
602                 /**
603                  * Gets various content types out of the Clipboard API. It will also get the
604                  * plain text using older IE and WebKit API:s.
605                  *
606                  * @param {ClipboardEvent} clipboardEvent Event fired on paste.
607                  * @return {Object} Object with mime types and data for those mime types.
608                  */
609                 function getClipboardContent(clipboardEvent) {
610                         return getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);
611                 }
612
613                 /**
614                  * Checks if the clipboard contains image data if it does it will take that data
615                  * and convert it into a data url image and paste that image at the caret location.
616                  *
617                  * @param  {ClipboardEvent} e Paste/drop event object.
618                  * @param  {DOMRange} rng Optional rng object to move selection to.
619                  * @return {Boolean} true/false if the image data was found or not.
620                  */
621                 function pasteImageData(e, rng) {
622                         var dataTransfer = e.clipboardData || e.dataTransfer;
623
624                         function processItems(items) {
625                                 var i, item, reader, hadImage = false;
626
627                                 function pasteImage(reader) {
628                                         if (rng) {
629                                                 editor.selection.setRng(rng);
630                                                 rng = null;
631                                         }
632
633                                         pasteHtml('<img src="' + reader.result + '">');
634                                 }
635
636                                 if (items) {
637                                         for (i = 0; i < items.length; i++) {
638                                                 item = items[i];
639
640                                                 if (/^image\/(jpeg|png|gif|bmp)$/.test(item.type)) {
641                                                         reader = new FileReader();
642                                                         reader.onload = pasteImage.bind(null, reader);
643                                                         reader.readAsDataURL(item.getAsFile ? item.getAsFile() : item);
644
645                                                         e.preventDefault();
646                                                         hadImage = true;
647                                                 }
648                                         }
649                                 }
650
651                                 return hadImage;
652                         }
653
654                         if (editor.settings.paste_data_images && dataTransfer) {
655                                 return processItems(dataTransfer.items) || processItems(dataTransfer.files);
656                         }
657                 }
658
659                 /**
660                  * Chrome on Android doesn't support proper clipboard access so we have no choice but to allow the browser default behavior.
661                  *
662                  * @param {Event} e Paste event object to check if it contains any data.
663                  * @return {Boolean} true/false if the clipboard is empty or not.
664                  */
665                 function isBrokenAndroidClipboardEvent(e) {
666                         var clipboardData = e.clipboardData;
667
668                         return navigator.userAgent.indexOf('Android') != -1 && clipboardData && clipboardData.items && clipboardData.items.length === 0;
669                 }
670
671                 function getCaretRangeFromEvent(e) {
672                         return RangeUtils.getCaretRangeFromPoint(e.clientX, e.clientY, editor.getDoc());
673                 }
674
675                 function hasContentType(clipboardContent, mimeType) {
676                         return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
677                 }
678
679                 function isKeyboardPasteEvent(e) {
680                         return (VK.metaKeyPressed(e) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45);
681                 }
682
683                 function registerEventHandlers() {
684                         editor.on('keydown', function(e) {
685                                 function removePasteBinOnKeyUp(e) {
686                                         // Ctrl+V or Shift+Insert
687                                         if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
688                                                 removePasteBin();
689                                         }
690                                 }
691
692                                 // Ctrl+V or Shift+Insert
693                                 if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
694                                         keyboardPastePlainTextState = e.shiftKey && e.keyCode == 86;
695
696                                         // Edge case on Safari on Mac where it doesn't handle Cmd+Shift+V correctly
697                                         // it fires the keydown but no paste or keyup so we are left with a paste bin
698                                         if (keyboardPastePlainTextState && Env.webkit && navigator.userAgent.indexOf('Version/') != -1) {
699                                                 return;
700                                         }
701
702                                         // Prevent undoManager keydown handler from making an undo level with the pastebin in it
703                                         e.stopImmediatePropagation();
704
705                                         keyboardPasteTimeStamp = new Date().getTime();
706
707                                         // IE doesn't support Ctrl+Shift+V and it doesn't even produce a paste event
708                                         // so lets fake a paste event and let IE use the execCommand/dataTransfer methods
709                                         if (Env.ie && keyboardPastePlainTextState) {
710                                                 e.preventDefault();
711                                                 editor.fire('paste', {ieFake: true});
712                                                 return;
713                                         }
714
715                                         removePasteBin();
716                                         createPasteBin();
717
718                                         // Remove pastebin if we get a keyup and no paste event
719                                         // For example pasting a file in IE 11 will not produce a paste event
720                                         editor.once('keyup', removePasteBinOnKeyUp);
721                                         editor.once('paste', function() {
722                                                 editor.off('keyup', removePasteBinOnKeyUp);
723                                         });
724                                 }
725                         });
726
727                         editor.on('paste', function(e) {
728                                 // Getting content from the Clipboard can take some time
729                                 var clipboardTimer = new Date().getTime();
730                                 var clipboardContent = getClipboardContent(e);
731                                 var clipboardDelay = new Date().getTime() - clipboardTimer;
732
733                                 var isKeyBoardPaste = (new Date().getTime() - keyboardPasteTimeStamp - clipboardDelay) < 1000;
734                                 var plainTextMode = self.pasteFormat == "text" || keyboardPastePlainTextState;
735
736                                 keyboardPastePlainTextState = false;
737
738                                 if (e.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e)) {
739                                         removePasteBin();
740                                         return;
741                                 }
742
743                                 if (pasteImageData(e)) {
744                                         removePasteBin();
745                                         return;
746                                 }
747
748                                 // Not a keyboard paste prevent default paste and try to grab the clipboard contents using different APIs
749                                 if (!isKeyBoardPaste) {
750                                         e.preventDefault();
751                                 }
752
753                                 // Try IE only method if paste isn't a keyboard paste
754                                 if (Env.ie && (!isKeyBoardPaste || e.ieFake)) {
755                                         createPasteBin();
756
757                                         editor.dom.bind(pasteBinElm, 'paste', function(e) {
758                                                 e.stopPropagation();
759                                         });
760
761                                         editor.getDoc().execCommand('Paste', false, null);
762                                         clipboardContent["text/html"] = getPasteBinHtml();
763                                 }
764
765                                 setTimeout(function() {
766                                         var content;
767
768                                         // Grab HTML from Clipboard API or paste bin as a fallback
769                                         if (hasContentType(clipboardContent, 'text/html')) {
770                                                 content = clipboardContent['text/html'];
771                                         } else {
772                                                 content = getPasteBinHtml();
773
774                                                 // If paste bin is empty try using plain text mode
775                                                 // since that is better than nothing right
776                                                 if (content == pasteBinDefaultContent) {
777                                                         plainTextMode = true;
778                                                 }
779                                         }
780
781                                         content = Utils.trimHtml(content);
782
783                                         // WebKit has a nice bug where it clones the paste bin if you paste from for example notepad
784                                         // so we need to force plain text mode in this case
785                                         if (pasteBinElm && pasteBinElm.firstChild && pasteBinElm.firstChild.id === 'mcepastebin') {
786                                                 plainTextMode = true;
787                                         }
788
789                                         removePasteBin();
790
791                                         // If we got nothing from clipboard API and pastebin then we could try the last resort: plain/text
792                                         if (!content.length) {
793                                                 plainTextMode = true;
794                                         }
795
796                                         // Grab plain text from Clipboard API or convert existing HTML to plain text
797                                         if (plainTextMode) {
798                                                 // Use plain text contents from Clipboard API unless the HTML contains paragraphs then
799                                                 // we should convert the HTML to plain text since works better when pasting HTML/Word contents as plain text
800                                                 if (hasContentType(clipboardContent, 'text/plain') && content.indexOf('</p>') == -1) {
801                                                         content = clipboardContent['text/plain'];
802                                                 } else {
803                                                         content = Utils.innerText(content);
804                                                 }
805                                         }
806
807                                         // If the content is the paste bin default HTML then it was
808                                         // impossible to get the cliboard data out.
809                                         if (content == pasteBinDefaultContent) {
810                                                 if (!isKeyBoardPaste) {
811                                                         editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.');
812                                                 }
813
814                                                 return;
815                                         }
816
817                                         if (plainTextMode) {
818                                                 pasteText(content);
819                                         } else {
820                                                 pasteHtml(content);
821                                         }
822                                 }, 0);
823                         });
824
825                         editor.on('dragstart dragend', function(e) {
826                                 draggingInternally = e.type == 'dragstart';
827                         });
828
829                         editor.on('drop', function(e) {
830                                 var rng = getCaretRangeFromEvent(e);
831
832                                 if (e.isDefaultPrevented() || draggingInternally) {
833                                         return;
834                                 }
835
836                                 if (pasteImageData(e, rng)) {
837                                         return;
838                                 }
839
840                                 if (rng && editor.settings.paste_filter_drop !== false) {
841                                         var dropContent = getDataTransferItems(e.dataTransfer);
842                                         var content = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain'];
843
844                                         if (content) {
845                                                 e.preventDefault();
846
847                                                 editor.undoManager.transact(function() {
848                                                         if (dropContent['mce-internal']) {
849                                                                 editor.execCommand('Delete');
850                                                         }
851
852                                                         editor.selection.setRng(rng);
853
854                                                         content = Utils.trimHtml(content);
855
856                                                         if (!dropContent['text/html']) {
857                                                                 pasteText(content);
858                                                         } else {
859                                                                 pasteHtml(content);
860                                                         }
861                                                 });
862                                         }
863                                 }
864                         });
865
866                         editor.on('dragover dragend', function(e) {
867                                 if (editor.settings.paste_data_images) {
868                                         e.preventDefault();
869                                 }
870                         });
871                 }
872
873                 self.pasteHtml = pasteHtml;
874                 self.pasteText = pasteText;
875
876                 editor.on('preInit', function() {
877                         registerEventHandlers();
878
879                         // Remove all data images from paste for example from Gecko
880                         // except internal images like video elements
881                         editor.parser.addNodeFilter('img', function(nodes, name, args) {
882                                 function isPasteInsert(args) {
883                                         return args.data && args.data.paste === true;
884                                 }
885
886                                 function remove(node) {
887                                         if (!node.attr('data-mce-object') && src !== Env.transparentSrc) {
888                                                 node.remove();
889                                         }
890                                 }
891
892                                 function isWebKitFakeUrl(src) {
893                                         return src.indexOf("webkit-fake-url") === 0;
894                                 }
895
896                                 function isDataUri(src) {
897                                         return src.indexOf("data:") === 0;
898                                 }
899
900                                 if (!editor.settings.paste_data_images && isPasteInsert(args)) {
901                                         var i = nodes.length;
902
903                                         while (i--) {
904                                                 var src = nodes[i].attributes.map.src;
905
906                                                 if (!src) {
907                                                         continue;
908                                                 }
909
910                                                 // Safari on Mac produces webkit-fake-url see: https://bugs.webkit.org/show_bug.cgi?id=49141
911                                                 if (isWebKitFakeUrl(src)) {
912                                                         remove(nodes[i]);
913                                                 } else if (!editor.settings.allow_html_data_urls && isDataUri(src)) {
914                                                         remove(nodes[i]);
915                                                 }
916                                         }
917                                 }
918                         });
919                 });
920         };
921 });
922
923 // Included from: js/tinymce/plugins/paste/classes/WordFilter.js
924
925 /**
926  * WordFilter.js
927  *
928  * Released under LGPL License.
929  * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
930  *
931  * License: http://www.tinymce.com/license
932  * Contributing: http://www.tinymce.com/contributing
933  */
934
935 /**
936  * This class parses word HTML into proper TinyMCE markup.
937  *
938  * @class tinymce.pasteplugin.WordFilter
939  * @private
940  */
941 define("tinymce/pasteplugin/WordFilter", [
942         "tinymce/util/Tools",
943         "tinymce/html/DomParser",
944         "tinymce/html/Schema",
945         "tinymce/html/Serializer",
946         "tinymce/html/Node",
947         "tinymce/pasteplugin/Utils"
948 ], function(Tools, DomParser, Schema, Serializer, Node, Utils) {
949         /**
950          * Checks if the specified content is from any of the following sources: MS Word/Office 365/Google docs.
951          */
952         function isWordContent(content) {
953                 return (
954                         (/<font face="Times New Roman"|class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i).test(content) ||
955                         (/class="OutlineElement/).test(content) ||
956                         (/id="?docs\-internal\-guid\-/.test(content))
957                 );
958         }
959
960         /**
961          * Checks if the specified text starts with "1. " or "a. " etc.
962          */
963         function isNumericList(text) {
964                 var found, patterns;
965
966                 patterns = [
967                         /^[IVXLMCD]{1,2}\.[ \u00a0]/,  // Roman upper case
968                         /^[ivxlmcd]{1,2}\.[ \u00a0]/,  // Roman lower case
969                         /^[a-z]{1,2}[\.\)][ \u00a0]/,  // Alphabetical a-z
970                         /^[A-Z]{1,2}[\.\)][ \u00a0]/,  // Alphabetical A-Z
971                         /^[0-9]+\.[ \u00a0]/,          // Numeric lists
972                         /^[\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d]+\.[ \u00a0]/, // Japanese
973                         /^[\u58f1\u5f10\u53c2\u56db\u4f0d\u516d\u4e03\u516b\u4e5d\u62fe]+\.[ \u00a0]/  // Chinese
974                 ];
975
976                 text = text.replace(/^[\u00a0 ]+/, '');
977
978                 Tools.each(patterns, function(pattern) {
979                         if (pattern.test(text)) {
980                                 found = true;
981                                 return false;
982                         }
983                 });
984
985                 return found;
986         }
987
988         function isBulletList(text) {
989                 return /^[\s\u00a0]*[\u2022\u00b7\u00a7\u25CF]\s*/.test(text);
990         }
991
992         function WordFilter(editor) {
993                 var settings = editor.settings;
994
995                 editor.on('BeforePastePreProcess', function(e) {
996                         var content = e.content, retainStyleProperties, validStyles;
997
998                         // Remove google docs internal guid markers
999                         content = content.replace(/<b[^>]+id="?docs-internal-[^>]*>/gi, '');
1000                         content = content.replace(/<br class="?Apple-interchange-newline"?>/gi, '');
1001
1002                         retainStyleProperties = settings.paste_retain_style_properties;
1003                         if (retainStyleProperties) {
1004                                 validStyles = Tools.makeMap(retainStyleProperties.split(/[, ]/));
1005                         }
1006
1007                         /**
1008                          * Converts fake bullet and numbered lists to real semantic OL/UL.
1009                          *
1010                          * @param {tinymce.html.Node} node Root node to convert children of.
1011                          */
1012                         function convertFakeListsToProperLists(node) {
1013                                 var currentListNode, prevListNode, lastLevel = 1;
1014
1015                                 function getText(node) {
1016                                         var txt = '';
1017
1018                                         if (node.type === 3) {
1019                                                 return node.value;
1020                                         }
1021
1022                                         if ((node = node.firstChild)) {
1023                                                 do {
1024                                                         txt += getText(node);
1025                                                 } while ((node = node.next));
1026                                         }
1027
1028                                         return txt;
1029                                 }
1030
1031                                 function trimListStart(node, regExp) {
1032                                         if (node.type === 3) {
1033                                                 if (regExp.test(node.value)) {
1034                                                         node.value = node.value.replace(regExp, '');
1035                                                         return false;
1036                                                 }
1037                                         }
1038
1039                                         if ((node = node.firstChild)) {
1040                                                 do {
1041                                                         if (!trimListStart(node, regExp)) {
1042                                                                 return false;
1043                                                         }
1044                                                 } while ((node = node.next));
1045                                         }
1046
1047                                         return true;
1048                                 }
1049
1050                                 function removeIgnoredNodes(node) {
1051                                         if (node._listIgnore) {
1052                                                 node.remove();
1053                                                 return;
1054                                         }
1055
1056                                         if ((node = node.firstChild)) {
1057                                                 do {
1058                                                         removeIgnoredNodes(node);
1059                                                 } while ((node = node.next));
1060                                         }
1061                                 }
1062
1063                                 function convertParagraphToLi(paragraphNode, listName, start) {
1064                                         var level = paragraphNode._listLevel || lastLevel;
1065
1066                                         // Handle list nesting
1067                                         if (level != lastLevel) {
1068                                                 if (level < lastLevel) {
1069                                                         // Move to parent list
1070                                                         if (currentListNode) {
1071                                                                 currentListNode = currentListNode.parent.parent;
1072                                                         }
1073                                                 } else {
1074                                                         // Create new list
1075                                                         prevListNode = currentListNode;
1076                                                         currentListNode = null;
1077                                                 }
1078                                         }
1079
1080                                         if (!currentListNode || currentListNode.name != listName) {
1081                                                 prevListNode = prevListNode || currentListNode;
1082                                                 currentListNode = new Node(listName, 1);
1083
1084                                                 if (start > 1) {
1085                                                         currentListNode.attr('start', '' + start);
1086                                                 }
1087
1088                                                 paragraphNode.wrap(currentListNode);
1089                                         } else {
1090                                                 currentListNode.append(paragraphNode);
1091                                         }
1092
1093                                         paragraphNode.name = 'li';
1094
1095                                         // Append list to previous list if it exists
1096                                         if (level > lastLevel && prevListNode) {
1097                                                 prevListNode.lastChild.append(currentListNode);
1098                                         }
1099
1100                                         lastLevel = level;
1101
1102                                         // Remove start of list item "1. " or "&middot; " etc
1103                                         removeIgnoredNodes(paragraphNode);
1104                                         trimListStart(paragraphNode, /^\u00a0+/);
1105                                         trimListStart(paragraphNode, /^\s*([\u2022\u00b7\u00a7\u25CF]|\w+\.)/);
1106                                         trimListStart(paragraphNode, /^\u00a0+/);
1107                                 }
1108
1109                                 // Build a list of all root level elements before we start
1110                                 // altering them in the loop below.
1111                                 var elements = [], child = node.firstChild;
1112                                 while (typeof child !== 'undefined' && child !== null) {
1113                                         elements.push(child);
1114
1115                                         child = child.walk();
1116                                         if (child !== null) {
1117                                                 while (typeof child !== 'undefined' && child.parent !== node) {
1118                                                         child = child.walk();
1119                                                 }
1120                                         }
1121                                 }
1122
1123                                 for (var i = 0; i < elements.length; i++) {
1124                                         node = elements[i];
1125
1126                                         if (node.name == 'p' && node.firstChild) {
1127                                                 // Find first text node in paragraph
1128                                                 var nodeText = getText(node);
1129
1130                                                 // Detect unordered lists look for bullets
1131                                                 if (isBulletList(nodeText)) {
1132                                                         convertParagraphToLi(node, 'ul');
1133                                                         continue;
1134                                                 }
1135
1136                                                 // Detect ordered lists 1., a. or ixv.
1137                                                 if (isNumericList(nodeText)) {
1138                                                         // Parse OL start number
1139                                                         var matches = /([0-9]+)\./.exec(nodeText);
1140                                                         var start = 1;
1141                                                         if (matches) {
1142                                                                 start = parseInt(matches[1], 10);
1143                                                         }
1144
1145                                                         convertParagraphToLi(node, 'ol', start);
1146                                                         continue;
1147                                                 }
1148
1149                                                 // Convert paragraphs marked as lists but doesn't look like anything
1150                                                 if (node._listLevel) {
1151                                                         convertParagraphToLi(node, 'ul', 1);
1152                                                         continue;
1153                                                 }
1154
1155                                                 currentListNode = null;
1156                                         } else {
1157                                                 // If the root level element isn't a p tag which can be
1158                                                 // processed by convertParagraphToLi, it interrupts the
1159                                                 // lists, causing a new list to start instead of having
1160                                                 // elements from the next list inserted above this tag.
1161                                                 prevListNode = currentListNode;
1162                                                 currentListNode = null;
1163                                         }
1164                                 }
1165                         }
1166
1167                         function filterStyles(node, styleValue) {
1168                                 var outputStyles = {}, matches, styles = editor.dom.parseStyle(styleValue);
1169
1170                                 Tools.each(styles, function(value, name) {
1171                                         // Convert various MS styles to W3C styles
1172                                         switch (name) {
1173                                                 case 'mso-list':
1174                                                         // Parse out list indent level for lists
1175                                                         matches = /\w+ \w+([0-9]+)/i.exec(styleValue);
1176                                                         if (matches) {
1177                                                                 node._listLevel = parseInt(matches[1], 10);
1178                                                         }
1179
1180                                                         // Remove these nodes <span style="mso-list:Ignore">o</span>
1181                                                         // Since the span gets removed we mark the text node and the span
1182                                                         if (/Ignore/i.test(value) && node.firstChild) {
1183                                                                 node._listIgnore = true;
1184                                                                 node.firstChild._listIgnore = true;
1185                                                         }
1186
1187                                                         break;
1188
1189                                                 case "horiz-align":
1190                                                         name = "text-align";
1191                                                         break;
1192
1193                                                 case "vert-align":
1194                                                         name = "vertical-align";
1195                                                         break;
1196
1197                                                 case "font-color":
1198                                                 case "mso-foreground":
1199                                                         name = "color";
1200                                                         break;
1201
1202                                                 case "mso-background":
1203                                                 case "mso-highlight":
1204                                                         name = "background";
1205                                                         break;
1206
1207                                                 case "font-weight":
1208                                                 case "font-style":
1209                                                         if (value != "normal") {
1210                                                                 outputStyles[name] = value;
1211                                                         }
1212                                                         return;
1213
1214                                                 case "mso-element":
1215                                                         // Remove track changes code
1216                                                         if (/^(comment|comment-list)$/i.test(value)) {
1217                                                                 node.remove();
1218                                                                 return;
1219                                                         }
1220
1221                                                         break;
1222                                         }
1223
1224                                         if (name.indexOf('mso-comment') === 0) {
1225                                                 node.remove();
1226                                                 return;
1227                                         }
1228
1229                                         // Never allow mso- prefixed names
1230                                         if (name.indexOf('mso-') === 0) {
1231                                                 return;
1232                                         }
1233
1234                                         // Output only valid styles
1235                                         if (retainStyleProperties == "all" || (validStyles && validStyles[name])) {
1236                                                 outputStyles[name] = value;
1237                                         }
1238                                 });
1239
1240                                 // Convert bold style to "b" element
1241                                 if (/(bold)/i.test(outputStyles["font-weight"])) {
1242                                         delete outputStyles["font-weight"];
1243                                         node.wrap(new Node("b", 1));
1244                                 }
1245
1246                                 // Convert italic style to "i" element
1247                                 if (/(italic)/i.test(outputStyles["font-style"])) {
1248                                         delete outputStyles["font-style"];
1249                                         node.wrap(new Node("i", 1));
1250                                 }
1251
1252                                 // Serialize the styles and see if there is something left to keep
1253                                 outputStyles = editor.dom.serializeStyle(outputStyles, node.name);
1254                                 if (outputStyles) {
1255                                         return outputStyles;
1256                                 }
1257
1258                                 return null;
1259                         }
1260
1261                         if (settings.paste_enable_default_filters === false) {
1262                                 return;
1263                         }
1264
1265                         // Detect is the contents is Word junk HTML
1266                         if (isWordContent(e.content)) {
1267                                 e.wordContent = true; // Mark it for other processors
1268
1269                                 // Remove basic Word junk
1270                                 content = Utils.filter(content, [
1271                                         // Word comments like conditional comments etc
1272                                         /<!--[\s\S]+?-->/gi,
1273
1274                                         // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
1275                                         // MS Office namespaced tags, and a few other tags
1276                                         /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
1277
1278                                         // Convert <s> into <strike> for line-though
1279                                         [/<(\/?)s>/gi, "<$1strike>"],
1280
1281                                         // Replace nsbp entites to char since it's easier to handle
1282                                         [/&nbsp;/gi, "\u00a0"],
1283
1284                                         // Convert <span style="mso-spacerun:yes">___</span> to string of alternating
1285                                         // breaking/non-breaking spaces of same length
1286                                         [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
1287                                                 function(str, spaces) {
1288                                                         return (spaces.length > 0) ?
1289                                                                 spaces.replace(/./, " ").slice(Math.floor(spaces.length / 2)).split("").join("\u00a0") : "";
1290                                                 }
1291                                         ]
1292                                 ]);
1293
1294                                 var validElements = settings.paste_word_valid_elements;
1295                                 if (!validElements) {
1296                                         validElements = (
1297                                                 '-strong/b,-em/i,-u,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' +
1298                                                 '-p/div,-a[href|name],sub,sup,strike,br,del,table[width],tr,' +
1299                                                 'td[colspan|rowspan|width],th[colspan|rowspan|width],thead,tfoot,tbody'
1300                                         );
1301                                 }
1302
1303                                 // Setup strict schema
1304                                 var schema = new Schema({
1305                                         valid_elements: validElements,
1306                                         valid_children: '-li[p]'
1307                                 });
1308
1309                                 // Add style/class attribute to all element rules since the user might have removed them from
1310                                 // paste_word_valid_elements config option and we need to check them for properties
1311                                 Tools.each(schema.elements, function(rule) {
1312                                         /*eslint dot-notation:0*/
1313                                         if (!rule.attributes["class"]) {
1314                                                 rule.attributes["class"] = {};
1315                                                 rule.attributesOrder.push("class");
1316                                         }
1317
1318                                         if (!rule.attributes.style) {
1319                                                 rule.attributes.style = {};
1320                                                 rule.attributesOrder.push("style");
1321                                         }
1322                                 });
1323
1324                                 // Parse HTML into DOM structure
1325                                 var domParser = new DomParser({}, schema);
1326
1327                                 // Filter styles to remove "mso" specific styles and convert some of them
1328                                 domParser.addAttributeFilter('style', function(nodes) {
1329                                         var i = nodes.length, node;
1330
1331                                         while (i--) {
1332                                                 node = nodes[i];
1333                                                 node.attr('style', filterStyles(node, node.attr('style')));
1334
1335                                                 // Remove pointess spans
1336                                                 if (node.name == 'span' && node.parent && !node.attributes.length) {
1337                                                         node.unwrap();
1338                                                 }
1339                                         }
1340                                 });
1341
1342                                 // Check the class attribute for comments or del items and remove those
1343                                 domParser.addAttributeFilter('class', function(nodes) {
1344                                         var i = nodes.length, node, className;
1345
1346                                         while (i--) {
1347                                                 node = nodes[i];
1348
1349                                                 className = node.attr('class');
1350                                                 if (/^(MsoCommentReference|MsoCommentText|msoDel)$/i.test(className)) {
1351                                                         node.remove();
1352                                                 }
1353
1354                                                 node.attr('class', null);
1355                                         }
1356                                 });
1357
1358                                 // Remove all del elements since we don't want the track changes code in the editor
1359                                 domParser.addNodeFilter('del', function(nodes) {
1360                                         var i = nodes.length;
1361
1362                                         while (i--) {
1363                                                 nodes[i].remove();
1364                                         }
1365                                 });
1366
1367                                 // Keep some of the links and anchors
1368                                 domParser.addNodeFilter('a', function(nodes) {
1369                                         var i = nodes.length, node, href, name;
1370
1371                                         while (i--) {
1372                                                 node = nodes[i];
1373                                                 href = node.attr('href');
1374                                                 name = node.attr('name');
1375
1376                                                 if (href && href.indexOf('#_msocom_') != -1) {
1377                                                         node.remove();
1378                                                         continue;
1379                                                 }
1380
1381                                                 if (href && href.indexOf('file://') === 0) {
1382                                                         href = href.split('#')[1];
1383                                                         if (href) {
1384                                                                 href = '#' + href;
1385                                                         }
1386                                                 }
1387
1388                                                 if (!href && !name) {
1389                                                         node.unwrap();
1390                                                 } else {
1391                                                         // Remove all named anchors that aren't specific to TOC, Footnotes or Endnotes
1392                                                         if (name && !/^_?(?:toc|edn|ftn)/i.test(name)) {
1393                                                                 node.unwrap();
1394                                                                 continue;
1395                                                         }
1396
1397                                                         node.attr({
1398                                                                 href: href,
1399                                                                 name: name
1400                                                         });
1401                                                 }
1402                                         }
1403                                 });
1404
1405                                 // Parse into DOM structure
1406                                 var rootNode = domParser.parse(content);
1407
1408                                 // Process DOM
1409                                 if (settings.paste_convert_word_fake_lists !== false) {
1410                                         convertFakeListsToProperLists(rootNode);
1411                                 }
1412
1413                                 // Serialize DOM back to HTML
1414                                 e.content = new Serializer({
1415                                         validate: settings.validate
1416                                 }, schema).serialize(rootNode);
1417                         }
1418                 });
1419         }
1420
1421         WordFilter.isWordContent = isWordContent;
1422
1423         return WordFilter;
1424 });
1425
1426 // Included from: js/tinymce/plugins/paste/classes/Quirks.js
1427
1428 /**
1429  * Quirks.js
1430  *
1431  * Released under LGPL License.
1432  * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
1433  *
1434  * License: http://www.tinymce.com/license
1435  * Contributing: http://www.tinymce.com/contributing
1436  */
1437
1438 /**
1439  * This class contains various fixes for browsers. These issues can not be feature
1440  * detected since we have no direct control over the clipboard. However we might be able
1441  * to remove some of these fixes once the browsers gets updated/fixed.
1442  *
1443  * @class tinymce.pasteplugin.Quirks
1444  * @private
1445  */
1446 define("tinymce/pasteplugin/Quirks", [
1447         "tinymce/Env",
1448         "tinymce/util/Tools",
1449         "tinymce/pasteplugin/WordFilter",
1450         "tinymce/pasteplugin/Utils"
1451 ], function(Env, Tools, WordFilter, Utils) {
1452         "use strict";
1453
1454         return function(editor) {
1455                 function addPreProcessFilter(filterFunc) {
1456                         editor.on('BeforePastePreProcess', function(e) {
1457                                 e.content = filterFunc(e.content);
1458                         });
1459                 }
1460
1461                 /**
1462                  * Removes BR elements after block elements. IE9 has a nasty bug where it puts a BR element after each
1463                  * block element when pasting from word. This removes those elements.
1464                  *
1465                  * This:
1466                  *  <p>a</p><br><p>b</p>
1467                  *
1468                  * Becomes:
1469                  *  <p>a</p><p>b</p>
1470                  */
1471                 function removeExplorerBrElementsAfterBlocks(html) {
1472                         // Only filter word specific content
1473                         if (!WordFilter.isWordContent(html)) {
1474                                 return html;
1475                         }
1476
1477                         // Produce block regexp based on the block elements in schema
1478                         var blockElements = [];
1479
1480                         Tools.each(editor.schema.getBlockElements(), function(block, blockName) {
1481                                 blockElements.push(blockName);
1482                         });
1483
1484                         var explorerBlocksRegExp = new RegExp(
1485                                 '(?:<br>&nbsp;[\\s\\r\\n]+|<br>)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:<br>&nbsp;[\\s\\r\\n]+|<br>)*',
1486                                 'g'
1487                         );
1488
1489                         // Remove BR:s from: <BLOCK>X</BLOCK><BR>
1490                         html = Utils.filter(html, [
1491                                 [explorerBlocksRegExp, '$1']
1492                         ]);
1493
1494                         // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
1495                         html = Utils.filter(html, [
1496                                 [/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact
1497                                 [/<br>/g, ' '],            // Replace single br elements with space since they are word wrap BR:s
1498                                 [/<BR><BR>/g, '<br>']      // Replace back the double brs but into a single BR
1499                         ]);
1500
1501                         return html;
1502                 }
1503
1504                 /**
1505                  * WebKit has a nasty bug where the all computed styles gets added to style attributes when copy/pasting contents.
1506                  * This fix solves that by simply removing the whole style attribute.
1507                  *
1508                  * The paste_webkit_styles option can be set to specify what to keep:
1509                  *  paste_webkit_styles: "none" // Keep no styles
1510                  *  paste_webkit_styles: "all", // Keep all of them
1511                  *  paste_webkit_styles: "font-weight color" // Keep specific ones
1512                  *
1513                  * @param {String} content Content that needs to be processed.
1514                  * @return {String} Processed contents.
1515                  */
1516                 function removeWebKitStyles(content) {
1517                         // Passthrough all styles from Word and let the WordFilter handle that junk
1518                         if (WordFilter.isWordContent(content)) {
1519                                 return content;
1520                         }
1521
1522                         // Filter away styles that isn't matching the target node
1523                         var webKitStyles = editor.settings.paste_webkit_styles;
1524
1525                         if (editor.settings.paste_remove_styles_if_webkit === false || webKitStyles == "all") {
1526                                 return content;
1527                         }
1528
1529                         if (webKitStyles) {
1530                                 webKitStyles = webKitStyles.split(/[, ]/);
1531                         }
1532
1533                         // Keep specific styles that doesn't match the current node computed style
1534                         if (webKitStyles) {
1535                                 var dom = editor.dom, node = editor.selection.getNode();
1536
1537                                 content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, function(all, before, value, after) {
1538                                         var inputStyles = dom.parseStyle(value, 'span'), outputStyles = {};
1539
1540                                         if (webKitStyles === "none") {
1541                                                 return before + after;
1542                                         }
1543
1544                                         for (var i = 0; i < webKitStyles.length; i++) {
1545                                                 var inputValue = inputStyles[webKitStyles[i]], currentValue = dom.getStyle(node, webKitStyles[i], true);
1546
1547                                                 if (/color/.test(webKitStyles[i])) {
1548                                                         inputValue = dom.toHex(inputValue);
1549                                                         currentValue = dom.toHex(currentValue);
1550                                                 }
1551
1552                                                 if (currentValue != inputValue) {
1553                                                         outputStyles[webKitStyles[i]] = inputValue;
1554                                                 }
1555                                         }
1556
1557                                         outputStyles = dom.serializeStyle(outputStyles, 'span');
1558                                         if (outputStyles) {
1559                                                 return before + ' style="' + outputStyles + '"' + after;
1560                                         }
1561
1562                                         return before + after;
1563                                 });
1564                         } else {
1565                                 // Remove all external styles
1566                                 content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, '$1$3');
1567                         }
1568
1569                         // Keep internal styles
1570                         content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, function(all, before, value, after) {
1571                                 return before + ' style="' + value + '"' + after;
1572                         });
1573
1574                         return content;
1575                 }
1576
1577                 // Sniff browsers and apply fixes since we can't feature detect
1578                 if (Env.webkit) {
1579                         addPreProcessFilter(removeWebKitStyles);
1580                 }
1581
1582                 if (Env.ie) {
1583                         addPreProcessFilter(removeExplorerBrElementsAfterBlocks);
1584                 }
1585         };
1586 });
1587
1588 // Included from: js/tinymce/plugins/paste/classes/Plugin.js
1589
1590 /**
1591  * Plugin.js
1592  *
1593  * Released under LGPL License.
1594  * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
1595  *
1596  * License: http://www.tinymce.com/license
1597  * Contributing: http://www.tinymce.com/contributing
1598  */
1599
1600 /**
1601  * This class contains the tinymce plugin logic for the paste plugin.
1602  *
1603  * @class tinymce.pasteplugin.Plugin
1604  * @private
1605  */
1606 define("tinymce/pasteplugin/Plugin", [
1607         "tinymce/PluginManager",
1608         "tinymce/pasteplugin/Clipboard",
1609         "tinymce/pasteplugin/WordFilter",
1610         "tinymce/pasteplugin/Quirks"
1611 ], function(PluginManager, Clipboard, WordFilter, Quirks) {
1612         var userIsInformed;
1613
1614         PluginManager.add('paste', function(editor) {
1615                 var self = this, clipboard, settings = editor.settings;
1616
1617                 function togglePlainTextPaste() {
1618                         if (clipboard.pasteFormat == "text") {
1619                                 this.active(false);
1620                                 clipboard.pasteFormat = "html";
1621                         } else {
1622                                 clipboard.pasteFormat = "text";
1623                                 this.active(true);
1624
1625                                 if (!userIsInformed) {
1626                                         editor.windowManager.alert(
1627                                                 'Paste is now in plain text mode. Contents will now ' +
1628                                                 'be pasted as plain text until you toggle this option off.'
1629                                         );
1630
1631                                         userIsInformed = true;
1632                                 }
1633                         }
1634                 }
1635
1636                 self.clipboard = clipboard = new Clipboard(editor);
1637                 self.quirks = new Quirks(editor);
1638                 self.wordFilter = new WordFilter(editor);
1639
1640                 if (editor.settings.paste_as_text) {
1641                         self.clipboard.pasteFormat = "text";
1642                 }
1643
1644                 if (settings.paste_preprocess) {
1645                         editor.on('PastePreProcess', function(e) {
1646                                 settings.paste_preprocess.call(self, self, e);
1647                         });
1648                 }
1649
1650                 if (settings.paste_postprocess) {
1651                         editor.on('PastePostProcess', function(e) {
1652                                 settings.paste_postprocess.call(self, self, e);
1653                         });
1654                 }
1655
1656                 editor.addCommand('mceInsertClipboardContent', function(ui, value) {
1657                         if (value.content) {
1658                                 self.clipboard.pasteHtml(value.content);
1659                         }
1660
1661                         if (value.text) {
1662                                 self.clipboard.pasteText(value.text);
1663                         }
1664                 });
1665
1666                 // Block all drag/drop events
1667                 if (editor.paste_block_drop) {
1668                         editor.on('dragend dragover draggesture dragdrop drop drag', function(e) {
1669                                 e.preventDefault();
1670                                 e.stopPropagation();
1671                         });
1672                 }
1673
1674                 // Prevent users from dropping data images on Gecko
1675                 if (!editor.settings.paste_data_images) {
1676                         editor.on('drop', function(e) {
1677                                 var dataTransfer = e.dataTransfer;
1678
1679                                 if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
1680                                         e.preventDefault();
1681                                 }
1682                         });
1683                 }
1684
1685                 editor.addButton('pastetext', {
1686                         icon: 'pastetext',
1687                         tooltip: 'Paste as text',
1688                         onclick: togglePlainTextPaste,
1689                         active: self.clipboard.pasteFormat == "text"
1690                 });
1691
1692                 editor.addMenuItem('pastetext', {
1693                         text: 'Paste as text',
1694                         selectable: true,
1695                         active: clipboard.pasteFormat,
1696                         onclick: togglePlainTextPaste
1697                 });
1698         });
1699 });
1700
1701 expose(["tinymce/pasteplugin/Utils"]);
1702 })(this);