4 * Released under LGPL License.
5 * Copyright (c) 1999-2015 Ephox Corp. All rights reserved
7 * License: http://www.tinymce.com/license
8 * Contributing: http://www.tinymce.com/contributing
11 /*jshint maxlen:255 */
13 /*global tinymce:true */
15 tinymce.PluginManager.add('media', function(editor, url) {
17 {regex: /youtu\.be\/([\w\-.]+)/, type: 'iframe', w: 560, h: 314, url: '//www.youtube.com/embed/$1', allowFullscreen: true},
18 {regex: /youtube\.com(.+)v=([^&]+)/, type: 'iframe', w: 560, h: 314, url: '//www.youtube.com/embed/$2', allowFullscreen: true},
19 {regex: /youtube.com\/embed\/([a-z0-9\-_]+)/i, type: 'iframe', w: 560, h: 314, url: '//www.youtube.com/embed/$1', allowFullscreen: true},
20 {regex: /vimeo\.com\/([0-9]+)/, type: 'iframe', w: 425, h: 350, url: '//player.vimeo.com/video/$1?title=0&byline=0&portrait=0&color=8dc7dc', allowfullscreen: true},
21 {regex: /vimeo\.com\/(.*)\/([0-9]+)/, type: "iframe", w: 425, h: 350, url: "//player.vimeo.com/video/$2?title=0&byline=0", allowfullscreen: true},
22 {regex: /maps\.google\.([a-z]{2,3})\/maps\/(.+)msid=(.+)/, type: 'iframe', w: 425, h: 350, url: '//maps.google.com/maps/ms?msid=$2&output=embed"', allowFullscreen: false},
23 {regex: /dailymotion\.com\/video\/([^_]+)/, type: 'iframe', w: 480, h: 270, url: '//www.dailymotion.com/embed/video/$1', allowFullscreen: true}
26 var embedChange = (tinymce.Env.ie && tinymce.Env.ie <= 8) ? 'onChange' : 'onInput';
28 function guessMime(url) {
29 url = url.toLowerCase();
31 if (url.indexOf('.mp3') != -1) {
35 if (url.indexOf('.wav') != -1) {
39 if (url.indexOf('.mp4') != -1) {
43 if (url.indexOf('.webm') != -1) {
47 if (url.indexOf('.ogg') != -1) {
51 if (url.indexOf('.swf') != -1) {
52 return 'application/x-shockwave-flash';
58 function getVideoScriptMatch(src) {
59 var prefixes = editor.settings.media_scripts;
62 for (var i = 0; i < prefixes.length; i++) {
63 if (src.indexOf(prefixes[i].filter) !== -1) {
70 function showDialog() {
71 var win, width, height, data;
73 var generalFormItems = [
81 onchange: function(e) {
82 tinymce.each(e.meta, function(value, key) {
83 win.find('#' + key).value(value);
89 function recalcSize(e) {
90 var widthCtrl, heightCtrl, newWidth, newHeight;
92 widthCtrl = win.find('#width')[0];
93 heightCtrl = win.find('#height')[0];
95 newWidth = widthCtrl.value();
96 newHeight = heightCtrl.value();
98 if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) {
99 if (e.control == widthCtrl) {
100 newHeight = Math.round((newWidth / width) * newHeight);
102 if (!isNaN(newHeight)) {
103 heightCtrl.value(newHeight);
106 newWidth = Math.round((newHeight / height) * newWidth);
108 if (!isNaN(newWidth)) {
109 widthCtrl.value(newWidth);
118 if (editor.settings.media_alt_source !== false) {
119 generalFormItems.push({name: 'source2', type: 'filepicker', filetype: 'media', size: 40, label: 'Alternative source'});
122 if (editor.settings.media_poster !== false) {
123 generalFormItems.push({name: 'poster', type: 'filepicker', filetype: 'image', size: 40, label: 'Poster'});
126 if (editor.settings.media_dimensions !== false) {
127 generalFormItems.push({
134 {name: 'width', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Width'},
135 {type: 'label', text: 'x'},
136 {name: 'height', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Height'},
137 {name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions'}
142 data = getData(editor.selection.getNode());
144 height = data.height;
147 id: 'mcemediasource',
156 function updateValueOnChange() {
157 data = htmlToData(this.value());
158 this.parent().parent().fromJSON(data);
161 embedTextBox[embedChange] = updateValueOnChange;
163 win = editor.windowManager.open({
164 title: 'Insert/edit video',
166 bodyType: 'tabpanel',
171 onShowTab: function() {
172 data = htmlToData(this.next().find('#embed').value());
175 items: generalFormItems
186 onShowTab: function() {
187 this.find('#embed').value(dataToHtml(this.parent().toJSON()));
192 text: 'Paste your embed code below:',
193 forId: 'mcemediasource'
199 onSubmit: function() {
200 var beforeObjects, afterObjects, i, y;
202 beforeObjects = editor.dom.select('img[data-mce-object]');
203 editor.insertContent(dataToHtml(this.toJSON()));
204 afterObjects = editor.dom.select('img[data-mce-object]');
206 // Find new image placeholder so we can select it
207 for (i = 0; i < beforeObjects.length; i++) {
208 for (y = afterObjects.length - 1; y >= 0; y--) {
209 if (beforeObjects[i] == afterObjects[y]) {
210 afterObjects.splice(y, 1);
215 editor.selection.select(afterObjects[0]);
216 editor.nodeChanged();
221 function getSource() {
222 var elm = editor.selection.getNode();
224 if (elm.getAttribute('data-mce-object')) {
225 return editor.selection.getContent();
229 function dataToHtml(data) {
233 tinymce.extend(data, htmlToData(data.embed));
247 data.source1 = editor.convertURL(data.source1, "source");
248 data.source2 = editor.convertURL(data.source2, "source");
249 data.source1mime = guessMime(data.source1);
250 data.source2mime = guessMime(data.source2);
251 data.poster = editor.convertURL(data.poster, "poster");
252 data.flashPlayerUrl = editor.convertURL(url + '/moxieplayer.swf', "movie");
254 tinymce.each(urlPatterns, function(pattern) {
257 if ((match = pattern.regex.exec(data.source1))) {
260 for (i = 0; match[i]; i++) {
261 /*jshint loopfunc:true*/
262 /*eslint no-loop-func:0 */
263 url = url.replace('$' + i, function() {
269 data.type = pattern.type;
270 data.allowFullscreen = pattern.allowFullscreen;
271 data.width = data.width || pattern.w;
272 data.height = data.height || pattern.h;
277 html = updateHtml(data.embed, data, true);
279 var videoScript = getVideoScriptMatch(data.source1);
281 data.type = 'script';
282 data.width = videoScript.width;
283 data.height = videoScript.height;
286 data.width = data.width || 300;
287 data.height = data.height || 150;
289 tinymce.each(data, function(value, key) {
290 data[key] = editor.dom.encode(value);
293 if (data.type == "iframe") {
294 var allowFullscreen = data.allowFullscreen ? ' allowFullscreen="1"' : '';
295 html += '<iframe src="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '"' + allowFullscreen + '></iframe>';
296 } else if (data.source1mime == "application/x-shockwave-flash") {
297 html += '<object data="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '" type="application/x-shockwave-flash">';
300 html += '<img src="' + data.poster + '" width="' + data.width + '" height="' + data.height + '" />';
304 } else if (data.source1mime.indexOf('audio') != -1) {
305 if (editor.settings.audio_template_callback) {
306 html = editor.settings.audio_template_callback(data);
309 '<audio controls="controls" src="' + data.source1 + '">' +
310 (data.source2 ? '\n<source src="' + data.source2 + '"' + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') +
314 } else if (data.type == "script") {
315 html += '<script src="' + data.source1 + '"></script>';
317 if (editor.settings.video_template_callback) {
318 html = editor.settings.video_template_callback(data);
321 '<video width="' + data.width + '" height="' + data.height + '"' + (data.poster ? ' poster="' + data.poster + '"' : '') + ' controls="controls">\n' +
322 '<source src="' + data.source1 + '"' + (data.source1mime ? ' type="' + data.source1mime + '"' : '') + ' />\n' +
323 (data.source2 ? '<source src="' + data.source2 + '"' + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') +
333 function htmlToData(html) {
336 new tinymce.html.SaxParser({
338 allow_conditional_comments: true,
339 special: 'script,noscript',
340 start: function(name, attrs) {
341 if (!data.source1 && name == "param") {
342 data.source1 = attrs.map.movie;
345 if (name == "iframe" || name == "object" || name == "embed" || name == "video" || name == "audio") {
350 data = tinymce.extend(attrs.map, data);
353 if (name == "script") {
354 var videoScript = getVideoScriptMatch(attrs.map.src);
361 source1: attrs.map.src,
362 width: videoScript.width,
363 height: videoScript.height
367 if (name == "source") {
369 data.source1 = attrs.map.src;
370 } else if (!data.source2) {
371 data.source2 = attrs.map.src;
375 if (name == "img" && !data.poster) {
376 data.poster = attrs.map.src;
381 data.source1 = data.source1 || data.src || data.data;
382 data.source2 = data.source2 || '';
383 data.poster = data.poster || '';
388 function getData(element) {
389 if (element.getAttribute('data-mce-object')) {
390 return htmlToData(editor.serializer.serialize(element, {selection: true}));
396 function sanitize(html) {
397 if (editor.settings.media_filter_html === false) {
401 var writer = new tinymce.html.Writer(), blocked;
403 new tinymce.html.SaxParser({
405 allow_conditional_comments: false,
406 special: 'script,noscript',
408 comment: function(text) {
409 writer.comment(text);
412 cdata: function(text) {
416 text: function(text, raw) {
417 writer.text(text, raw);
420 start: function(name, attrs, empty) {
423 if (name == 'script' || name == 'noscript') {
427 for (var i = 0; i < attrs.length; i++) {
428 if (attrs[i].name.indexOf('on') === 0) {
432 if (attrs[i].name == 'style') {
433 attrs[i].value = editor.dom.serializeStyle(editor.dom.parseStyle(attrs[i].value), name);
437 writer.start(name, attrs, empty);
441 end: function(name) {
448 }, new tinymce.html.Schema({})).parse(html);
450 return writer.getContent();
453 function updateHtml(html, data, updateAll) {
454 var writer = new tinymce.html.Writer();
455 var sourceCount = 0, hasImage;
457 function setAttributes(attrs, updatedAttrs) {
458 var name, i, value, attr;
460 for (name in updatedAttrs) {
461 value = "" + updatedAttrs[name];
463 if (attrs.map[name]) {
468 if (attr.name == name) {
470 attrs.map[name] = value;
473 delete attrs.map[name];
484 attrs.map[name] = value;
489 new tinymce.html.SaxParser({
491 allow_conditional_comments: true,
492 special: 'script,noscript',
494 comment: function(text) {
495 writer.comment(text);
498 cdata: function(text) {
502 text: function(text, raw) {
503 writer.text(text, raw);
506 start: function(name, attrs, empty) {
513 setAttributes(attrs, {
523 setAttributes(attrs, {
529 setAttributes(attrs, {
536 setAttributes(attrs, {
544 if (sourceCount <= 2) {
545 setAttributes(attrs, {
546 src: data["source" + sourceCount],
547 type: data["source" + sourceCount + "mime"]
550 if (!data["source" + sourceCount]) {
566 writer.start(name, attrs, empty);
569 end: function(name) {
570 if (name == "video" && updateAll) {
571 for (var index = 1; index <= 2; index++) {
572 if (data["source" + index]) {
576 if (sourceCount < index) {
577 setAttributes(attrs, {
578 src: data["source" + index],
579 type: data["source" + index + "mime"]
582 writer.start("source", attrs, true);
588 if (data.poster && name == "object" && updateAll && !hasImage) {
592 setAttributes(imgAttrs, {
598 writer.start("img", imgAttrs, true);
603 }, new tinymce.html.Schema({})).parse(html);
605 return writer.getContent();
608 editor.on('ResolveName', function(e) {
611 if (e.target.nodeType == 1 && (name = e.target.getAttribute("data-mce-object"))) {
616 function retainAttributesAndInnerHtml(sourceNode, targetNode) {
617 var attrName, attrValue, attribs, ai, innerHtml;
619 // Prefix all attributes except width, height and style since we
620 // will add these to the placeholder
621 attribs = sourceNode.attributes;
624 attrName = attribs[ai].name;
625 attrValue = attribs[ai].value;
627 if (attrName !== "width" && attrName !== "height" && attrName !== "style") {
628 if (attrName == "data" || attrName == "src") {
629 attrValue = editor.convertURL(attrValue, attrName);
632 targetNode.attr('data-mce-p-' + attrName, attrValue);
636 // Place the inner HTML contents inside an escaped attribute
637 // This enables us to copy/paste the fake object
638 innerHtml = sourceNode.firstChild && sourceNode.firstChild.value;
640 targetNode.attr("data-mce-html", escape(innerHtml));
641 targetNode.firstChild = null;
645 function createPlaceholderNode(node) {
646 var placeHolder, name = node.name;
648 placeHolder = new tinymce.html.Node('img', 1);
649 placeHolder.shortEnded = true;
651 retainAttributesAndInnerHtml(node, placeHolder);
654 width: node.attr('width') || "300",
655 height: node.attr('height') || (name == "audio" ? "30" : "150"),
656 style: node.attr('style'),
657 src: tinymce.Env.transparentSrc,
658 "data-mce-object": name,
659 "class": "mce-object mce-object-" + name
665 function createPreviewNode(node) {
666 var previewWrapper, previewNode, shimNode, name = node.name;
668 previewWrapper = new tinymce.html.Node('span', 1);
669 previewWrapper.attr({
670 contentEditable: 'false',
671 style: node.attr('style'),
672 "data-mce-object": name,
673 "class": "mce-preview-object mce-object-" + name
676 retainAttributesAndInnerHtml(node, previewWrapper);
678 previewNode = new tinymce.html.Node(name, 1);
680 src: node.attr('src'),
681 allowfullscreen: node.attr('allowfullscreen'),
682 width: node.attr('width') || "300",
683 height: node.attr('height') || (name == "audio" ? "30" : "150"),
687 shimNode = new tinymce.html.Node('span', 1);
688 shimNode.attr('class', 'mce-shim');
690 previewWrapper.append(previewNode);
691 previewWrapper.append(shimNode);
693 return previewWrapper;
696 editor.on('preInit', function() {
697 // Make sure that any messy HTML is retained inside these
698 var specialElements = editor.schema.getSpecialElements();
699 tinymce.each('video audio iframe object'.split(' '), function(name) {
700 specialElements[name] = new RegExp('<\/' + name + '[^>]*>', 'gi');
704 //editor.schema.addValidElements('object[id|style|width|height|classid|codebase|*],embed[id|style|width|height|type|src|*],video[*],audio[*]');
706 // Set allowFullscreen attribs as boolean
707 var boolAttrs = editor.schema.getBoolAttrs();
708 tinymce.each('webkitallowfullscreen mozallowfullscreen allowfullscreen'.split(' '), function(name) {
709 boolAttrs[name] = {};
712 // Converts iframe, video etc into placeholder images
713 editor.parser.addNodeFilter('iframe,video,audio,object,embed,script', function(nodes) {
714 var i = nodes.length, node, placeHolder, videoScript;
722 if (node.parent.attr('data-mce-object')) {
726 if (node.name == 'script') {
727 videoScript = getVideoScriptMatch(node.attr('src'));
734 if (videoScript.width) {
735 node.attr('width', videoScript.width.toString());
738 if (videoScript.height) {
739 node.attr('height', videoScript.height.toString());
743 if (node.name == 'iframe' && editor.settings.media_live_embeds !== false && tinymce.Env.ceFalse) {
744 placeHolder = createPreviewNode(node);
746 placeHolder = createPlaceholderNode(node);
749 node.replace(placeHolder);
753 // Replaces placeholder images with real elements for video, object, iframe etc
754 editor.serializer.addAttributeFilter('data-mce-object', function(nodes, name) {
755 var i = nodes.length, node, realElm, ai, attribs, innerHtml, innerNode, realElmName, className;
763 realElmName = node.attr(name);
764 realElm = new tinymce.html.Node(realElmName, 1);
766 // Add width/height to everything but audio
767 if (realElmName != "audio" && realElmName != "script") {
768 className = node.attr('class');
769 if (className && className.indexOf('mce-preview-object') !== -1) {
771 width: node.firstChild.attr('width'),
772 height: node.firstChild.attr('height')
776 width: node.attr('width'),
777 height: node.attr('height')
783 style: node.attr('style')
786 // Unprefix all placeholder attributes
787 attribs = node.attributes;
790 var attrName = attribs[ai].name;
792 if (attrName.indexOf('data-mce-p-') === 0) {
793 realElm.attr(attrName.substr(11), attribs[ai].value);
797 if (realElmName == "script") {
798 realElm.attr('type', 'text/javascript');
802 innerHtml = node.attr('data-mce-html');
804 innerNode = new tinymce.html.Node('#text', 3);
805 innerNode.raw = true;
806 innerNode.value = sanitize(unescape(innerHtml));
807 realElm.append(innerNode);
810 node.replace(realElm);
815 editor.on('click keyup', function() {
816 var selectedNode = editor.selection.getNode();
818 if (selectedNode && editor.dom.hasClass(selectedNode, 'mce-preview-object')) {
819 if (editor.dom.getAttrib(selectedNode, 'data-mce-selected')) {
820 selectedNode.setAttribute('data-mce-selected', '2');
825 editor.on('ObjectSelected', function(e) {
826 var objectType = e.target.getAttribute('data-mce-object');
828 if (objectType == "audio" || objectType == "script") {
833 editor.on('objectResized', function(e) {
834 var target = e.target, html;
836 if (target.getAttribute('data-mce-object')) {
837 html = target.getAttribute('data-mce-html');
839 html = unescape(html);
840 target.setAttribute('data-mce-html', escape(
850 editor.addButton('media', {
851 tooltip: 'Insert/edit video',
853 stateSelector: ['img[data-mce-object]', 'span[data-mce-object]']
856 editor.addMenuItem('media', {
858 text: 'Insert/edit video',
861 prependToContext: true
864 editor.on('setContent', function() {
865 // TODO: This shouldn't be needed there should be a way to mark bogus
866 // elements so they are never removed except external save
867 editor.$('span.mce-preview-object').each(function(index, elm) {
868 var $elm = editor.$(elm);
870 if ($elm.find('span.mce-shim', elm).length === 0) {
871 $elm.append('<span class="mce-shim"></span>');
876 editor.addCommand('mceMedia', showDialog);
878 this.showDialog = showDialog;