plugin.js 38 KB

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