]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/tinymce/plugins/media/plugin.js
WordPress 4.1-scripts
[autoinstalls/wordpress.git] / wp-includes / js / tinymce / plugins / media / plugin.js
1 /**
2  * plugin.js
3  *
4  * Copyright, Moxiecode Systems AB
5  * Released under LGPL License.
6  *
7  * License: http://www.tinymce.com/license
8  * Contributing: http://www.tinymce.com/contributing
9  */
10
11 /*jshint maxlen:255 */
12 /*eslint max-len:0 */
13 /*global tinymce:true */
14
15 tinymce.PluginManager.add('media', function(editor, url) {
16         var urlPatterns = [
17                 {regex: /youtu\.be\/([\w\-.]+)/, type: 'iframe', w: 425, h: 350, url: '//www.youtube.com/embed/$1'},
18                 {regex: /youtube\.com(.+)v=([^&]+)/, type: 'iframe', w: 425, h: 350, url: '//www.youtube.com/embed/$2'},
19                 {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'},
20                 {regex: /vimeo\.com\/(.*)\/([0-9]+)/, type: "iframe", w: 425, h: 350, url: "//player.vimeo.com/video/$2?title=0&byline=0"},
21                 {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"'}
22         ];
23
24         var embedChange = (tinymce.Env.ie && tinymce.Env.ie <= 8) ? 'onChange' : 'onInput';
25
26         function guessMime(url) {
27                 if (url.indexOf('.mp3') != -1) {
28                         return 'audio/mpeg';
29                 }
30
31                 if (url.indexOf('.wav') != -1) {
32                         return 'audio/wav';
33                 }
34
35                 if (url.indexOf('.mp4') != -1) {
36                         return 'video/mp4';
37                 }
38
39                 if (url.indexOf('.webm') != -1) {
40                         return 'video/webm';
41                 }
42
43                 if (url.indexOf('.ogg') != -1) {
44                         return 'video/ogg';
45                 }
46
47                 if (url.indexOf('.swf') != -1) {
48                         return 'application/x-shockwave-flash';
49                 }
50
51                 return '';
52         }
53
54         function getVideoScriptMatch(src) {
55                 var prefixes = editor.settings.media_scripts;
56
57                 if (prefixes) {
58                         for (var i = 0; i < prefixes.length; i++) {
59                                 if (src.indexOf(prefixes[i].filter) !== -1) {
60                                         return prefixes[i];
61                                 }
62                         }
63                 }
64         }
65
66         function showDialog() {
67                 var win, width, height, data;
68
69                 var generalFormItems = [
70                         {
71                                 name: 'source1',
72                                 type: 'filepicker',
73                                 filetype: 'media',
74                                 size: 40,
75                                 autofocus: true,
76                                 label: 'Source',
77                                 onchange: function(e) {
78                                         tinymce.each(e.meta, function(value, key) {
79                                                 win.find('#' + key).value(value);
80                                         });
81                                 }
82                         }
83                 ];
84
85                 function recalcSize(e) {
86                         var widthCtrl, heightCtrl, newWidth, newHeight;
87
88                         widthCtrl = win.find('#width')[0];
89                         heightCtrl = win.find('#height')[0];
90
91                         newWidth = widthCtrl.value();
92                         newHeight = heightCtrl.value();
93
94                         if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) {
95                                 if (e.control == widthCtrl) {
96                                         newHeight = Math.round((newWidth / width) * newHeight);
97                                         heightCtrl.value(newHeight);
98                                 } else {
99                                         newWidth = Math.round((newHeight / height) * newWidth);
100                                         widthCtrl.value(newWidth);
101                                 }
102                         }
103
104                         width = newWidth;
105                         height = newHeight;
106                 }
107
108                 if (editor.settings.media_alt_source !== false) {
109                         generalFormItems.push({name: 'source2', type: 'filepicker', filetype: 'media', size: 40, label: 'Alternative source'});
110                 }
111
112                 if (editor.settings.media_poster !== false) {
113                         generalFormItems.push({name: 'poster', type: 'filepicker', filetype: 'image', size: 40, label: 'Poster'});
114                 }
115
116                 if (editor.settings.media_dimensions !== false) {
117                         generalFormItems.push({
118                                 type: 'container',
119                                 label: 'Dimensions',
120                                 layout: 'flex',
121                                 align: 'center',
122                                 spacing: 5,
123                                 items: [
124                                         {name: 'width', type: 'textbox', maxLength: 3, size: 3, onchange: recalcSize},
125                                         {type: 'label', text: 'x'},
126                                         {name: 'height', type: 'textbox', maxLength: 3, size: 3, onchange: recalcSize},
127                                         {name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions'}
128                                 ]
129                         });
130                 }
131
132                 data = getData(editor.selection.getNode());
133                 width = data.width;
134                 height = data.height;
135
136                 var embedTextBox = {
137                         id: 'mcemediasource',
138                         type: 'textbox',
139                         flex: 1,
140                         name: 'embed',
141                         value: getSource(),
142                         multiline: true,
143                         label: 'Source'
144                 };
145
146                 function updateValueOnChange() {
147                         data = htmlToData(this.value());
148                         this.parent().parent().fromJSON(data);
149                 }
150
151                 embedTextBox[embedChange] = updateValueOnChange;
152
153                 win = editor.windowManager.open({
154                         title: 'Insert/edit video',
155                         data: data,
156                         bodyType: 'tabpanel',
157                         body: [
158                                 {
159                                         title: 'General',
160                                         type: "form",
161                                         onShowTab: function() {
162                                                 data = htmlToData(this.next().find('#embed').value());
163                                                 this.fromJSON(data);
164                                         },
165                                         items: generalFormItems
166                                 },
167
168                                 {
169                                         title: 'Embed',
170                                         type: "panel",
171                                         layout: 'flex',
172                                         direction: 'column',
173                                         align: 'stretch',
174                                         padding: 10,
175                                         spacing: 10,
176                                         onShowTab: function() {
177                                                 this.find('#embed').value(dataToHtml(this.parent().toJSON()));
178                                         },
179                                         items: [
180                                                 {
181                                                         type: 'label',
182                                                         text: 'Paste your embed code below:',
183                                                         forId: 'mcemediasource'
184                                                 },
185                                                 embedTextBox
186                                         ]
187                                 }
188                         ],
189                         onSubmit: function() {
190                                 var beforeObjects, afterObjects, i, y;
191
192                                 beforeObjects = editor.dom.select('img[data-mce-object]');
193                                 editor.insertContent(dataToHtml(this.toJSON()));
194                                 afterObjects = editor.dom.select('img[data-mce-object]');
195
196                                 // Find new image placeholder so we can select it
197                                 for (i = 0; i < beforeObjects.length; i++) {
198                                         for (y = afterObjects.length - 1; y >= 0; y--) {
199                                                 if (beforeObjects[i] == afterObjects[y]) {
200                                                         afterObjects.splice(y, 1);
201                                                 }
202                                         }
203                                 }
204
205                                 editor.selection.select(afterObjects[0]);
206                                 editor.nodeChanged();
207                         }
208                 });
209         }
210
211         function getSource() {
212                 var elm = editor.selection.getNode();
213
214                 if (elm.getAttribute('data-mce-object')) {
215                         return editor.selection.getContent();
216                 }
217         }
218
219         function dataToHtml(data) {
220                 var html = '';
221
222                 if (!data.source1) {
223                         tinymce.extend(data, htmlToData(data.embed));
224                         if (!data.source1) {
225                                 return '';
226                         }
227                 }
228
229                 if (!data.source2) {
230                         data.source2 = '';
231                 }
232
233                 if (!data.poster) {
234                         data.poster = '';
235                 }
236
237                 data.source1 = editor.convertURL(data.source1, "source");
238                 data.source2 = editor.convertURL(data.source2, "source");
239                 data.source1mime = guessMime(data.source1);
240                 data.source2mime = guessMime(data.source2);
241                 data.poster = editor.convertURL(data.poster, "poster");
242                 data.flashPlayerUrl = editor.convertURL(url + '/moxieplayer.swf', "movie");
243
244                 tinymce.each(urlPatterns, function(pattern) {
245                         var match, i, url;
246
247                         if ((match = pattern.regex.exec(data.source1))) {
248                                 url = pattern.url;
249
250                                 for (i = 0; match[i]; i++) {
251                                         /*jshint loopfunc:true*/
252                                         /*eslint no-loop-func:0 */
253                                         url = url.replace('$' + i, function() {
254                                                 return match[i];
255                                         });
256                                 }
257
258                                 data.source1 = url;
259                                 data.type = pattern.type;
260                                 data.width = data.width || pattern.w;
261                                 data.height = data.height || pattern.h;
262                         }
263                 });
264
265                 if (data.embed) {
266                         html = updateHtml(data.embed, data, true);
267                 } else {
268                         var videoScript = getVideoScriptMatch(data.source1);
269                         if (videoScript) {
270                                 data.type = 'script';
271                                 data.width = videoScript.width;
272                                 data.height = videoScript.height;
273                         }
274
275                         data.width = data.width || 300;
276                         data.height = data.height || 150;
277
278                         tinymce.each(data, function(value, key) {
279                                 data[key] = editor.dom.encode(value);
280                         });
281
282                         if (data.type == "iframe") {
283                                 html += '<iframe src="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '"></iframe>';
284                         } else if (data.source1mime == "application/x-shockwave-flash") {
285                                 html += '<object data="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '" type="application/x-shockwave-flash">';
286
287                                 if (data.poster) {
288                                         html += '<img src="' + data.poster + '" width="' + data.width + '" height="' + data.height + '" />';
289                                 }
290
291                                 html += '</object>';
292                         } else if (data.source1mime.indexOf('audio') != -1) {
293                                 if (editor.settings.audio_template_callback) {
294                                         html = editor.settings.audio_template_callback(data);
295                                 } else {
296                                         html += (
297                                                 '<audio controls="controls" src="' + data.source1 + '">' +
298                                                         (data.source2 ? '\n<source src="' + data.source2 + '"' + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') +
299                                                 '</audio>'
300                                         );
301                                 }
302                         } else if (data.type == "script") {
303                                 html += '<script src="' + data.source1 + '"></script>';
304                         } else {
305                                 if (editor.settings.video_template_callback) {
306                                         html = editor.settings.video_template_callback(data);
307                                 } else {
308                                         html = (
309                                                 '<video width="' + data.width + '" height="' + data.height + '"' + (data.poster ? ' poster="' + data.poster + '"' : '') + ' controls="controls">\n' +
310                                                         '<source src="' + data.source1 + '"' + (data.source1mime ? ' type="' + data.source1mime + '"' : '') + ' />\n' +
311                                                         (data.source2 ? '<source src="' + data.source2 + '"' + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') +
312                                                 '</video>'
313                                         );
314                                 }
315                         }
316                 }
317
318                 return html;
319         }
320
321         function htmlToData(html) {
322                 var data = {};
323
324                 new tinymce.html.SaxParser({
325                         validate: false,
326                         allow_conditional_comments: true,
327                         special: 'script,noscript',
328                         start: function(name, attrs) {
329                                 if (!data.source1 && name == "param") {
330                                         data.source1 = attrs.map.movie;
331                                 }
332
333                                 if (name == "iframe" || name == "object" || name == "embed" || name == "video" || name == "audio") {
334                                         if (!data.type) {
335                                                 data.type = name;
336                                         }
337
338                                         data = tinymce.extend(attrs.map, data);
339                                 }
340
341                                 if (name == "script") {
342                                         var videoScript = getVideoScriptMatch(attrs.map.src);
343                                         if (!videoScript) {
344                                                 return;
345                                         }
346
347                                         data = {
348                                                 type: "script",
349                                                 source1: attrs.map.src,
350                                                 width: videoScript.width,
351                                                 height: videoScript.height
352                                         };
353                                 }
354
355                                 if (name == "source") {
356                                         if (!data.source1) {
357                                                 data.source1 = attrs.map.src;
358                                         } else if (!data.source2) {
359                                                 data.source2 = attrs.map.src;
360                                         }
361                                 }
362
363                                 if (name == "img" && !data.poster) {
364                                         data.poster = attrs.map.src;
365                                 }
366                         }
367                 }).parse(html);
368
369                 data.source1 = data.source1 || data.src || data.data;
370                 data.source2 = data.source2 || '';
371                 data.poster = data.poster || '';
372
373                 return data;
374         }
375
376         function getData(element) {
377                 if (element.getAttribute('data-mce-object')) {
378                         return htmlToData(editor.serializer.serialize(element, {selection: true}));
379                 }
380
381                 return {};
382         }
383
384         function sanitize(html) {
385                 if (editor.settings.media_filter_html === false) {
386                         return html;
387                 }
388
389                 var writer = new tinymce.html.Writer();
390
391                 new tinymce.html.SaxParser({
392                         validate: false,
393                         allow_conditional_comments: false,
394                         special: 'script,noscript',
395
396                         comment: function(text) {
397                                 writer.comment(text);
398                         },
399
400                         cdata: function(text) {
401                                 writer.cdata(text);
402                         },
403
404                         text: function(text, raw) {
405                                 writer.text(text, raw);
406                         },
407
408                         start: function(name, attrs, empty) {
409                                 if (name == 'script' || name == 'noscript') {
410                                         return;
411                                 }
412
413                                 for (var i = 0; i < attrs.length; i++) {
414                                         if (attrs[i].name.indexOf('on') === 0) {
415                                                 return;
416                                         }
417                                 }
418
419                                 writer.start(name, attrs, empty);
420                         },
421
422                         end: function(name) {
423                                 if (name == 'script' || name == 'noscript') {
424                                         return;
425                                 }
426
427                                 writer.end(name);
428                         }
429                 }, new tinymce.html.Schema({})).parse(html);
430
431                 return writer.getContent();
432         }
433
434         function updateHtml(html, data, updateAll) {
435                 var writer = new tinymce.html.Writer();
436                 var sourceCount = 0, hasImage;
437
438                 function setAttributes(attrs, updatedAttrs) {
439                         var name, i, value, attr;
440
441                         for (name in updatedAttrs) {
442                                 value = "" + updatedAttrs[name];
443
444                                 if (attrs.map[name]) {
445                                         i = attrs.length;
446                                         while (i--) {
447                                                 attr = attrs[i];
448
449                                                 if (attr.name == name) {
450                                                         if (value) {
451                                                                 attrs.map[name] = value;
452                                                                 attr.value = value;
453                                                         } else {
454                                                                 delete attrs.map[name];
455                                                                 attrs.splice(i, 1);
456                                                         }
457                                                 }
458                                         }
459                                 } else if (value) {
460                                         attrs.push({
461                                                 name: name,
462                                                 value: value
463                                         });
464
465                                         attrs.map[name] = value;
466                                 }
467                         }
468                 }
469
470                 new tinymce.html.SaxParser({
471                         validate: false,
472                         allow_conditional_comments: true,
473                         special: 'script,noscript',
474
475                         comment: function(text) {
476                                 writer.comment(text);
477                         },
478
479                         cdata: function(text) {
480                                 writer.cdata(text);
481                         },
482
483                         text: function(text, raw) {
484                                 writer.text(text, raw);
485                         },
486
487                         start: function(name, attrs, empty) {
488                                 switch (name) {
489                                         case "video":
490                                         case "object":
491                                         case "embed":
492                                         case "img":
493                                         case "iframe":
494                                                 setAttributes(attrs, {
495                                                         width: data.width,
496                                                         height: data.height
497                                                 });
498                                                 break;
499                                 }
500
501                                 if (updateAll) {
502                                         switch (name) {
503                                                 case "video":
504                                                         setAttributes(attrs, {
505                                                                 poster: data.poster,
506                                                                 src: ""
507                                                         });
508
509                                                         if (data.source2) {
510                                                                 setAttributes(attrs, {
511                                                                         src: ""
512                                                                 });
513                                                         }
514                                                         break;
515
516                                                 case "iframe":
517                                                         setAttributes(attrs, {
518                                                                 src: data.source1
519                                                         });
520                                                         break;
521
522                                                 case "source":
523                                                         sourceCount++;
524
525                                                         if (sourceCount <= 2) {
526                                                                 setAttributes(attrs, {
527                                                                         src: data["source" + sourceCount],
528                                                                         type: data["source" + sourceCount + "mime"]
529                                                                 });
530
531                                                                 if (!data["source" + sourceCount]) {
532                                                                         return;
533                                                                 }
534                                                         }
535                                                         break;
536
537                                                 case "img":
538                                                         if (!data.poster) {
539                                                                 return;
540                                                         }
541
542                                                         hasImage = true;
543                                                         break;
544                                         }
545                                 }
546
547                                 writer.start(name, attrs, empty);
548                         },
549
550                         end: function(name) {
551                                 if (name == "video" && updateAll) {
552                                         for (var index = 1; index <= 2; index++) {
553                                                 if (data["source" + index]) {
554                                                         var attrs = [];
555                                                         attrs.map = {};
556
557                                                         if (sourceCount < index) {
558                                                                 setAttributes(attrs, {
559                                                                         src: data["source" + index],
560                                                                         type: data["source" + index + "mime"]
561                                                                 });
562
563                                                                 writer.start("source", attrs, true);
564                                                         }
565                                                 }
566                                         }
567                                 }
568
569                                 if (data.poster && name == "object" && updateAll && !hasImage) {
570                                         var imgAttrs = [];
571                                         imgAttrs.map = {};
572
573                                         setAttributes(imgAttrs, {
574                                                 src: data.poster,
575                                                 width: data.width,
576                                                 height: data.height
577                                         });
578
579                                         writer.start("img", imgAttrs, true);
580                                 }
581
582                                 writer.end(name);
583                         }
584                 }, new tinymce.html.Schema({})).parse(html);
585
586                 return writer.getContent();
587         }
588
589         editor.on('ResolveName', function(e) {
590                 var name;
591
592                 if (e.target.nodeType == 1 && (name = e.target.getAttribute("data-mce-object"))) {
593                         e.name = name;
594                 }
595         });
596
597         editor.on('preInit', function() {
598                 // Make sure that any messy HTML is retained inside these
599                 var specialElements = editor.schema.getSpecialElements();
600                 tinymce.each('video audio iframe object'.split(' '), function(name) {
601                         specialElements[name] = new RegExp('<\/' + name + '[^>]*>', 'gi');
602                 });
603
604                 // Allow elements
605                 //editor.schema.addValidElements('object[id|style|width|height|classid|codebase|*],embed[id|style|width|height|type|src|*],video[*],audio[*]');
606
607                 // Set allowFullscreen attribs as boolean
608                 var boolAttrs = editor.schema.getBoolAttrs();
609                 tinymce.each('webkitallowfullscreen mozallowfullscreen allowfullscreen'.split(' '), function(name) {
610                         boolAttrs[name] = {};
611                 });
612
613                 // Converts iframe, video etc into placeholder images
614                 editor.parser.addNodeFilter('iframe,video,audio,object,embed,script', function(nodes, name) {
615                         var i = nodes.length, ai, node, placeHolder, attrName, attrValue, attribs, innerHtml;
616                         var videoScript;
617
618                         while (i--) {
619                                 node = nodes[i];
620                                 if (!node.parent) {
621                                         continue;
622                                 }
623
624                                 if (node.name == 'script') {
625                                         videoScript = getVideoScriptMatch(node.attr('src'));
626                                         if (!videoScript) {
627                                                 continue;
628                                         }
629                                 }
630
631                                 placeHolder = new tinymce.html.Node('img', 1);
632                                 placeHolder.shortEnded = true;
633
634                                 if (videoScript) {
635                                         if (videoScript.width) {
636                                                 node.attr('width', videoScript.width.toString());
637                                         }
638
639                                         if (videoScript.height) {
640                                                 node.attr('height', videoScript.height.toString());
641                                         }
642                                 }
643
644                                 // Prefix all attributes except width, height and style since we
645                                 // will add these to the placeholder
646                                 attribs = node.attributes;
647                                 ai = attribs.length;
648                                 while (ai--) {
649                                         attrName = attribs[ai].name;
650                                         attrValue = attribs[ai].value;
651
652                                         if (attrName !== "width" && attrName !== "height" && attrName !== "style") {
653                                                 if (attrName == "data" || attrName == "src") {
654                                                         attrValue = editor.convertURL(attrValue, attrName);
655                                                 }
656
657                                                 placeHolder.attr('data-mce-p-' + attrName, attrValue);
658                                         }
659                                 }
660
661                                 // Place the inner HTML contents inside an escaped attribute
662                                 // This enables us to copy/paste the fake object
663                                 innerHtml = node.firstChild && node.firstChild.value;
664                                 if (innerHtml) {
665                                         placeHolder.attr("data-mce-html", escape(innerHtml));
666                                         placeHolder.firstChild = null;
667                                 }
668
669                                 placeHolder.attr({
670                                         width: node.attr('width') || "300",
671                                         height: node.attr('height') || (name == "audio" ? "30" : "150"),
672                                         style: node.attr('style'),
673                                         src: tinymce.Env.transparentSrc,
674                                         "data-mce-object": name,
675                                         "class": "mce-object mce-object-" + name
676                                 });
677
678                                 node.replace(placeHolder);
679                         }
680                 });
681
682                 // Replaces placeholder images with real elements for video, object, iframe etc
683                 editor.serializer.addAttributeFilter('data-mce-object', function(nodes, name) {
684                         var i = nodes.length, node, realElm, ai, attribs, innerHtml, innerNode, realElmName;
685
686                         while (i--) {
687                                 node = nodes[i];
688                                 if (!node.parent) {
689                                         continue;
690                                 }
691
692                                 realElmName = node.attr(name);
693                                 realElm = new tinymce.html.Node(realElmName, 1);
694
695                                 // Add width/height to everything but audio
696                                 if (realElmName != "audio" && realElmName != "script") {
697                                         realElm.attr({
698                                                 width: node.attr('width'),
699                                                 height: node.attr('height')
700                                         });
701                                 }
702
703                                 realElm.attr({
704                                         style: node.attr('style')
705                                 });
706
707                                 // Unprefix all placeholder attributes
708                                 attribs = node.attributes;
709                                 ai = attribs.length;
710                                 while (ai--) {
711                                         var attrName = attribs[ai].name;
712
713                                         if (attrName.indexOf('data-mce-p-') === 0) {
714                                                 realElm.attr(attrName.substr(11), attribs[ai].value);
715                                         }
716                                 }
717
718                                 if (realElmName == "script") {
719                                         realElm.attr('type', 'text/javascript');
720                                 }
721
722                                 // Inject innerhtml
723                                 innerHtml = node.attr('data-mce-html');
724                                 if (innerHtml) {
725                                         innerNode = new tinymce.html.Node('#text', 3);
726                                         innerNode.raw = true;
727                                         innerNode.value = sanitize(unescape(innerHtml));
728                                         realElm.append(innerNode);
729                                 }
730
731                                 node.replace(realElm);
732                         }
733                 });
734         });
735
736         editor.on('ObjectSelected', function(e) {
737                 var objectType = e.target.getAttribute('data-mce-object');
738
739                 if (objectType == "audio" || objectType == "script") {
740                         e.preventDefault();
741                 }
742         });
743
744         editor.on('objectResized', function(e) {
745                 var target = e.target, html;
746
747                 if (target.getAttribute('data-mce-object')) {
748                         html = target.getAttribute('data-mce-html');
749                         if (html) {
750                                 html = unescape(html);
751                                 target.setAttribute('data-mce-html', escape(
752                                         updateHtml(html, {
753                                                 width: e.width,
754                                                 height: e.height
755                                         })
756                                 ));
757                         }
758                 }
759         });
760
761         editor.addButton('media', {
762                 tooltip: 'Insert/edit video',
763                 onclick: showDialog,
764                 stateSelector: ['img[data-mce-object=video]', 'img[data-mce-object=iframe]']
765         });
766
767         editor.addMenuItem('media', {
768                 icon: 'media',
769                 text: 'Insert video',
770                 onclick: showDialog,
771                 context: 'insert',
772                 prependToContext: true
773         });
774 });