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,
174 orderby: 'menu_order ID'
177 attachments: function( shortcode ) {
178 var shortcodeString = shortcode.string(),
179 result = galleries[ shortcodeString ],
180 attrs, args, query, others;
182 delete galleries[ shortcodeString ];
187 // Fill the default shortcode attributes.
188 attrs = _.defaults( shortcode.attrs.named, wp.media.gallery.defaults );
189 args = _.pick( attrs, 'orderby', 'order' );
194 // Mark the `orderby` override attribute.
195 if ( 'rand' === attrs.orderby )
196 attrs._orderbyRandom = true;
198 // Map the `orderby` attribute to the corresponding model property.
199 if ( ! attrs.orderby || /^menu_order(?: ID)?$/i.test( attrs.orderby ) )
200 args.orderby = 'menuOrder';
202 // Map the `ids` param to the correct query args.
204 args.post__in = attrs.ids.split(',');
205 args.orderby = 'post__in';
206 } else if ( attrs.include ) {
207 args.post__in = attrs.include.split(',');
211 args.post__not_in = attrs.exclude.split(',');
213 if ( ! args.post__in )
214 args.uploadedTo = attrs.id;
216 // Collect the attributes that were not included in `args`.
217 others = _.omit( attrs, 'id', 'ids', 'include', 'exclude', 'orderby', 'order' );
219 query = wp.media.query( args );
220 query.gallery = new Backbone.Model( others );
224 shortcode: function( attachments ) {
225 var props = attachments.props.toJSON(),
226 attrs = _.pick( props, 'orderby', 'order' ),
229 if ( attachments.gallery )
230 _.extend( attrs, attachments.gallery.toJSON() );
232 // Convert all gallery shortcodes to use the `ids` property.
233 // Ignore `post__in` and `post__not_in`; the attachments in
234 // the collection will already reflect those properties.
235 attrs.ids = attachments.pluck('id');
237 // Copy the `uploadedTo` post ID.
238 if ( props.uploadedTo )
239 attrs.id = props.uploadedTo;
241 // Check if the gallery is randomly ordered.
242 if ( attrs._orderbyRandom )
243 attrs.orderby = 'rand';
244 delete attrs._orderbyRandom;
246 // If the `ids` attribute is set and `orderby` attribute
247 // is the default value, clear it for cleaner output.
248 if ( attrs.ids && 'post__in' === attrs.orderby )
249 delete attrs.orderby;
251 // Remove default attributes from the shortcode.
252 _.each( wp.media.gallery.defaults, function( value, key ) {
253 if ( value === attrs[ key ] )
257 shortcode = new wp.shortcode({
263 // Use a cloned version of the gallery.
264 clone = new wp.media.model.Attachments( attachments.models, {
267 clone.gallery = attachments.gallery;
268 galleries[ shortcode.string() ] = clone;
273 edit: function( content ) {
274 var shortcode = wp.shortcode.next( 'gallery', content ),
275 defaultPostId = wp.media.gallery.defaults.id,
276 attachments, selection;
278 // Bail if we didn't match the shortcode or all of the content.
279 if ( ! shortcode || shortcode.content !== content )
282 // Ignore the rest of the match object.
283 shortcode = shortcode.shortcode;
285 if ( _.isUndefined( shortcode.get('id') ) && ! _.isUndefined( defaultPostId ) )
286 shortcode.set( 'id', defaultPostId );
288 attachments = wp.media.gallery.attachments( shortcode );
290 selection = new wp.media.model.Selection( attachments.models, {
291 props: attachments.props.toJSON(),
295 selection.gallery = attachments.gallery;
297 // Fetch the query's attachments, and then break ties from the
298 // query to allow for sorting.
299 selection.more().done( function() {
300 // Break ties with the query.
301 selection.props.set({ query: false });
302 selection.unmirror();
303 selection.props.unset('orderby');
306 // Destroy the previous gallery frame.
308 this.frame.dispose();
310 // Store the current gallery frame.
311 this.frame = wp.media({
313 state: 'gallery-edit',
314 title: wp.media.view.l10n.editGalleryTitle,
325 wp.media.featuredImage = {
327 return wp.media.view.settings.post.featuredImageId;
330 set: function( id ) {
331 var settings = wp.media.view.settings;
333 settings.post.featuredImageId = id;
335 wp.media.post( 'set-post-thumbnail', {
337 post_id: settings.post.id,
338 thumbnail_id: settings.post.featuredImageId,
339 _wpnonce: settings.post.nonce
340 }).done( function( html ) {
341 $( '.inside', '#postimagediv' ).html( html );
349 this._frame = wp.media({
350 state: 'featured-image',
351 states: [ new wp.media.controller.FeaturedImage() ]
354 this._frame.on( 'toolbar:create:featured-image', function( toolbar ) {
355 this.createSelectToolbar( toolbar, {
356 text: wp.media.view.l10n.setFeaturedImage
360 this._frame.state('featured-image').on( 'select', this.select );
365 var settings = wp.media.view.settings,
366 selection = this.get('selection').single();
368 if ( ! settings.post.featuredImageId )
371 wp.media.featuredImage.set( selection ? selection.id : -1 );
375 // Open the content media manager to the 'featured image' tab when
376 // the post thumbnail is clicked.
377 $('#postimagediv').on( 'click', '#set-post-thumbnail', function( event ) {
378 event.preventDefault();
379 // Stop propagation to prevent thickbox from activating.
380 event.stopPropagation();
382 wp.media.featuredImage.frame().open();
384 // Update the featured image id when the 'remove' link is clicked.
385 }).on( 'click', '#remove-post-thumbnail', function() {
386 wp.media.view.settings.post.featuredImageId = -1;
391 $( wp.media.featuredImage.init );
394 insert: function( h ) {
395 var mce = typeof(tinymce) != 'undefined',
396 qt = typeof(QTags) != 'undefined',
397 wpActiveEditor = window.wpActiveEditor,
400 // Delegate to the global `send_to_editor` if it exists.
401 // This attempts to play nice with any themes/plugins that have
402 // overridden the insert functionality.
403 if ( window.send_to_editor )
404 return window.send_to_editor.apply( this, arguments );
406 if ( ! wpActiveEditor ) {
407 if ( mce && tinymce.activeEditor ) {
408 ed = tinymce.activeEditor;
409 wpActiveEditor = window.wpActiveEditor = ed.id;
414 if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') )
415 ed = tinymce.activeEditor;
417 ed = tinymce.get(wpActiveEditor);
420 if ( ed && !ed.isHidden() ) {
421 // restore caret position on IE
422 if ( tinymce.isIE && ed.windowManager.insertimagebookmark )
423 ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark);
425 if ( h.indexOf('[caption') !== -1 ) {
426 if ( ed.wpSetImgCaption )
427 h = ed.wpSetImgCaption(h);
428 } else if ( h.indexOf('[gallery') !== -1 ) {
429 if ( ed.plugins.wpgallery )
430 h = ed.plugins.wpgallery._do_gallery(h);
431 } else if ( h.indexOf('[embed') === 0 ) {
432 if ( ed.plugins.wordpress )
433 h = ed.plugins.wordpress._setEmbed(h);
436 ed.execCommand('mceInsertContent', false, h);
438 QTags.insertContent(h);
440 document.getElementById(wpActiveEditor).value += h;
443 // If the old thickbox remove function exists, call it in case
444 // a theme/plugin overloaded it.
445 if ( window.tb_remove )
446 try { window.tb_remove(); } catch( e ) {}
449 add: function( id, options ) {
450 var workflow = this.get( id );
455 workflow = workflows[ id ] = wp.media( _.defaults( options || {}, {
458 title: wp.media.view.l10n.addMedia,
462 workflow.on( 'insert', function( selection ) {
463 var state = workflow.state();
465 selection = selection || state.get('selection');
470 $.when.apply( $, selection.map( function( attachment ) {
471 var display = state.display( attachment ).toJSON();
472 return this.send.attachment( display, attachment.toJSON() );
473 }, this ) ).done( function() {
474 wp.media.editor.insert( _.toArray( arguments ).join("\n\n") );
478 workflow.state('gallery-edit').on( 'update', function( selection ) {
479 this.insert( wp.media.gallery.shortcode( selection ).string() );
482 workflow.state('embed').on( 'select', function() {
483 var state = workflow.state(),
484 type = state.get('type'),
485 embed = state.props.toJSON();
487 embed.url = embed.url || '';
489 if ( 'link' === type ) {
495 this.send.link( embed ).done( function( resp ) {
496 wp.media.editor.insert( resp );
499 } else if ( 'image' === type ) {
507 if ( 'none' === embed.link )
509 else if ( 'file' === embed.link )
510 embed.linkUrl = embed.url;
512 this.insert( wp.media.string.image( embed ) );
516 workflow.state('featured-image').on( 'select', wp.media.featuredImage.select );
517 workflow.setState( workflow.options.state );
525 // If an empty `id` is provided, default to `wpActiveEditor`.
528 // If that doesn't work, fall back to `tinymce.activeEditor.id`.
529 if ( ! id && typeof tinymce !== 'undefined' && tinymce.activeEditor )
530 id = tinymce.activeEditor.id;
532 // Last but not least, fall back to the empty string.
537 get: function( id ) {
539 return workflows[ id ];
542 remove: function( id ) {
544 delete workflows[ id ];
548 attachment: function( props, attachment ) {
549 var caption = attachment.caption,
552 // If captions are disabled, clear the caption.
553 if ( ! wp.media.view.settings.captions )
554 delete attachment.caption;
556 props = wp.media.string.props( props, attachment );
560 post_content: attachment.description,
561 post_excerpt: caption
565 options.url = props.linkUrl;
567 if ( 'image' === attachment.type ) {
568 html = wp.media.string.image( props );
574 }, function( option, prop ) {
576 options[ option ] = props[ prop ];
580 html = wp.media.string.link( props );
581 options.post_title = props.title;
584 return wp.media.post( 'send-attachment-to-editor', {
585 nonce: wp.media.view.settings.nonce.sendToEditor,
588 post_id: wp.media.view.settings.post.id
592 link: function( embed ) {
593 return wp.media.post( 'send-link-to-editor', {
594 nonce: wp.media.view.settings.nonce.sendToEditor,
597 html: wp.media.string.link( embed ),
598 post_id: wp.media.view.settings.post.id
603 open: function( id ) {
604 var workflow, editor;
608 // Save a bookmark of the caret position in IE.
609 if ( typeof tinymce !== 'undefined' ) {
610 editor = tinymce.get( id );
612 if ( tinymce.isIE && editor && ! editor.isHidden() ) {
614 editor.windowManager.insertimagebookmark = editor.selection.getBookmark();
618 workflow = this.get( id );
620 // Initialize the editor's workflow if we haven't yet.
622 workflow = this.add( id );
624 return workflow.open();
628 $(document.body).on( 'click', '.insert-media', function( event ) {
630 editor = $this.data('editor');
632 event.preventDefault();
634 // Remove focus from the `.insert-media` button.
635 // Prevents Opera from showing the outline of the button
638 // See: http://core.trac.wordpress.org/ticket/22445
641 wp.media.editor.open( editor );
646 _.bindAll( wp.media.editor, 'open' );
647 $( wp.media.editor.init );