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( undefined !== attrs.orderby )
240 attrs._orderByField = attrs.orderby;
242 if ( 'rand' === attrs.orderby )
243 attrs._orderbyRandom = true;
245 // Map the `orderby` attribute to the corresponding model property.
246 if ( ! attrs.orderby || /^menu_order(?: ID)?$/i.test( attrs.orderby ) )
247 args.orderby = 'menuOrder';
249 // Map the `ids` param to the correct query args.
251 args.post__in = attrs.ids.split(',');
252 args.orderby = 'post__in';
253 } else if ( attrs.include ) {
254 args.post__in = attrs.include.split(',');
258 args.post__not_in = attrs.exclude.split(',');
260 if ( ! args.post__in )
261 args.uploadedTo = attrs.id;
263 // Collect the attributes that were not included in `args`.
264 others = _.omit( attrs, 'id', 'ids', 'include', 'exclude', 'orderby', 'order' );
266 query = wp.media.query( args );
267 query.gallery = new Backbone.Model( others );
271 shortcode: function( attachments ) {
272 var props = attachments.props.toJSON(),
273 attrs = _.pick( props, 'orderby', 'order' ),
276 if ( attachments.gallery )
277 _.extend( attrs, attachments.gallery.toJSON() );
279 // Convert all gallery shortcodes to use the `ids` property.
280 // Ignore `post__in` and `post__not_in`; the attachments in
281 // the collection will already reflect those properties.
282 attrs.ids = attachments.pluck('id');
284 // Copy the `uploadedTo` post ID.
285 if ( props.uploadedTo )
286 attrs.id = props.uploadedTo;
288 // Check if the gallery is randomly ordered.
289 delete attrs.orderby;
291 if ( attrs._orderbyRandom )
292 attrs.orderby = 'rand';
293 else if ( attrs._orderByField && attrs._orderByField != 'rand' )
294 attrs.orderby = attrs._orderByField;
296 delete attrs._orderbyRandom;
297 delete attrs._orderByField;
299 // If the `ids` attribute is set and `orderby` attribute
300 // is the default value, clear it for cleaner output.
301 if ( attrs.ids && 'post__in' === attrs.orderby )
302 delete attrs.orderby;
304 // Remove default attributes from the shortcode.
305 _.each( wp.media.gallery.defaults, function( value, key ) {
306 if ( value === attrs[ key ] )
310 shortcode = new wp.shortcode({
316 // Use a cloned version of the gallery.
317 clone = new wp.media.model.Attachments( attachments.models, {
320 clone.gallery = attachments.gallery;
321 galleries[ shortcode.string() ] = clone;
326 edit: function( content ) {
327 var shortcode = wp.shortcode.next( 'gallery', content ),
328 defaultPostId = wp.media.gallery.defaults.id,
329 attachments, selection;
331 // Bail if we didn't match the shortcode or all of the content.
332 if ( ! shortcode || shortcode.content !== content )
335 // Ignore the rest of the match object.
336 shortcode = shortcode.shortcode;
338 if ( _.isUndefined( shortcode.get('id') ) && ! _.isUndefined( defaultPostId ) )
339 shortcode.set( 'id', defaultPostId );
341 attachments = wp.media.gallery.attachments( shortcode );
343 selection = new wp.media.model.Selection( attachments.models, {
344 props: attachments.props.toJSON(),
348 selection.gallery = attachments.gallery;
350 // Fetch the query's attachments, and then break ties from the
351 // query to allow for sorting.
352 selection.more().done( function() {
353 // Break ties with the query.
354 selection.props.set({ query: false });
355 selection.unmirror();
356 selection.props.unset('orderby');
359 // Destroy the previous gallery frame.
361 this.frame.dispose();
363 // Store the current gallery frame.
364 this.frame = wp.media({
366 state: 'gallery-edit',
367 title: wp.media.view.l10n.editGalleryTitle,
378 wp.media.featuredImage = {
380 return wp.media.view.settings.post.featuredImageId;
383 set: function( id ) {
384 var settings = wp.media.view.settings;
386 settings.post.featuredImageId = id;
388 wp.media.post( 'set-post-thumbnail', {
390 post_id: settings.post.id,
391 thumbnail_id: settings.post.featuredImageId,
392 _wpnonce: settings.post.nonce
393 }).done( function( html ) {
394 $( '.inside', '#postimagediv' ).html( html );
402 this._frame = wp.media({
403 state: 'featured-image',
404 states: [ new wp.media.controller.FeaturedImage() ]
407 this._frame.on( 'toolbar:create:featured-image', function( toolbar ) {
408 this.createSelectToolbar( toolbar, {
409 text: wp.media.view.l10n.setFeaturedImage
413 this._frame.state('featured-image').on( 'select', this.select );
418 var settings = wp.media.view.settings,
419 selection = this.get('selection').single();
421 if ( ! settings.post.featuredImageId )
424 wp.media.featuredImage.set( selection ? selection.id : -1 );
428 // Open the content media manager to the 'featured image' tab when
429 // the post thumbnail is clicked.
430 $('#postimagediv').on( 'click', '#set-post-thumbnail', function( event ) {
431 event.preventDefault();
432 // Stop propagation to prevent thickbox from activating.
433 event.stopPropagation();
435 wp.media.featuredImage.frame().open();
437 // Update the featured image id when the 'remove' link is clicked.
438 }).on( 'click', '#remove-post-thumbnail', function() {
439 wp.media.view.settings.post.featuredImageId = -1;
444 $( wp.media.featuredImage.init );
447 insert: function( h ) {
448 var mce = typeof(tinymce) != 'undefined',
449 qt = typeof(QTags) != 'undefined',
450 wpActiveEditor = window.wpActiveEditor,
453 // Delegate to the global `send_to_editor` if it exists.
454 // This attempts to play nice with any themes/plugins that have
455 // overridden the insert functionality.
456 if ( window.send_to_editor )
457 return window.send_to_editor.apply( this, arguments );
459 if ( ! wpActiveEditor ) {
460 if ( mce && tinymce.activeEditor ) {
461 ed = tinymce.activeEditor;
462 wpActiveEditor = window.wpActiveEditor = ed.id;
467 if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') )
468 ed = tinymce.activeEditor;
470 ed = tinymce.get(wpActiveEditor);
473 if ( ed && !ed.isHidden() ) {
474 // restore caret position on IE
475 if ( tinymce.isIE && ed.windowManager.insertimagebookmark )
476 ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark);
478 if ( h.indexOf('[caption') !== -1 ) {
479 if ( ed.wpSetImgCaption )
480 h = ed.wpSetImgCaption(h);
481 } else if ( h.indexOf('[gallery') !== -1 ) {
482 if ( ed.plugins.wpgallery )
483 h = ed.plugins.wpgallery._do_gallery(h);
484 } else if ( h.indexOf('[embed') === 0 ) {
485 if ( ed.plugins.wordpress )
486 h = ed.plugins.wordpress._setEmbed(h);
489 ed.execCommand('mceInsertContent', false, h);
491 QTags.insertContent(h);
493 document.getElementById(wpActiveEditor).value += h;
496 // If the old thickbox remove function exists, call it in case
497 // a theme/plugin overloaded it.
498 if ( window.tb_remove )
499 try { window.tb_remove(); } catch( e ) {}
502 add: function( id, options ) {
503 var workflow = this.get( id );
505 if ( workflow ) // only add once: if exists return existing
508 workflow = workflows[ id ] = wp.media( _.defaults( options || {}, {
511 title: wp.media.view.l10n.addMedia,
515 workflow.on( 'insert', function( selection ) {
516 var state = workflow.state();
518 selection = selection || state.get('selection');
523 $.when.apply( $, selection.map( function( attachment ) {
524 var display = state.display( attachment ).toJSON();
525 return this.send.attachment( display, attachment.toJSON() );
526 }, this ) ).done( function() {
527 wp.media.editor.insert( _.toArray( arguments ).join("\n\n") );
531 workflow.state('gallery-edit').on( 'update', function( selection ) {
532 this.insert( wp.media.gallery.shortcode( selection ).string() );
535 workflow.state('embed').on( 'select', function() {
536 var state = workflow.state(),
537 type = state.get('type'),
538 embed = state.props.toJSON();
540 embed.url = embed.url || '';
542 if ( 'link' === type ) {
548 this.send.link( embed ).done( function( resp ) {
549 wp.media.editor.insert( resp );
552 } else if ( 'image' === type ) {
560 if ( 'none' === embed.link )
562 else if ( 'file' === embed.link )
563 embed.linkUrl = embed.url;
565 this.insert( wp.media.string.image( embed ) );
569 workflow.state('featured-image').on( 'select', wp.media.featuredImage.select );
570 workflow.setState( workflow.options.state );
578 // If an empty `id` is provided, default to `wpActiveEditor`.
581 // If that doesn't work, fall back to `tinymce.activeEditor.id`.
582 if ( ! id && typeof tinymce !== 'undefined' && tinymce.activeEditor )
583 id = tinymce.activeEditor.id;
585 // Last but not least, fall back to the empty string.
590 get: function( id ) {
592 return workflows[ id ];
595 remove: function( id ) {
597 delete workflows[ id ];
601 attachment: function( props, attachment ) {
602 var caption = attachment.caption,
605 // If captions are disabled, clear the caption.
606 if ( ! wp.media.view.settings.captions )
607 delete attachment.caption;
609 props = wp.media.string.props( props, attachment );
613 post_content: attachment.description,
614 post_excerpt: caption
618 options.url = props.linkUrl;
620 if ( 'image' === attachment.type ) {
621 html = wp.media.string.image( props );
627 }, function( option, prop ) {
629 options[ option ] = props[ prop ];
631 } else if ( 'video' === attachment.type ) {
632 html = wp.media.string.video( props, attachment );
633 } else if ( 'audio' === attachment.type ) {
634 html = wp.media.string.audio( props, attachment );
636 html = wp.media.string.link( props );
637 options.post_title = props.title;
640 return wp.media.post( 'send-attachment-to-editor', {
641 nonce: wp.media.view.settings.nonce.sendToEditor,
644 post_id: wp.media.view.settings.post.id
648 link: function( embed ) {
649 return wp.media.post( 'send-link-to-editor', {
650 nonce: wp.media.view.settings.nonce.sendToEditor,
653 html: wp.media.string.link( embed ),
654 post_id: wp.media.view.settings.post.id
659 open: function( id, options ) {
660 var workflow, editor;
662 options = options || {};
666 // Save a bookmark of the caret position in IE.
667 if ( typeof tinymce !== 'undefined' ) {
668 editor = tinymce.get( id );
670 if ( tinymce.isIE && editor && ! editor.isHidden() ) {
672 editor.windowManager.insertimagebookmark = editor.selection.getBookmark();
676 workflow = this.get( id );
678 // Redo workflow if state has changed
679 if ( ! workflow || ( workflow.options && options.state !== workflow.options.state ) )
680 workflow = this.add( id, options );
682 return workflow.open();
686 $(document.body).on( 'click', '.insert-media', function( event ) {
688 editor = $this.data('editor'),
692 title: wp.media.view.l10n.addMedia,
696 event.preventDefault();
698 // Remove focus from the `.insert-media` button.
699 // Prevents Opera from showing the outline of the button
702 // See: http://core.trac.wordpress.org/ticket/22445
705 if ( $this.hasClass( 'gallery' ) ) {
706 options.state = 'gallery';
707 options.title = wp.media.view.l10n.createGalleryTitle;
710 wp.media.editor.open( editor, options );
715 _.bindAll( wp.media.editor, 'open' );
716 $( wp.media.editor.init );