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}
25 var embedChange = (tinymce.Env.ie && tinymce.Env.ie <= 8) ? 'onChange' : 'onInput';
27 function guessMime(url) {
28 url = url.toLowerCase();
30 if (url.indexOf('.mp3') != -1) {
34 if (url.indexOf('.wav') != -1) {
38 if (url.indexOf('.mp4') != -1) {
42 if (url.indexOf('.webm') != -1) {
46 if (url.indexOf('.ogg') != -1) {
50 if (url.indexOf('.swf') != -1) {
51 return 'application/x-shockwave-flash';
57 function getVideoScriptMatch(src) {
58 var prefixes = editor.settings.media_scripts;
61 for (var i = 0; i < prefixes.length; i++) {
62 if (src.indexOf(prefixes[i].filter) !== -1) {
69 function showDialog() {
70 var win, width, height, data;
72 var generalFormItems = [
80 onchange: function(e) {
81 tinymce.each(e.meta, function(value, key) {
82 win.find('#' + key).value(value);
88 function recalcSize(e) {
89 var widthCtrl, heightCtrl, newWidth, newHeight;
91 widthCtrl = win.find('#width')[0];
92 heightCtrl = win.find('#height')[0];
94 newWidth = widthCtrl.value();
95 newHeight = heightCtrl.value();
97 if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) {
98 if (e.control == widthCtrl) {
99 newHeight = Math.round((newWidth / width) * newHeight);
101 if (!isNaN(newHeight)) {
102 heightCtrl.value(newHeight);
105 newWidth = Math.round((newHeight / height) * newWidth);
107 if (!isNaN(newWidth)) {
108 widthCtrl.value(newWidth);
117 if (editor.settings.media_alt_source !== false) {
118 generalFormItems.push({name: 'source2', type: 'filepicker', filetype: 'media', size: 40, label: 'Alternative source'});
121 if (editor.settings.media_poster !== false) {
122 generalFormItems.push({name: 'poster', type: 'filepicker', filetype: 'image', size: 40, label: 'Poster'});
125 if (editor.settings.media_dimensions !== false) {
126 generalFormItems.push({
133 {name: 'width', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Width'},
134 {type: 'label', text: 'x'},
135 {name: 'height', type: 'textbox', maxLength: 5, size: 3, onchange: recalcSize, ariaLabel: 'Height'},
136 {name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions'}
141 data = getData(editor.selection.getNode());
143 height = data.height;
146 id: 'mcemediasource',
155 function updateValueOnChange() {
156 data = htmlToData(this.value());
157 this.parent().parent().fromJSON(data);
160 embedTextBox[embedChange] = updateValueOnChange;
162 win = editor.windowManager.open({
163 title: 'Insert/edit video',
165 bodyType: 'tabpanel',
170 onShowTab: function() {
171 data = htmlToData(this.next().find('#embed').value());
174 items: generalFormItems
185 onShowTab: function() {
186 this.find('#embed').value(dataToHtml(this.parent().toJSON()));
191 text: 'Paste your embed code below:',
192 forId: 'mcemediasource'
198 onSubmit: function() {
199 var beforeObjects, afterObjects, i, y;
201 beforeObjects = editor.dom.select('img[data-mce-object]');
202 editor.insertContent(dataToHtml(this.toJSON()));
203 afterObjects = editor.dom.select('img[data-mce-object]');
205 // Find new image placeholder so we can select it
206 for (i = 0; i < beforeObjects.length; i++) {
207 for (y = afterObjects.length - 1; y >= 0; y--) {
208 if (beforeObjects[i] == afterObjects[y]) {
209 afterObjects.splice(y, 1);
214 editor.selection.select(afterObjects[0]);
215 editor.nodeChanged();
220 function getSource() {
221 var elm = editor.selection.getNode();
223 if (elm.getAttribute('data-mce-object')) {
224 return editor.selection.getContent();
228 function dataToHtml(data) {
232 tinymce.extend(data, htmlToData(data.embed));
246 data.source1 = editor.convertURL(data.source1, "source");
247 data.source2 = editor.convertURL(data.source2, "source");
248 data.source1mime = guessMime(data.source1);
249 data.source2mime = guessMime(data.source2);
250 data.poster = editor.convertURL(data.poster, "poster");
251 data.flashPlayerUrl = editor.convertURL(url + '/moxieplayer.swf', "movie");
253 tinymce.each(urlPatterns, function(pattern) {
256 if ((match = pattern.regex.exec(data.source1))) {
259 for (i = 0; match[i]; i++) {
260 /*jshint loopfunc:true*/
261 /*eslint no-loop-func:0 */
262 url = url.replace('$' + i, function() {
268 data.type = pattern.type;
269 data.allowFullscreen = pattern.allowFullscreen;
270 data.width = data.width || pattern.w;
271 data.height = data.height || pattern.h;
276 html = updateHtml(data.embed, data, true);
278 var videoScript = getVideoScriptMatch(data.source1);
280 data.type = 'script';
281 data.width = videoScript.width;
282 data.height = videoScript.height;
285 data.width = data.width || 300;
286 data.height = data.height || 150;
288 tinymce.each(data, function(value, key) {
289 data[key] = editor.dom.encode(value);
292 if (data.type == "iframe") {
293 var allowFullscreen = data.allowFullscreen ? ' allowFullscreen="1"' : '';
294 html += '<iframe src="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '"' + allowFullscreen + '></iframe>';
295 } else if (data.source1mime == "application/x-shockwave-flash") {
296 html += '<object data="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '" type="application/x-shockwave-flash">';
299 html += '<img src="' + data.poster + '" width="' + data.width + '" height="' + data.height + '" />';
303 } else if (data.source1mime.indexOf('audio') != -1) {
304 if (editor.settings.audio_template_callback) {
305 html = editor.settings.audio_template_callback(data);
308 '<audio controls="controls" src="' + data.source1 + '">' +
309 (data.source2 ? '\n<source src="' + data.source2 + '"' + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') +
313 } else if (data.type == "script") {
314 html += '<script src="' + data.source1 + '"></script>';
316 if (editor.settings.video_template_callback) {
317 html = editor.settings.video_template_callback(data);
320 '<video width="' + data.width + '" height="' + data.height + '"' + (data.poster ? ' poster="' + data.poster + '"' : '') + ' controls="controls">\n' +
321 '<source src="' + data.source1 + '"' + (data.source1mime ? ' type="' + data.source1mime + '"' : '') + ' />\n' +
322 (data.source2 ? '<source src="' + data.source2 + '"' + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') +
332 function htmlToData(html) {
335 new tinymce.html.SaxParser({
337 allow_conditional_comments: true,
338 special: 'script,noscript',
339 start: function(name, attrs) {
340 if (!data.source1 && name == "param") {
341 data.source1 = attrs.map.movie;
344 if (name == "iframe" || name == "object" || name == "embed" || name == "video" || name == "audio") {
349 data = tinymce.extend(attrs.map, data);
352 if (name == "script") {
353 var videoScript = getVideoScriptMatch(attrs.map.src);
360 source1: attrs.map.src,
361 width: videoScript.width,
362 height: videoScript.height
366 if (name == "source") {
368 data.source1 = attrs.map.src;
369 } else if (!data.source2) {
370 data.source2 = attrs.map.src;
374 if (name == "img" && !data.poster) {
375 data.poster = attrs.map.src;
380 data.source1 = data.source1 || data.src || data.data;
381 data.source2 = data.source2 || '';
382 data.poster = data.poster || '';
387 function getData(element) {
388 if (element.getAttribute('data-mce-object')) {
389 return htmlToData(editor.serializer.serialize(element, {selection: true}));
395 function sanitize(html) {
396 if (editor.settings.media_filter_html === false) {
400 var writer = new tinymce.html.Writer(), blocked;
402 new tinymce.html.SaxParser({
404 allow_conditional_comments: false,
405 special: 'script,noscript',
407 comment: function(text) {
408 writer.comment(text);
411 cdata: function(text) {
415 text: function(text, raw) {
416 writer.text(text, raw);
419 start: function(name, attrs, empty) {
422 if (name == 'script' || name == 'noscript') {
426 for (var i = 0; i < attrs.length; i++) {
427 if (attrs[i].name.indexOf('on') === 0) {
431 if (attrs[i].name == 'style') {
432 attrs[i].value = editor.dom.serializeStyle(editor.dom.parseStyle(attrs[i].value), name);
436 writer.start(name, attrs, empty);
440 end: function(name) {
447 }, new tinymce.html.Schema({})).parse(html);
449 return writer.getContent();
452 function updateHtml(html, data, updateAll) {
453 var writer = new tinymce.html.Writer();
454 var sourceCount = 0, hasImage;
456 function setAttributes(attrs, updatedAttrs) {
457 var name, i, value, attr;
459 for (name in updatedAttrs) {
460 value = "" + updatedAttrs[name];
462 if (attrs.map[name]) {
467 if (attr.name == name) {
469 attrs.map[name] = value;
472 delete attrs.map[name];
483 attrs.map[name] = value;
488 new tinymce.html.SaxParser({
490 allow_conditional_comments: true,
491 special: 'script,noscript',
493 comment: function(text) {
494 writer.comment(text);
497 cdata: function(text) {
501 text: function(text, raw) {
502 writer.text(text, raw);
505 start: function(name, attrs, empty) {
512 setAttributes(attrs, {
522 setAttributes(attrs, {
528 setAttributes(attrs, {
535 setAttributes(attrs, {
543 if (sourceCount <= 2) {
544 setAttributes(attrs, {
545 src: data["source" + sourceCount],
546 type: data["source" + sourceCount + "mime"]
549 if (!data["source" + sourceCount]) {
565 writer.start(name, attrs, empty);
568 end: function(name) {
569 if (name == "video" && updateAll) {
570 for (var index = 1; index <= 2; index++) {
571 if (data["source" + index]) {
575 if (sourceCount < index) {
576 setAttributes(attrs, {
577 src: data["source" + index],
578 type: data["source" + index + "mime"]
581 writer.start("source", attrs, true);
587 if (data.poster && name == "object" && updateAll && !hasImage) {
591 setAttributes(imgAttrs, {
597 writer.start("img", imgAttrs, true);
602 }, new tinymce.html.Schema({})).parse(html);
604 return writer.getContent();
607 editor.on('ResolveName', function(e) {
610 if (e.target.nodeType == 1 && (name = e.target.getAttribute("data-mce-object"))) {
615 function retainAttributesAndInnerHtml(sourceNode, targetNode) {
616 var attrName, attrValue, attribs, ai, innerHtml;
618 // Prefix all attributes except width, height and style since we
619 // will add these to the placeholder
620 attribs = sourceNode.attributes;
623 attrName = attribs[ai].name;
624 attrValue = attribs[ai].value;
626 if (attrName !== "width" && attrName !== "height" && attrName !== "style") {
627 if (attrName == "data" || attrName == "src") {
628 attrValue = editor.convertURL(attrValue, attrName);
631 targetNode.attr('data-mce-p-' + attrName, attrValue);
635 // Place the inner HTML contents inside an escaped attribute
636 // This enables us to copy/paste the fake object
637 innerHtml = sourceNode.firstChild && sourceNode.firstChild.value;
639 targetNode.attr("data-mce-html", escape(innerHtml));
640 targetNode.firstChild = null;
644 function createPlaceholderNode(node) {
645 var placeHolder, name = node.name;
647 placeHolder = new tinymce.html.Node('img', 1);
648 placeHolder.shortEnded = true;
650 retainAttributesAndInnerHtml(node, placeHolder);
653 width: node.attr('width') || "300",
654 height: node.attr('height') || (name == "audio" ? "30" : "150"),
655 style: node.attr('style'),
656 src: tinymce.Env.transparentSrc,
657 "data-mce-object": name,
658 "class": "mce-object mce-object-" + name
664 function createPreviewNode(node) {
665 var previewWrapper, previewNode, shimNode, name = node.name;
667 previewWrapper = new tinymce.html.Node('span', 1);
668 previewWrapper.attr({
669 contentEditable: 'false',
670 style: node.attr('style'),
671 "data-mce-object": name,
672 "class": "mce-preview-object mce-object-" + name
675 retainAttributesAndInnerHtml(node, previewWrapper);
677 previewNode = new tinymce.html.Node(name, 1);
679 src: node.attr('src'),
680 allowfullscreen: node.attr('allowfullscreen'),
681 width: node.attr('width') || "300",
682 height: node.attr('height') || (name == "audio" ? "30" : "150"),
686 shimNode = new tinymce.html.Node('span', 1);
687 shimNode.attr('class', 'mce-shim');
689 previewWrapper.append(previewNode);
690 previewWrapper.append(shimNode);
692 return previewWrapper;
695 editor.on('preInit', function() {
696 // Make sure that any messy HTML is retained inside these
697 var specialElements = editor.schema.getSpecialElements();
698 tinymce.each('video audio iframe object'.split(' '), function(name) {
699 specialElements[name] = new RegExp('<\/' + name + '[^>]*>', 'gi');
703 //editor.schema.addValidElements('object[id|style|width|height|classid|codebase|*],embed[id|style|width|height|type|src|*],video[*],audio[*]');
705 // Set allowFullscreen attribs as boolean
706 var boolAttrs = editor.schema.getBoolAttrs();
707 tinymce.each('webkitallowfullscreen mozallowfullscreen allowfullscreen'.split(' '), function(name) {
708 boolAttrs[name] = {};
711 // Converts iframe, video etc into placeholder images
712 editor.parser.addNodeFilter('iframe,video,audio,object,embed,script', function(nodes) {
713 var i = nodes.length, node, placeHolder, videoScript;
721 if (node.parent.attr('data-mce-object')) {
725 if (node.name == 'script') {
726 videoScript = getVideoScriptMatch(node.attr('src'));
733 if (videoScript.width) {
734 node.attr('width', videoScript.width.toString());
737 if (videoScript.height) {
738 node.attr('height', videoScript.height.toString());
742 if (node.name == 'iframe' && editor.settings.media_live_embeds !== false && tinymce.Env.ceFalse) {
743 placeHolder = createPreviewNode(node);
745 placeHolder = createPlaceholderNode(node);
748 node.replace(placeHolder);
752 // Replaces placeholder images with real elements for video, object, iframe etc
753 editor.serializer.addAttributeFilter('data-mce-object', function(nodes, name) {
754 var i = nodes.length, node, realElm, ai, attribs, innerHtml, innerNode, realElmName, className;
762 realElmName = node.attr(name);
763 realElm = new tinymce.html.Node(realElmName, 1);
765 // Add width/height to everything but audio
766 if (realElmName != "audio" && realElmName != "script") {
767 className = node.attr('class');
768 if (className && className.indexOf('mce-preview-object') !== -1) {
770 width: node.firstChild.attr('width'),
771 height: node.firstChild.attr('height')
775 width: node.attr('width'),
776 height: node.attr('height')
782 style: node.attr('style')
785 // Unprefix all placeholder attributes
786 attribs = node.attributes;
789 var attrName = attribs[ai].name;
791 if (attrName.indexOf('data-mce-p-') === 0) {
792 realElm.attr(attrName.substr(11), attribs[ai].value);
796 if (realElmName == "script") {
797 realElm.attr('type', 'text/javascript');
801 innerHtml = node.attr('data-mce-html');
803 innerNode = new tinymce.html.Node('#text', 3);
804 innerNode.raw = true;
805 innerNode.value = sanitize(unescape(innerHtml));
806 realElm.append(innerNode);
809 node.replace(realElm);
814 editor.on('click keyup', function() {
815 var selectedNode = editor.selection.getNode();
817 if (selectedNode && editor.dom.hasClass(selectedNode, 'mce-preview-object')) {
818 if (editor.dom.getAttrib(selectedNode, 'data-mce-selected')) {
819 selectedNode.setAttribute('data-mce-selected', '2');
824 editor.on('ObjectSelected', function(e) {
825 var objectType = e.target.getAttribute('data-mce-object');
827 if (objectType == "audio" || objectType == "script") {
832 editor.on('objectResized', function(e) {
833 var target = e.target, html;
835 if (target.getAttribute('data-mce-object')) {
836 html = target.getAttribute('data-mce-html');
838 html = unescape(html);
839 target.setAttribute('data-mce-html', escape(
849 editor.addButton('media', {
850 tooltip: 'Insert/edit video',
852 stateSelector: ['img[data-mce-object]', 'span[data-mce-object]']
855 editor.addMenuItem('media', {
857 text: 'Insert/edit video',
860 prependToContext: true
863 editor.on('setContent', function() {
864 // TODO: This shouldn't be needed there should be a way to mark bogus
865 // elements so they are never removed except external save
866 editor.$('span.mce-preview-object').each(function(index, elm) {
867 var $elm = editor.$(elm);
869 if ($elm.find('span.mce-shim', elm).length === 0) {
870 $elm.append('<span class="mce-shim"></span>');
875 editor.addCommand('mceMedia', showDialog);
877 this.showDialog = showDialog;