]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/media-editor.js
Wordpress 3.6
[autoinstalls/wordpress.git] / wp-includes / js / media-editor.js
1 // WordPress, TinyMCE, and Media
2 // -----------------------------
3 (function($){
4         // Stores the editors' `wp.media.controller.Frame` instances.
5         var workflows = {};
6
7         wp.media.string = {
8                 // Joins the `props` and `attachment` objects,
9                 // outputting the proper object format based on the
10                 // attachment's type.
11                 props: function( props, attachment ) {
12                         var link, linkUrl, size, sizes, fallbacks,
13                                 defaultProps = wp.media.view.settings.defaultProps;
14
15                         // Final fallbacks run after all processing has been completed.
16                         fallbacks = function( props ) {
17                                 // Generate alt fallbacks and strip tags.
18                                 if ( 'image' === props.type && ! props.alt ) {
19                                         props.alt = props.caption || props.title || '';
20                                         props.alt = props.alt.replace( /<\/?[^>]+>/g, '' );
21                                         props.alt = props.alt.replace( /[\r\n]+/g, ' ' );
22                                 }
23
24                                 return props;
25                         };
26
27                         props = props ? _.clone( props ) : {};
28
29                         if ( attachment && attachment.type )
30                                 props.type = attachment.type;
31
32                         if ( 'image' === props.type ) {
33                                 props = _.defaults( props || {}, {
34                                         align:   defaultProps.align || getUserSetting( 'align', 'none' ),
35                                         size:    defaultProps.size  || getUserSetting( 'imgsize', 'medium' ),
36                                         url:     '',
37                                         classes: []
38                                 });
39                         }
40
41                         // All attachment-specific settings follow.
42                         if ( ! attachment )
43                                 return fallbacks( props );
44
45                         props.title = props.title || attachment.title;
46
47                         link = props.link || defaultProps.link || getUserSetting( 'urlbutton', 'file' );
48                         if ( 'file' === link || 'embed' === link )
49                                 linkUrl = attachment.url;
50                         else if ( 'post' === link )
51                                 linkUrl = attachment.link;
52                         else if ( 'custom' === link )
53                                 linkUrl = props.linkUrl;
54                         props.linkUrl = linkUrl || '';
55
56                         // Format properties for images.
57                         if ( 'image' === attachment.type ) {
58                                 props.classes.push( 'wp-image-' + attachment.id );
59
60                                 sizes = attachment.sizes;
61                                 size = sizes && sizes[ props.size ] ? sizes[ props.size ] : attachment;
62
63                                 _.extend( props, _.pick( attachment, 'align', 'caption', 'alt' ), {
64                                         width:     size.width,
65                                         height:    size.height,
66                                         src:       size.url,
67                                         captionId: 'attachment_' + attachment.id
68                                 });
69                         } else if ( 'video' === attachment.type || 'audio' === attachment.type ) {
70                                 _.extend( props, _.pick( attachment, 'title', 'type', 'icon', 'mime' ) );
71                         // Format properties for non-images.
72                         } else {
73                                 props.title = props.title || attachment.filename;
74                                 props.rel = props.rel || 'attachment wp-att-' + attachment.id;
75                         }
76
77                         return fallbacks( props );
78                 },
79
80                 link: function( props, attachment ) {
81                         var options;
82
83                         props = wp.media.string.props( props, attachment );
84
85                         options = {
86                                 tag:     'a',
87                                 content: props.title,
88                                 attrs:   {
89                                         href: props.linkUrl
90                                 }
91                         };
92
93                         if ( props.rel )
94                                 options.attrs.rel = props.rel;
95
96                         return wp.html.string( options );
97                 },
98
99                 audio: function( props, attachment ) {
100                         return wp.media.string._audioVideo( 'audio', props, attachment );
101                 },
102
103                 video: function( props, attachment ) {
104                         return wp.media.string._audioVideo( 'video', props, attachment );
105                 },
106
107                 _audioVideo: function( type, props, attachment ) {
108                         var shortcode, html, extension;
109
110                         props = wp.media.string.props( props, attachment );
111                         if ( props.link !== 'embed' )
112                                 return wp.media.string.link( props );
113
114                         shortcode = {};
115
116                         if ( 'video' === type ) {
117                                 if ( attachment.width )
118                                         shortcode.width = attachment.width;
119
120                                 if ( attachment.height )
121                                         shortcode.height = attachment.height;
122                         }
123
124                         extension = attachment.filename.split('.').pop();
125
126                         if ( _.contains( wp.media.view.settings.embedExts, extension ) ) {
127                                 shortcode[extension] = attachment.url;
128                         } else {
129                                 // Render unsupported audio and video files as links.
130                                 return wp.media.string.link( props );
131                         }
132
133                         html = wp.shortcode.string({
134                                 tag:     type,
135                                 attrs:   shortcode
136                         });
137
138                         return html;
139                 },
140
141                 image: function( props, attachment ) {
142                         var img = {},
143                                 options, classes, shortcode, html;
144
145                         props = wp.media.string.props( props, attachment );
146                         classes = props.classes || [];
147
148                         img.src = typeof attachment !== 'undefined' ? attachment.url : props.url;
149                         _.extend( img, _.pick( props, 'width', 'height', 'alt' ) );
150
151                         // Only assign the align class to the image if we're not printing
152                         // a caption, since the alignment is sent to the shortcode.
153                         if ( props.align && ! props.caption )
154                                 classes.push( 'align' + props.align );
155
156                         if ( props.size )
157                                 classes.push( 'size-' + props.size );
158
159                         img['class'] = _.compact( classes ).join(' ');
160
161                         // Generate `img` tag options.
162                         options = {
163                                 tag:    'img',
164                                 attrs:  img,
165                                 single: true
166                         };
167
168                         // Generate the `a` element options, if they exist.
169                         if ( props.linkUrl ) {
170                                 options = {
171                                         tag:   'a',
172                                         attrs: {
173                                                 href: props.linkUrl
174                                         },
175                                         content: options
176                                 };
177                         }
178
179                         html = wp.html.string( options );
180
181                         // Generate the caption shortcode.
182                         if ( props.caption ) {
183                                 shortcode = {};
184
185                                 if ( img.width )
186                                         shortcode.width = img.width;
187
188                                 if ( props.captionId )
189                                         shortcode.id = props.captionId;
190
191                                 if ( props.align )
192                                         shortcode.align = 'align' + props.align;
193
194                                 html = wp.shortcode.string({
195                                         tag:     'caption',
196                                         attrs:   shortcode,
197                                         content: html + ' ' + props.caption
198                                 });
199                         }
200
201                         return html;
202                 }
203         };
204
205         wp.media.gallery = (function() {
206                 var galleries = {};
207
208                 return {
209                         defaults: {
210                                 order:      'ASC',
211                                 id:         wp.media.view.settings.post.id,
212                                 itemtag:    'dl',
213                                 icontag:    'dt',
214                                 captiontag: 'dd',
215                                 columns:    '3',
216                                 link:       'post',
217                                 size:       'thumbnail',
218                                 orderby:    'menu_order ID'
219                         },
220
221                         attachments: function( shortcode ) {
222                                 var shortcodeString = shortcode.string(),
223                                         result = galleries[ shortcodeString ],
224                                         attrs, args, query, others;
225
226                                 delete galleries[ shortcodeString ];
227
228                                 if ( result )
229                                         return result;
230
231                                 // Fill the default shortcode attributes.
232                                 attrs = _.defaults( shortcode.attrs.named, wp.media.gallery.defaults );
233                                 args  = _.pick( attrs, 'orderby', 'order' );
234
235                                 args.type    = 'image';
236                                 args.perPage = -1;
237
238                                 // Mark the `orderby` override attribute.
239                                 if ( 'rand' === attrs.orderby )
240                                         attrs._orderbyRandom = true;
241
242                                 // Map the `orderby` attribute to the corresponding model property.
243                                 if ( ! attrs.orderby || /^menu_order(?: ID)?$/i.test( attrs.orderby ) )
244                                         args.orderby = 'menuOrder';
245
246                                 // Map the `ids` param to the correct query args.
247                                 if ( attrs.ids ) {
248                                         args.post__in = attrs.ids.split(',');
249                                         args.orderby  = 'post__in';
250                                 } else if ( attrs.include ) {
251                                         args.post__in = attrs.include.split(',');
252                                 }
253
254                                 if ( attrs.exclude )
255                                         args.post__not_in = attrs.exclude.split(',');
256
257                                 if ( ! args.post__in )
258                                         args.uploadedTo = attrs.id;
259
260                                 // Collect the attributes that were not included in `args`.
261                                 others = _.omit( attrs, 'id', 'ids', 'include', 'exclude', 'orderby', 'order' );
262
263                                 query = wp.media.query( args );
264                                 query.gallery = new Backbone.Model( others );
265                                 return query;
266                         },
267
268                         shortcode: function( attachments ) {
269                                 var props = attachments.props.toJSON(),
270                                         attrs = _.pick( props, 'orderby', 'order' ),
271                                         shortcode, clone;
272
273                                 if ( attachments.gallery )
274                                         _.extend( attrs, attachments.gallery.toJSON() );
275
276                                 // Convert all gallery shortcodes to use the `ids` property.
277                                 // Ignore `post__in` and `post__not_in`; the attachments in
278                                 // the collection will already reflect those properties.
279                                 attrs.ids = attachments.pluck('id');
280
281                                 // Copy the `uploadedTo` post ID.
282                                 if ( props.uploadedTo )
283                                         attrs.id = props.uploadedTo;
284
285                                 // Check if the gallery is randomly ordered.
286                                 if ( attrs._orderbyRandom )
287                                         attrs.orderby = 'rand';
288                                 delete attrs._orderbyRandom;
289
290                                 // If the `ids` attribute is set and `orderby` attribute
291                                 // is the default value, clear it for cleaner output.
292                                 if ( attrs.ids && 'post__in' === attrs.orderby )
293                                         delete attrs.orderby;
294
295                                 // Remove default attributes from the shortcode.
296                                 _.each( wp.media.gallery.defaults, function( value, key ) {
297                                         if ( value === attrs[ key ] )
298                                                 delete attrs[ key ];
299                                 });
300
301                                 shortcode = new wp.shortcode({
302                                         tag:    'gallery',
303                                         attrs:  attrs,
304                                         type:   'single'
305                                 });
306
307                                 // Use a cloned version of the gallery.
308                                 clone = new wp.media.model.Attachments( attachments.models, {
309                                         props: props
310                                 });
311                                 clone.gallery = attachments.gallery;
312                                 galleries[ shortcode.string() ] = clone;
313
314                                 return shortcode;
315                         },
316
317                         edit: function( content ) {
318                                 var shortcode = wp.shortcode.next( 'gallery', content ),
319                                         defaultPostId = wp.media.gallery.defaults.id,
320                                         attachments, selection;
321
322                                 // Bail if we didn't match the shortcode or all of the content.
323                                 if ( ! shortcode || shortcode.content !== content )
324                                         return;
325
326                                 // Ignore the rest of the match object.
327                                 shortcode = shortcode.shortcode;
328
329                                 if ( _.isUndefined( shortcode.get('id') ) && ! _.isUndefined( defaultPostId ) )
330                                         shortcode.set( 'id', defaultPostId );
331
332                                 attachments = wp.media.gallery.attachments( shortcode );
333
334                                 selection = new wp.media.model.Selection( attachments.models, {
335                                         props:    attachments.props.toJSON(),
336                                         multiple: true
337                                 });
338
339                                 selection.gallery = attachments.gallery;
340
341                                 // Fetch the query's attachments, and then break ties from the
342                                 // query to allow for sorting.
343                                 selection.more().done( function() {
344                                         // Break ties with the query.
345                                         selection.props.set({ query: false });
346                                         selection.unmirror();
347                                         selection.props.unset('orderby');
348                                 });
349
350                                 // Destroy the previous gallery frame.
351                                 if ( this.frame )
352                                         this.frame.dispose();
353
354                                 // Store the current gallery frame.
355                                 this.frame = wp.media({
356                                         frame:     'post',
357                                         state:     'gallery-edit',
358                                         title:     wp.media.view.l10n.editGalleryTitle,
359                                         editing:   true,
360                                         multiple:  true,
361                                         selection: selection
362                                 }).open();
363
364                                 return this.frame;
365                         }
366                 };
367         }());
368
369         wp.media.featuredImage = {
370                 get: function() {
371                         return wp.media.view.settings.post.featuredImageId;
372                 },
373
374                 set: function( id ) {
375                         var settings = wp.media.view.settings;
376
377                         settings.post.featuredImageId = id;
378
379                         wp.media.post( 'set-post-thumbnail', {
380                                 json:         true,
381                                 post_id:      settings.post.id,
382                                 thumbnail_id: settings.post.featuredImageId,
383                                 _wpnonce:     settings.post.nonce
384                         }).done( function( html ) {
385                                 $( '.inside', '#postimagediv' ).html( html );
386                         });
387                 },
388
389                 frame: function() {
390                         if ( this._frame )
391                                 return this._frame;
392
393                         this._frame = wp.media({
394                                 state: 'featured-image',
395                                 states: [ new wp.media.controller.FeaturedImage() ]
396                         });
397
398                         this._frame.on( 'toolbar:create:featured-image', function( toolbar ) {
399                                 this.createSelectToolbar( toolbar, {
400                                         text: wp.media.view.l10n.setFeaturedImage
401                                 });
402                         }, this._frame );
403
404                         this._frame.state('featured-image').on( 'select', this.select );
405                         return this._frame;
406                 },
407
408                 select: function() {
409                         var settings = wp.media.view.settings,
410                                 selection = this.get('selection').single();
411
412                         if ( ! settings.post.featuredImageId )
413                                 return;
414
415                         wp.media.featuredImage.set( selection ? selection.id : -1 );
416                 },
417
418                 init: function() {
419                         // Open the content media manager to the 'featured image' tab when
420                         // the post thumbnail is clicked.
421                         $('#postimagediv').on( 'click', '#set-post-thumbnail', function( event ) {
422                                 event.preventDefault();
423                                 // Stop propagation to prevent thickbox from activating.
424                                 event.stopPropagation();
425
426                                 wp.media.featuredImage.frame().open();
427
428                         // Update the featured image id when the 'remove' link is clicked.
429                         }).on( 'click', '#remove-post-thumbnail', function() {
430                                 wp.media.view.settings.post.featuredImageId = -1;
431                         });
432                 }
433         };
434
435         $( wp.media.featuredImage.init );
436
437         wp.media.editor = {
438                 insert: function( h ) {
439                         var mce = typeof(tinymce) != 'undefined',
440                                 qt = typeof(QTags) != 'undefined',
441                                 wpActiveEditor = window.wpActiveEditor,
442                                 ed;
443
444                         // Delegate to the global `send_to_editor` if it exists.
445                         // This attempts to play nice with any themes/plugins that have
446                         // overridden the insert functionality.
447                         if ( window.send_to_editor )
448                                 return window.send_to_editor.apply( this, arguments );
449
450                         if ( ! wpActiveEditor ) {
451                                 if ( mce && tinymce.activeEditor ) {
452                                         ed = tinymce.activeEditor;
453                                         wpActiveEditor = window.wpActiveEditor = ed.id;
454                                 } else if ( !qt ) {
455                                         return false;
456                                 }
457                         } else if ( mce ) {
458                                 if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') )
459                                         ed = tinymce.activeEditor;
460                                 else
461                                         ed = tinymce.get(wpActiveEditor);
462                         }
463
464                         if ( ed && !ed.isHidden() ) {
465                                 // restore caret position on IE
466                                 if ( tinymce.isIE && ed.windowManager.insertimagebookmark )
467                                         ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark);
468
469                                 if ( h.indexOf('[caption') !== -1 ) {
470                                         if ( ed.wpSetImgCaption )
471                                                 h = ed.wpSetImgCaption(h);
472                                 } else if ( h.indexOf('[gallery') !== -1 ) {
473                                         if ( ed.plugins.wpgallery )
474                                                 h = ed.plugins.wpgallery._do_gallery(h);
475                                 } else if ( h.indexOf('[embed') === 0 ) {
476                                         if ( ed.plugins.wordpress )
477                                                 h = ed.plugins.wordpress._setEmbed(h);
478                                 }
479
480                                 ed.execCommand('mceInsertContent', false, h);
481                         } else if ( qt ) {
482                                 QTags.insertContent(h);
483                         } else {
484                                 document.getElementById(wpActiveEditor).value += h;
485                         }
486
487                         // If the old thickbox remove function exists, call it in case
488                         // a theme/plugin overloaded it.
489                         if ( window.tb_remove )
490                                 try { window.tb_remove(); } catch( e ) {}
491                 },
492
493                 add: function( id, options ) {
494                         var workflow = this.get( id );
495
496                         if ( workflow ) // only add once: if exists return existing
497                                 return workflow;
498
499                         workflow = workflows[ id ] = wp.media( _.defaults( options || {}, {
500                                 frame:    'post',
501                                 state:    'insert',
502                                 title:    wp.media.view.l10n.addMedia,
503                                 multiple: true
504                         } ) );
505
506                         workflow.on( 'insert', function( selection ) {
507                                 var state = workflow.state();
508
509                                 selection = selection || state.get('selection');
510
511                                 if ( ! selection )
512                                         return;
513
514                                 $.when.apply( $, selection.map( function( attachment ) {
515                                         var display = state.display( attachment ).toJSON();
516                                         return this.send.attachment( display, attachment.toJSON() );
517                                 }, this ) ).done( function() {
518                                         wp.media.editor.insert( _.toArray( arguments ).join("\n\n") );
519                                 });
520                         }, this );
521
522                         workflow.state('gallery-edit').on( 'update', function( selection ) {
523                                 this.insert( wp.media.gallery.shortcode( selection ).string() );
524                         }, this );
525
526                         workflow.state('embed').on( 'select', function() {
527                                 var state = workflow.state(),
528                                         type = state.get('type'),
529                                         embed = state.props.toJSON();
530
531                                 embed.url = embed.url || '';
532
533                                 if ( 'link' === type ) {
534                                         _.defaults( embed, {
535                                                 title:   embed.url,
536                                                 linkUrl: embed.url
537                                         });
538
539                                         this.send.link( embed ).done( function( resp ) {
540                                                 wp.media.editor.insert( resp );
541                                         });
542
543                                 } else if ( 'image' === type ) {
544                                         _.defaults( embed, {
545                                                 title:   embed.url,
546                                                 linkUrl: '',
547                                                 align:   'none',
548                                                 link:    'none'
549                                         });
550
551                                         if ( 'none' === embed.link )
552                                                 embed.linkUrl = '';
553                                         else if ( 'file' === embed.link )
554                                                 embed.linkUrl = embed.url;
555
556                                         this.insert( wp.media.string.image( embed ) );
557                                 }
558                         }, this );
559
560                         workflow.state('featured-image').on( 'select', wp.media.featuredImage.select );
561                         workflow.setState( workflow.options.state );
562                         return workflow;
563                 },
564
565                 id: function( id ) {
566                         if ( id )
567                                 return id;
568
569                         // If an empty `id` is provided, default to `wpActiveEditor`.
570                         id = wpActiveEditor;
571
572                         // If that doesn't work, fall back to `tinymce.activeEditor.id`.
573                         if ( ! id && typeof tinymce !== 'undefined' && tinymce.activeEditor )
574                                 id = tinymce.activeEditor.id;
575
576                         // Last but not least, fall back to the empty string.
577                         id = id || '';
578                         return id;
579                 },
580
581                 get: function( id ) {
582                         id = this.id( id );
583                         return workflows[ id ];
584                 },
585
586                 remove: function( id ) {
587                         id = this.id( id );
588                         delete workflows[ id ];
589                 },
590
591                 send: {
592                         attachment: function( props, attachment ) {
593                                 var caption = attachment.caption,
594                                         options, html;
595
596                                 // If captions are disabled, clear the caption.
597                                 if ( ! wp.media.view.settings.captions )
598                                         delete attachment.caption;
599
600                                 props = wp.media.string.props( props, attachment );
601
602                                 options = {
603                                         id:           attachment.id,
604                                         post_content: attachment.description,
605                                         post_excerpt: caption
606                                 };
607
608                                 if ( props.linkUrl )
609                                         options.url = props.linkUrl;
610
611                                 if ( 'image' === attachment.type ) {
612                                         html = wp.media.string.image( props );
613
614                                         _.each({
615                                                 align: 'align',
616                                                 size:  'image-size',
617                                                 alt:   'image_alt'
618                                         }, function( option, prop ) {
619                                                 if ( props[ prop ] )
620                                                         options[ option ] = props[ prop ];
621                                         });
622                                 } else if ( 'video' === attachment.type ) {
623                                         html = wp.media.string.video( props, attachment );
624                                 } else if ( 'audio' === attachment.type ) {
625                                         html = wp.media.string.audio( props, attachment );
626                                 } else {
627                                         html = wp.media.string.link( props );
628                                         options.post_title = props.title;
629                                 }
630
631                                 return wp.media.post( 'send-attachment-to-editor', {
632                                         nonce:      wp.media.view.settings.nonce.sendToEditor,
633                                         attachment: options,
634                                         html:       html,
635                                         post_id:    wp.media.view.settings.post.id
636                                 });
637                         },
638
639                         link: function( embed ) {
640                                 return wp.media.post( 'send-link-to-editor', {
641                                         nonce:   wp.media.view.settings.nonce.sendToEditor,
642                                         src:     embed.linkUrl,
643                                         title:   embed.title,
644                                         html:    wp.media.string.link( embed ),
645                                         post_id: wp.media.view.settings.post.id
646                                 });
647                         }
648                 },
649
650                 open: function( id, options ) {
651                         var workflow, editor;
652
653                         options = options || {};
654
655                         id = this.id( id );
656
657                         // Save a bookmark of the caret position in IE.
658                         if ( typeof tinymce !== 'undefined' ) {
659                                 editor = tinymce.get( id );
660
661                                 if ( tinymce.isIE && editor && ! editor.isHidden() ) {
662                                         editor.focus();
663                                         editor.windowManager.insertimagebookmark = editor.selection.getBookmark();
664                                 }
665                         }
666
667                         workflow = this.get( id );
668
669                         // Redo workflow if state has changed
670                         if ( ! workflow || ( workflow.options && options.state !== workflow.options.state ) )
671                                 workflow = this.add( id, options );
672
673                         return workflow.open();
674                 },
675
676                 init: function() {
677                         $(document.body).on( 'click', '.insert-media', function( event ) {
678                                 var $this = $(this),
679                                         editor = $this.data('editor'),
680                                         options = {
681                                                 frame:    'post',
682                                                 state:    'insert',
683                                                 title:    wp.media.view.l10n.addMedia,
684                                                 multiple: true
685                                         };
686
687                                 event.preventDefault();
688
689                                 // Remove focus from the `.insert-media` button.
690                                 // Prevents Opera from showing the outline of the button
691                                 // above the modal.
692                                 //
693                                 // See: http://core.trac.wordpress.org/ticket/22445
694                                 $this.blur();
695
696                                 if ( $this.hasClass( 'gallery' ) ) {
697                                         options.state = 'gallery';
698                                         options.title = wp.media.view.l10n.createGalleryTitle;
699                                 }
700
701                                 wp.media.editor.open( editor, options );
702                         });
703                 }
704         };
705
706         _.bindAll( wp.media.editor, 'open' );
707         $( wp.media.editor.init );
708 }(jQuery));