1 // WordPress, TinyMCE, and Media
2 // -----------------------------
4 // Stores the editors' `wp.media.controller.Frame` instances.
8 // Joins the `props` and `attachment` objects,
9 // outputting the proper object format based on the
11 props: function( props, attachment ) {
12 var link, linkUrl, size, sizes, fallbacks,
13 defaultProps = wp.media.view.settings.defaultProps;
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, ' ' );
27 props = props ? _.clone( props ) : {};
29 if ( attachment && attachment.type )
30 props.type = attachment.type;
32 if ( 'image' === props.type ) {
33 props = _.defaults( props || {}, {
34 align: defaultProps.align || getUserSetting( 'align', 'none' ),
35 size: defaultProps.size || getUserSetting( 'imgsize', 'medium' ),
41 // All attachment-specific settings follow.
43 return fallbacks( props );
45 props.title = props.title || attachment.title;
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 || '';
56 // Format properties for images.
57 if ( 'image' === attachment.type ) {
58 props.classes.push( 'wp-image-' + attachment.id );
60 sizes = attachment.sizes;
61 size = sizes && sizes[ props.size ] ? sizes[ props.size ] : attachment;
63 _.extend( props, _.pick( attachment, 'align', 'caption', 'alt' ), {
67 captionId: 'attachment_' + attachment.id
69 } else if ( 'video' === attachment.type || 'audio' === attachment.type ) {
70 _.extend( props, _.pick( attachment, 'title', 'type', 'icon', 'mime' ) );
71 // Format properties for non-images.
73 props.title = props.title || attachment.filename;
74 props.rel = props.rel || 'attachment wp-att-' + attachment.id;
77 return fallbacks( props );
80 link: function( props, attachment ) {
83 props = wp.media.string.props( props, attachment );
94 options.attrs.rel = props.rel;
96 return wp.html.string( options );
99 audio: function( props, attachment ) {
100 return wp.media.string._audioVideo( 'audio', props, attachment );
103 video: function( props, attachment ) {
104 return wp.media.string._audioVideo( 'video', props, attachment );
107 _audioVideo: function( type, props, attachment ) {
108 var shortcode, html, extension;
110 props = wp.media.string.props( props, attachment );
111 if ( props.link !== 'embed' )
112 return wp.media.string.link( props );
116 if ( 'video' === type ) {
117 if ( attachment.width )
118 shortcode.width = attachment.width;
120 if ( attachment.height )
121 shortcode.height = attachment.height;
124 extension = attachment.filename.split('.').pop();
126 if ( _.contains( wp.media.view.settings.embedExts, extension ) ) {
127 shortcode[extension] = attachment.url;
129 // Render unsupported audio and video files as links.
130 return wp.media.string.link( props );
133 html = wp.shortcode.string({
141 image: function( props, attachment ) {
143 options, classes, shortcode, html;
145 props = wp.media.string.props( props, attachment );
146 classes = props.classes || [];
148 img.src = typeof attachment !== 'undefined' ? attachment.url : props.url;
149 _.extend( img, _.pick( props, 'width', 'height', 'alt' ) );
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 );
157 classes.push( 'size-' + props.size );
159 img['class'] = _.compact( classes ).join(' ');
161 // Generate `img` tag options.
168 // Generate the `a` element options, if they exist.
169 if ( props.linkUrl ) {
179 html = wp.html.string( options );
181 // Generate the caption shortcode.
182 if ( props.caption ) {
186 shortcode.width = img.width;
188 if ( props.captionId )
189 shortcode.id = props.captionId;
192 shortcode.align = 'align' + props.align;
194 html = wp.shortcode.string({
197 content: html + ' ' + props.caption
205 wp.media.gallery = (function() {
211 id: wp.media.view.settings.post.id,
218 orderby: 'menu_order ID'
221 attachments: function( shortcode ) {
222 var shortcodeString = shortcode.string(),
223 result = galleries[ shortcodeString ],
224 attrs, args, query, others;
226 delete galleries[ shortcodeString ];
231 // Fill the default shortcode attributes.
232 attrs = _.defaults( shortcode.attrs.named, wp.media.gallery.defaults );
233 args = _.pick( attrs, 'orderby', 'order' );
238 // Mark the `orderby` override attribute.
239 if ( 'rand' === attrs.orderby )
240 attrs._orderbyRandom = true;
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';
246 // Map the `ids` param to the correct query args.
248 args.post__in = attrs.ids.split(',');
249 args.orderby = 'post__in';
250 } else if ( attrs.include ) {
251 args.post__in = attrs.include.split(',');
255 args.post__not_in = attrs.exclude.split(',');
257 if ( ! args.post__in )
258 args.uploadedTo = attrs.id;
260 // Collect the attributes that were not included in `args`.
261 others = _.omit( attrs, 'id', 'ids', 'include', 'exclude', 'orderby', 'order' );
263 query = wp.media.query( args );
264 query.gallery = new Backbone.Model( others );
268 shortcode: function( attachments ) {
269 var props = attachments.props.toJSON(),
270 attrs = _.pick( props, 'orderby', 'order' ),
273 if ( attachments.gallery )
274 _.extend( attrs, attachments.gallery.toJSON() );
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');
281 // Copy the `uploadedTo` post ID.
282 if ( props.uploadedTo )
283 attrs.id = props.uploadedTo;
285 // Check if the gallery is randomly ordered.
286 if ( attrs._orderbyRandom )
287 attrs.orderby = 'rand';
288 delete attrs._orderbyRandom;
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;
295 // Remove default attributes from the shortcode.
296 _.each( wp.media.gallery.defaults, function( value, key ) {
297 if ( value === attrs[ key ] )
301 shortcode = new wp.shortcode({
307 // Use a cloned version of the gallery.
308 clone = new wp.media.model.Attachments( attachments.models, {
311 clone.gallery = attachments.gallery;
312 galleries[ shortcode.string() ] = clone;
317 edit: function( content ) {
318 var shortcode = wp.shortcode.next( 'gallery', content ),
319 defaultPostId = wp.media.gallery.defaults.id,
320 attachments, selection;
322 // Bail if we didn't match the shortcode or all of the content.
323 if ( ! shortcode || shortcode.content !== content )
326 // Ignore the rest of the match object.
327 shortcode = shortcode.shortcode;
329 if ( _.isUndefined( shortcode.get('id') ) && ! _.isUndefined( defaultPostId ) )
330 shortcode.set( 'id', defaultPostId );
332 attachments = wp.media.gallery.attachments( shortcode );
334 selection = new wp.media.model.Selection( attachments.models, {
335 props: attachments.props.toJSON(),
339 selection.gallery = attachments.gallery;
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');
350 // Destroy the previous gallery frame.
352 this.frame.dispose();
354 // Store the current gallery frame.
355 this.frame = wp.media({
357 state: 'gallery-edit',
358 title: wp.media.view.l10n.editGalleryTitle,
369 wp.media.featuredImage = {
371 return wp.media.view.settings.post.featuredImageId;
374 set: function( id ) {
375 var settings = wp.media.view.settings;
377 settings.post.featuredImageId = id;
379 wp.media.post( 'set-post-thumbnail', {
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 );
393 this._frame = wp.media({
394 state: 'featured-image',
395 states: [ new wp.media.controller.FeaturedImage() ]
398 this._frame.on( 'toolbar:create:featured-image', function( toolbar ) {
399 this.createSelectToolbar( toolbar, {
400 text: wp.media.view.l10n.setFeaturedImage
404 this._frame.state('featured-image').on( 'select', this.select );
409 var settings = wp.media.view.settings,
410 selection = this.get('selection').single();
412 if ( ! settings.post.featuredImageId )
415 wp.media.featuredImage.set( selection ? selection.id : -1 );
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();
426 wp.media.featuredImage.frame().open();
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;
435 $( wp.media.featuredImage.init );
438 insert: function( h ) {
439 var mce = typeof(tinymce) != 'undefined',
440 qt = typeof(QTags) != 'undefined',
441 wpActiveEditor = window.wpActiveEditor,
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 );
450 if ( ! wpActiveEditor ) {
451 if ( mce && tinymce.activeEditor ) {
452 ed = tinymce.activeEditor;
453 wpActiveEditor = window.wpActiveEditor = ed.id;
458 if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') )
459 ed = tinymce.activeEditor;
461 ed = tinymce.get(wpActiveEditor);
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);
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);
480 ed.execCommand('mceInsertContent', false, h);
482 QTags.insertContent(h);
484 document.getElementById(wpActiveEditor).value += h;
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 ) {}
493 add: function( id, options ) {
494 var workflow = this.get( id );
496 if ( workflow ) // only add once: if exists return existing
499 workflow = workflows[ id ] = wp.media( _.defaults( options || {}, {
502 title: wp.media.view.l10n.addMedia,
506 workflow.on( 'insert', function( selection ) {
507 var state = workflow.state();
509 selection = selection || state.get('selection');
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") );
522 workflow.state('gallery-edit').on( 'update', function( selection ) {
523 this.insert( wp.media.gallery.shortcode( selection ).string() );
526 workflow.state('embed').on( 'select', function() {
527 var state = workflow.state(),
528 type = state.get('type'),
529 embed = state.props.toJSON();
531 embed.url = embed.url || '';
533 if ( 'link' === type ) {
539 this.send.link( embed ).done( function( resp ) {
540 wp.media.editor.insert( resp );
543 } else if ( 'image' === type ) {
551 if ( 'none' === embed.link )
553 else if ( 'file' === embed.link )
554 embed.linkUrl = embed.url;
556 this.insert( wp.media.string.image( embed ) );
560 workflow.state('featured-image').on( 'select', wp.media.featuredImage.select );
561 workflow.setState( workflow.options.state );
569 // If an empty `id` is provided, default to `wpActiveEditor`.
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;
576 // Last but not least, fall back to the empty string.
581 get: function( id ) {
583 return workflows[ id ];
586 remove: function( id ) {
588 delete workflows[ id ];
592 attachment: function( props, attachment ) {
593 var caption = attachment.caption,
596 // If captions are disabled, clear the caption.
597 if ( ! wp.media.view.settings.captions )
598 delete attachment.caption;
600 props = wp.media.string.props( props, attachment );
604 post_content: attachment.description,
605 post_excerpt: caption
609 options.url = props.linkUrl;
611 if ( 'image' === attachment.type ) {
612 html = wp.media.string.image( props );
618 }, function( option, prop ) {
620 options[ option ] = props[ prop ];
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 );
627 html = wp.media.string.link( props );
628 options.post_title = props.title;
631 return wp.media.post( 'send-attachment-to-editor', {
632 nonce: wp.media.view.settings.nonce.sendToEditor,
635 post_id: wp.media.view.settings.post.id
639 link: function( embed ) {
640 return wp.media.post( 'send-link-to-editor', {
641 nonce: wp.media.view.settings.nonce.sendToEditor,
644 html: wp.media.string.link( embed ),
645 post_id: wp.media.view.settings.post.id
650 open: function( id, options ) {
651 var workflow, editor;
653 options = options || {};
657 // Save a bookmark of the caret position in IE.
658 if ( typeof tinymce !== 'undefined' ) {
659 editor = tinymce.get( id );
661 if ( tinymce.isIE && editor && ! editor.isHidden() ) {
663 editor.windowManager.insertimagebookmark = editor.selection.getBookmark();
667 workflow = this.get( id );
669 // Redo workflow if state has changed
670 if ( ! workflow || ( workflow.options && options.state !== workflow.options.state ) )
671 workflow = this.add( id, options );
673 return workflow.open();
677 $(document.body).on( 'click', '.insert-media', function( event ) {
679 editor = $this.data('editor'),
683 title: wp.media.view.l10n.addMedia,
687 event.preventDefault();
689 // Remove focus from the `.insert-media` button.
690 // Prevents Opera from showing the outline of the button
693 // See: http://core.trac.wordpress.org/ticket/22445
696 if ( $this.hasClass( 'gallery' ) ) {
697 options.state = 'gallery';
698 options.title = wp.media.view.l10n.createGalleryTitle;
701 wp.media.editor.open( editor, options );
706 _.bindAll( wp.media.editor, 'open' );
707 $( wp.media.editor.init );