]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/media-editor.js
Wordpress 3.5.2
[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 )
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
70                         // Format properties for non-images.
71                         } else {
72                                 props.title = props.title || attachment.filename;
73                                 props.rel = props.rel || 'attachment wp-att-' + attachment.id;
74                         }
75
76                         return fallbacks( props );
77                 },
78
79                 link: function( props, attachment ) {
80                         var options;
81
82                         props = wp.media.string.props( props, attachment );
83
84                         options = {
85                                 tag:     'a',
86                                 content: props.title,
87                                 attrs:   {
88                                         href: props.linkUrl
89                                 }
90                         };
91
92                         if ( props.rel )
93                                 options.attrs.rel = props.rel;
94
95                         return wp.html.string( options );
96                 },
97
98                 image: function( props, attachment ) {
99                         var img = {},
100                                 options, classes, shortcode, html;
101
102                         props = wp.media.string.props( props, attachment );
103                         classes = props.classes || [];
104
105                         img.src = props.url;
106                         _.extend( img, _.pick( props, 'width', 'height', 'alt' ) );
107
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 );
112
113                         if ( props.size )
114                                 classes.push( 'size-' + props.size );
115
116                         img['class'] = _.compact( classes ).join(' ');
117
118                         // Generate `img` tag options.
119                         options = {
120                                 tag:    'img',
121                                 attrs:  img,
122                                 single: true
123                         };
124
125                         // Generate the `a` element options, if they exist.
126                         if ( props.linkUrl ) {
127                                 options = {
128                                         tag:   'a',
129                                         attrs: {
130                                                 href: props.linkUrl
131                                         },
132                                         content: options
133                                 };
134                         }
135
136                         html = wp.html.string( options );
137
138                         // Generate the caption shortcode.
139                         if ( props.caption ) {
140                                 shortcode = {};
141
142                                 if ( img.width )
143                                         shortcode.width = img.width;
144
145                                 if ( props.captionId )
146                                         shortcode.id = props.captionId;
147
148                                 if ( props.align )
149                                         shortcode.align = 'align' + props.align;
150
151                                 html = wp.shortcode.string({
152                                         tag:     'caption',
153                                         attrs:   shortcode,
154                                         content: html + ' ' + props.caption
155                                 });
156                         }
157
158                         return html;
159                 }
160         };
161
162         wp.media.gallery = (function() {
163                 var galleries = {};
164
165                 return {
166                         defaults: {
167                                 order:      'ASC',
168                                 id:         wp.media.view.settings.post.id,
169                                 itemtag:    'dl',
170                                 icontag:    'dt',
171                                 captiontag: 'dd',
172                                 columns:    '3',
173                                 link:       'post',
174                                 size:       'thumbnail',
175                                 orderby:    'menu_order ID'
176                         },
177
178                         attachments: function( shortcode ) {
179                                 var shortcodeString = shortcode.string(),
180                                         result = galleries[ shortcodeString ],
181                                         attrs, args, query, others;
182
183                                 delete galleries[ shortcodeString ];
184
185                                 if ( result )
186                                         return result;
187
188                                 // Fill the default shortcode attributes.
189                                 attrs = _.defaults( shortcode.attrs.named, wp.media.gallery.defaults );
190                                 args  = _.pick( attrs, 'orderby', 'order' );
191
192                                 args.type    = 'image';
193                                 args.perPage = -1;
194
195                                 // Mark the `orderby` override attribute.
196                                 if ( 'rand' === attrs.orderby )
197                                         attrs._orderbyRandom = true;
198
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';
202
203                                 // Map the `ids` param to the correct query args.
204                                 if ( attrs.ids ) {
205                                         args.post__in = attrs.ids.split(',');
206                                         args.orderby  = 'post__in';
207                                 } else if ( attrs.include ) {
208                                         args.post__in = attrs.include.split(',');
209                                 }
210
211                                 if ( attrs.exclude )
212                                         args.post__not_in = attrs.exclude.split(',');
213
214                                 if ( ! args.post__in )
215                                         args.uploadedTo = attrs.id;
216
217                                 // Collect the attributes that were not included in `args`.
218                                 others = _.omit( attrs, 'id', 'ids', 'include', 'exclude', 'orderby', 'order' );
219
220                                 query = wp.media.query( args );
221                                 query.gallery = new Backbone.Model( others );
222                                 return query;
223                         },
224
225                         shortcode: function( attachments ) {
226                                 var props = attachments.props.toJSON(),
227                                         attrs = _.pick( props, 'orderby', 'order' ),
228                                         shortcode, clone;
229
230                                 if ( attachments.gallery )
231                                         _.extend( attrs, attachments.gallery.toJSON() );
232
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');
237
238                                 // Copy the `uploadedTo` post ID.
239                                 if ( props.uploadedTo )
240                                         attrs.id = props.uploadedTo;
241
242                                 // Check if the gallery is randomly ordered.
243                                 if ( attrs._orderbyRandom )
244                                         attrs.orderby = 'rand';
245                                 delete attrs._orderbyRandom;
246
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;
251
252                                 // Remove default attributes from the shortcode.
253                                 _.each( wp.media.gallery.defaults, function( value, key ) {
254                                         if ( value === attrs[ key ] )
255                                                 delete attrs[ key ];
256                                 });
257
258                                 shortcode = new wp.shortcode({
259                                         tag:    'gallery',
260                                         attrs:  attrs,
261                                         type:   'single'
262                                 });
263
264                                 // Use a cloned version of the gallery.
265                                 clone = new wp.media.model.Attachments( attachments.models, {
266                                         props: props
267                                 });
268                                 clone.gallery = attachments.gallery;
269                                 galleries[ shortcode.string() ] = clone;
270
271                                 return shortcode;
272                         },
273
274                         edit: function( content ) {
275                                 var shortcode = wp.shortcode.next( 'gallery', content ),
276                                         defaultPostId = wp.media.gallery.defaults.id,
277                                         attachments, selection;
278
279                                 // Bail if we didn't match the shortcode or all of the content.
280                                 if ( ! shortcode || shortcode.content !== content )
281                                         return;
282
283                                 // Ignore the rest of the match object.
284                                 shortcode = shortcode.shortcode;
285
286                                 if ( _.isUndefined( shortcode.get('id') ) && ! _.isUndefined( defaultPostId ) )
287                                         shortcode.set( 'id', defaultPostId );
288
289                                 attachments = wp.media.gallery.attachments( shortcode );
290
291                                 selection = new wp.media.model.Selection( attachments.models, {
292                                         props:    attachments.props.toJSON(),
293                                         multiple: true
294                                 });
295
296                                 selection.gallery = attachments.gallery;
297
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');
305                                 });
306
307                                 // Destroy the previous gallery frame.
308                                 if ( this.frame )
309                                         this.frame.dispose();
310
311                                 // Store the current gallery frame.
312                                 this.frame = wp.media({
313                                         frame:     'post',
314                                         state:     'gallery-edit',
315                                         title:     wp.media.view.l10n.editGalleryTitle,
316                                         editing:   true,
317                                         multiple:  true,
318                                         selection: selection
319                                 }).open();
320
321                                 return this.frame;
322                         }
323                 };
324         }());
325
326         wp.media.featuredImage = {
327                 get: function() {
328                         return wp.media.view.settings.post.featuredImageId;
329                 },
330
331                 set: function( id ) {
332                         var settings = wp.media.view.settings;
333
334                         settings.post.featuredImageId = id;
335
336                         wp.media.post( 'set-post-thumbnail', {
337                                 json:         true,
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 );
343                         });
344                 },
345
346                 frame: function() {
347                         if ( this._frame )
348                                 return this._frame;
349
350                         this._frame = wp.media({
351                                 state: 'featured-image',
352                                 states: [ new wp.media.controller.FeaturedImage() ]
353                         });
354
355                         this._frame.on( 'toolbar:create:featured-image', function( toolbar ) {
356                                 this.createSelectToolbar( toolbar, {
357                                         text: wp.media.view.l10n.setFeaturedImage
358                                 });
359                         }, this._frame );
360
361                         this._frame.state('featured-image').on( 'select', this.select );
362                         return this._frame;
363                 },
364
365                 select: function() {
366                         var settings = wp.media.view.settings,
367                                 selection = this.get('selection').single();
368
369                         if ( ! settings.post.featuredImageId )
370                                 return;
371
372                         wp.media.featuredImage.set( selection ? selection.id : -1 );
373                 },
374
375                 init: function() {
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();
382
383                                 wp.media.featuredImage.frame().open();
384
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;
388                         });
389                 }
390         };
391
392         $( wp.media.featuredImage.init );
393
394         wp.media.editor = {
395                 insert: function( h ) {
396                         var mce = typeof(tinymce) != 'undefined',
397                                 qt = typeof(QTags) != 'undefined',
398                                 wpActiveEditor = window.wpActiveEditor,
399                                 ed;
400
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 );
406
407                         if ( ! wpActiveEditor ) {
408                                 if ( mce && tinymce.activeEditor ) {
409                                         ed = tinymce.activeEditor;
410                                         wpActiveEditor = window.wpActiveEditor = ed.id;
411                                 } else if ( !qt ) {
412                                         return false;
413                                 }
414                         } else if ( mce ) {
415                                 if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') )
416                                         ed = tinymce.activeEditor;
417                                 else
418                                         ed = tinymce.get(wpActiveEditor);
419                         }
420
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);
425
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);
435                                 }
436
437                                 ed.execCommand('mceInsertContent', false, h);
438                         } else if ( qt ) {
439                                 QTags.insertContent(h);
440                         } else {
441                                 document.getElementById(wpActiveEditor).value += h;
442                         }
443
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 ) {}
448                 },
449
450                 add: function( id, options ) {
451                         var workflow = this.get( id );
452
453                         if ( workflow )
454                                 return workflow;
455
456                         workflow = workflows[ id ] = wp.media( _.defaults( options || {}, {
457                                 frame:    'post',
458                                 state:    'insert',
459                                 title:    wp.media.view.l10n.addMedia,
460                                 multiple: true
461                         } ) );
462
463                         workflow.on( 'insert', function( selection ) {
464                                 var state = workflow.state();
465
466                                 selection = selection || state.get('selection');
467
468                                 if ( ! selection )
469                                         return;
470
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") );
476                                 });
477                         }, this );
478
479                         workflow.state('gallery-edit').on( 'update', function( selection ) {
480                                 this.insert( wp.media.gallery.shortcode( selection ).string() );
481                         }, this );
482
483                         workflow.state('embed').on( 'select', function() {
484                                 var state = workflow.state(),
485                                         type = state.get('type'),
486                                         embed = state.props.toJSON();
487
488                                 embed.url = embed.url || '';
489
490                                 if ( 'link' === type ) {
491                                         _.defaults( embed, {
492                                                 title:   embed.url,
493                                                 linkUrl: embed.url
494                                         });
495
496                                         this.send.link( embed ).done( function( resp ) {
497                                                 wp.media.editor.insert( resp );
498                                         });
499
500                                 } else if ( 'image' === type ) {
501                                         _.defaults( embed, {
502                                                 title:   embed.url,
503                                                 linkUrl: '',
504                                                 align:   'none',
505                                                 link:    'none'
506                                         });
507
508                                         if ( 'none' === embed.link )
509                                                 embed.linkUrl = '';
510                                         else if ( 'file' === embed.link )
511                                                 embed.linkUrl = embed.url;
512
513                                         this.insert( wp.media.string.image( embed ) );
514                                 }
515                         }, this );
516
517                         workflow.state('featured-image').on( 'select', wp.media.featuredImage.select );
518                         workflow.setState( workflow.options.state );
519                         return workflow;
520                 },
521
522                 id: function( id ) {
523                         if ( id )
524                                 return id;
525
526                         // If an empty `id` is provided, default to `wpActiveEditor`.
527                         id = wpActiveEditor;
528
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;
532
533                         // Last but not least, fall back to the empty string.
534                         id = id || '';
535                         return id;
536                 },
537
538                 get: function( id ) {
539                         id = this.id( id );
540                         return workflows[ id ];
541                 },
542
543                 remove: function( id ) {
544                         id = this.id( id );
545                         delete workflows[ id ];
546                 },
547
548                 send: {
549                         attachment: function( props, attachment ) {
550                                 var caption = attachment.caption,
551                                         options, html;
552
553                                 // If captions are disabled, clear the caption.
554                                 if ( ! wp.media.view.settings.captions )
555                                         delete attachment.caption;
556
557                                 props = wp.media.string.props( props, attachment );
558
559                                 options = {
560                                         id:           attachment.id,
561                                         post_content: attachment.description,
562                                         post_excerpt: caption
563                                 };
564
565                                 if ( props.linkUrl )
566                                         options.url = props.linkUrl;
567
568                                 if ( 'image' === attachment.type ) {
569                                         html = wp.media.string.image( props );
570
571                                         _.each({
572                                                 align: 'align',
573                                                 size:  'image-size',
574                                                 alt:   'image_alt'
575                                         }, function( option, prop ) {
576                                                 if ( props[ prop ] )
577                                                         options[ option ] = props[ prop ];
578                                         });
579
580                                 } else {
581                                         html = wp.media.string.link( props );
582                                         options.post_title = props.title;
583                                 }
584
585                                 return wp.media.post( 'send-attachment-to-editor', {
586                                         nonce:      wp.media.view.settings.nonce.sendToEditor,
587                                         attachment: options,
588                                         html:       html,
589                                         post_id:    wp.media.view.settings.post.id
590                                 });
591                         },
592
593                         link: function( embed ) {
594                                 return wp.media.post( 'send-link-to-editor', {
595                                         nonce:   wp.media.view.settings.nonce.sendToEditor,
596                                         src:     embed.linkUrl,
597                                         title:   embed.title,
598                                         html:    wp.media.string.link( embed ),
599                                         post_id: wp.media.view.settings.post.id
600                                 });
601                         }
602                 },
603
604                 open: function( id ) {
605                         var workflow, editor;
606
607                         id = this.id( id );
608
609                         // Save a bookmark of the caret position in IE.
610                         if ( typeof tinymce !== 'undefined' ) {
611                                 editor = tinymce.get( id );
612
613                                 if ( tinymce.isIE && editor && ! editor.isHidden() ) {
614                                         editor.focus();
615                                         editor.windowManager.insertimagebookmark = editor.selection.getBookmark();
616                                 }
617                         }
618
619                         workflow = this.get( id );
620
621                         // Initialize the editor's workflow if we haven't yet.
622                         if ( ! workflow )
623                                 workflow = this.add( id );
624
625                         return workflow.open();
626                 },
627
628                 init: function() {
629                         $(document.body).on( 'click', '.insert-media', function( event ) {
630                                 var $this = $(this),
631                                         editor = $this.data('editor');
632
633                                 event.preventDefault();
634
635                                 // Remove focus from the `.insert-media` button.
636                                 // Prevents Opera from showing the outline of the button
637                                 // above the modal.
638                                 //
639                                 // See: http://core.trac.wordpress.org/ticket/22445
640                                 $this.blur();
641
642                                 wp.media.editor.open( editor );
643                         });
644                 }
645         };
646
647         _.bindAll( wp.media.editor, 'open' );
648         $( wp.media.editor.init );
649 }(jQuery));