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 )
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
70 // Format properties for non-images.
72 props.title = props.title || attachment.filename;
73 props.rel = props.rel || 'attachment wp-att-' + attachment.id;
76 return fallbacks( props );
79 link: function( props, attachment ) {
82 props = wp.media.string.props( props, attachment );
93 options.attrs.rel = props.rel;
95 return wp.html.string( options );
98 image: function( props, attachment ) {
100 options, classes, shortcode, html;
102 props = wp.media.string.props( props, attachment );
103 classes = props.classes || [];
106 _.extend( img, _.pick( props, 'width', 'height', 'alt' ) );
108 // Only assign the align class to the image if we're not printing
109 // a caption, since the alignment is sent to the shortcode.
110 if ( props.align && ! props.caption )
111 classes.push( 'align' + props.align );
114 classes.push( 'size-' + props.size );
116 img['class'] = _.compact( classes ).join(' ');
118 // Generate `img` tag options.
125 // Generate the `a` element options, if they exist.
126 if ( props.linkUrl ) {
136 html = wp.html.string( options );
138 // Generate the caption shortcode.
139 if ( props.caption ) {
143 shortcode.width = img.width;
145 if ( props.captionId )
146 shortcode.id = props.captionId;
149 shortcode.align = 'align' + props.align;
151 html = wp.shortcode.string({
154 content: html + ' ' + props.caption
162 wp.media.gallery = (function() {
168 id: wp.media.view.settings.post.id,
175 orderby: 'menu_order ID'
178 attachments: function( shortcode ) {
179 var shortcodeString = shortcode.string(),
180 result = galleries[ shortcodeString ],
181 attrs, args, query, others;
183 delete galleries[ shortcodeString ];
188 // Fill the default shortcode attributes.
189 attrs = _.defaults( shortcode.attrs.named, wp.media.gallery.defaults );
190 args = _.pick( attrs, 'orderby', 'order' );
195 // Mark the `orderby` override attribute.
196 if ( 'rand' === attrs.orderby )
197 attrs._orderbyRandom = true;
199 // Map the `orderby` attribute to the corresponding model property.
200 if ( ! attrs.orderby || /^menu_order(?: ID)?$/i.test( attrs.orderby ) )
201 args.orderby = 'menuOrder';
203 // Map the `ids` param to the correct query args.
205 args.post__in = attrs.ids.split(',');
206 args.orderby = 'post__in';
207 } else if ( attrs.include ) {
208 args.post__in = attrs.include.split(',');
212 args.post__not_in = attrs.exclude.split(',');
214 if ( ! args.post__in )
215 args.uploadedTo = attrs.id;
217 // Collect the attributes that were not included in `args`.
218 others = _.omit( attrs, 'id', 'ids', 'include', 'exclude', 'orderby', 'order' );
220 query = wp.media.query( args );
221 query.gallery = new Backbone.Model( others );
225 shortcode: function( attachments ) {
226 var props = attachments.props.toJSON(),
227 attrs = _.pick( props, 'orderby', 'order' ),
230 if ( attachments.gallery )
231 _.extend( attrs, attachments.gallery.toJSON() );
233 // Convert all gallery shortcodes to use the `ids` property.
234 // Ignore `post__in` and `post__not_in`; the attachments in
235 // the collection will already reflect those properties.
236 attrs.ids = attachments.pluck('id');
238 // Copy the `uploadedTo` post ID.
239 if ( props.uploadedTo )
240 attrs.id = props.uploadedTo;
242 // Check if the gallery is randomly ordered.
243 if ( attrs._orderbyRandom )
244 attrs.orderby = 'rand';
245 delete attrs._orderbyRandom;
247 // If the `ids` attribute is set and `orderby` attribute
248 // is the default value, clear it for cleaner output.
249 if ( attrs.ids && 'post__in' === attrs.orderby )
250 delete attrs.orderby;
252 // Remove default attributes from the shortcode.
253 _.each( wp.media.gallery.defaults, function( value, key ) {
254 if ( value === attrs[ key ] )
258 shortcode = new wp.shortcode({
264 // Use a cloned version of the gallery.
265 clone = new wp.media.model.Attachments( attachments.models, {
268 clone.gallery = attachments.gallery;
269 galleries[ shortcode.string() ] = clone;
274 edit: function( content ) {
275 var shortcode = wp.shortcode.next( 'gallery', content ),
276 defaultPostId = wp.media.gallery.defaults.id,
277 attachments, selection;
279 // Bail if we didn't match the shortcode or all of the content.
280 if ( ! shortcode || shortcode.content !== content )
283 // Ignore the rest of the match object.
284 shortcode = shortcode.shortcode;
286 if ( _.isUndefined( shortcode.get('id') ) && ! _.isUndefined( defaultPostId ) )
287 shortcode.set( 'id', defaultPostId );
289 attachments = wp.media.gallery.attachments( shortcode );
291 selection = new wp.media.model.Selection( attachments.models, {
292 props: attachments.props.toJSON(),
296 selection.gallery = attachments.gallery;
298 // Fetch the query's attachments, and then break ties from the
299 // query to allow for sorting.
300 selection.more().done( function() {
301 // Break ties with the query.
302 selection.props.set({ query: false });
303 selection.unmirror();
304 selection.props.unset('orderby');
307 // Destroy the previous gallery frame.
309 this.frame.dispose();
311 // Store the current gallery frame.
312 this.frame = wp.media({
314 state: 'gallery-edit',
315 title: wp.media.view.l10n.editGalleryTitle,
326 wp.media.featuredImage = {
328 return wp.media.view.settings.post.featuredImageId;
331 set: function( id ) {
332 var settings = wp.media.view.settings;
334 settings.post.featuredImageId = id;
336 wp.media.post( 'set-post-thumbnail', {
338 post_id: settings.post.id,
339 thumbnail_id: settings.post.featuredImageId,
340 _wpnonce: settings.post.nonce
341 }).done( function( html ) {
342 $( '.inside', '#postimagediv' ).html( html );
350 this._frame = wp.media({
351 state: 'featured-image',
352 states: [ new wp.media.controller.FeaturedImage() ]
355 this._frame.on( 'toolbar:create:featured-image', function( toolbar ) {
356 this.createSelectToolbar( toolbar, {
357 text: wp.media.view.l10n.setFeaturedImage
361 this._frame.state('featured-image').on( 'select', this.select );
366 var settings = wp.media.view.settings,
367 selection = this.get('selection').single();
369 if ( ! settings.post.featuredImageId )
372 wp.media.featuredImage.set( selection ? selection.id : -1 );
376 // Open the content media manager to the 'featured image' tab when
377 // the post thumbnail is clicked.
378 $('#postimagediv').on( 'click', '#set-post-thumbnail', function( event ) {
379 event.preventDefault();
380 // Stop propagation to prevent thickbox from activating.
381 event.stopPropagation();
383 wp.media.featuredImage.frame().open();
385 // Update the featured image id when the 'remove' link is clicked.
386 }).on( 'click', '#remove-post-thumbnail', function() {
387 wp.media.view.settings.post.featuredImageId = -1;
392 $( wp.media.featuredImage.init );
395 insert: function( h ) {
396 var mce = typeof(tinymce) != 'undefined',
397 qt = typeof(QTags) != 'undefined',
398 wpActiveEditor = window.wpActiveEditor,
401 // Delegate to the global `send_to_editor` if it exists.
402 // This attempts to play nice with any themes/plugins that have
403 // overridden the insert functionality.
404 if ( window.send_to_editor )
405 return window.send_to_editor.apply( this, arguments );
407 if ( ! wpActiveEditor ) {
408 if ( mce && tinymce.activeEditor ) {
409 ed = tinymce.activeEditor;
410 wpActiveEditor = window.wpActiveEditor = ed.id;
415 if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') )
416 ed = tinymce.activeEditor;
418 ed = tinymce.get(wpActiveEditor);
421 if ( ed && !ed.isHidden() ) {
422 // restore caret position on IE
423 if ( tinymce.isIE && ed.windowManager.insertimagebookmark )
424 ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark);
426 if ( h.indexOf('[caption') !== -1 ) {
427 if ( ed.wpSetImgCaption )
428 h = ed.wpSetImgCaption(h);
429 } else if ( h.indexOf('[gallery') !== -1 ) {
430 if ( ed.plugins.wpgallery )
431 h = ed.plugins.wpgallery._do_gallery(h);
432 } else if ( h.indexOf('[embed') === 0 ) {
433 if ( ed.plugins.wordpress )
434 h = ed.plugins.wordpress._setEmbed(h);
437 ed.execCommand('mceInsertContent', false, h);
439 QTags.insertContent(h);
441 document.getElementById(wpActiveEditor).value += h;
444 // If the old thickbox remove function exists, call it in case
445 // a theme/plugin overloaded it.
446 if ( window.tb_remove )
447 try { window.tb_remove(); } catch( e ) {}
450 add: function( id, options ) {
451 var workflow = this.get( id );
456 workflow = workflows[ id ] = wp.media( _.defaults( options || {}, {
459 title: wp.media.view.l10n.addMedia,
463 workflow.on( 'insert', function( selection ) {
464 var state = workflow.state();
466 selection = selection || state.get('selection');
471 $.when.apply( $, selection.map( function( attachment ) {
472 var display = state.display( attachment ).toJSON();
473 return this.send.attachment( display, attachment.toJSON() );
474 }, this ) ).done( function() {
475 wp.media.editor.insert( _.toArray( arguments ).join("\n\n") );
479 workflow.state('gallery-edit').on( 'update', function( selection ) {
480 this.insert( wp.media.gallery.shortcode( selection ).string() );
483 workflow.state('embed').on( 'select', function() {
484 var state = workflow.state(),
485 type = state.get('type'),
486 embed = state.props.toJSON();
488 embed.url = embed.url || '';
490 if ( 'link' === type ) {
496 this.send.link( embed ).done( function( resp ) {
497 wp.media.editor.insert( resp );
500 } else if ( 'image' === type ) {
508 if ( 'none' === embed.link )
510 else if ( 'file' === embed.link )
511 embed.linkUrl = embed.url;
513 this.insert( wp.media.string.image( embed ) );
517 workflow.state('featured-image').on( 'select', wp.media.featuredImage.select );
518 workflow.setState( workflow.options.state );
526 // If an empty `id` is provided, default to `wpActiveEditor`.
529 // If that doesn't work, fall back to `tinymce.activeEditor.id`.
530 if ( ! id && typeof tinymce !== 'undefined' && tinymce.activeEditor )
531 id = tinymce.activeEditor.id;
533 // Last but not least, fall back to the empty string.
538 get: function( id ) {
540 return workflows[ id ];
543 remove: function( id ) {
545 delete workflows[ id ];
549 attachment: function( props, attachment ) {
550 var caption = attachment.caption,
553 // If captions are disabled, clear the caption.
554 if ( ! wp.media.view.settings.captions )
555 delete attachment.caption;
557 props = wp.media.string.props( props, attachment );
561 post_content: attachment.description,
562 post_excerpt: caption
566 options.url = props.linkUrl;
568 if ( 'image' === attachment.type ) {
569 html = wp.media.string.image( props );
575 }, function( option, prop ) {
577 options[ option ] = props[ prop ];
581 html = wp.media.string.link( props );
582 options.post_title = props.title;
585 return wp.media.post( 'send-attachment-to-editor', {
586 nonce: wp.media.view.settings.nonce.sendToEditor,
589 post_id: wp.media.view.settings.post.id
593 link: function( embed ) {
594 return wp.media.post( 'send-link-to-editor', {
595 nonce: wp.media.view.settings.nonce.sendToEditor,
598 html: wp.media.string.link( embed ),
599 post_id: wp.media.view.settings.post.id
604 open: function( id ) {
605 var workflow, editor;
609 // Save a bookmark of the caret position in IE.
610 if ( typeof tinymce !== 'undefined' ) {
611 editor = tinymce.get( id );
613 if ( tinymce.isIE && editor && ! editor.isHidden() ) {
615 editor.windowManager.insertimagebookmark = editor.selection.getBookmark();
619 workflow = this.get( id );
621 // Initialize the editor's workflow if we haven't yet.
623 workflow = this.add( id );
625 return workflow.open();
629 $(document.body).on( 'click', '.insert-media', function( event ) {
631 editor = $this.data('editor');
633 event.preventDefault();
635 // Remove focus from the `.insert-media` button.
636 // Prevents Opera from showing the outline of the button
639 // See: http://core.trac.wordpress.org/ticket/22445
642 wp.media.editor.open( editor );
647 _.bindAll( wp.media.editor, 'open' );
648 $( wp.media.editor.init );