You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1844 lines
51 KiB

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