15eff8da5c97b991923c32c251850ca58f548be8
[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                                 size:       'thumbnail',
174                                 orderby:    'menu_order ID'
175                         },
176
177                         attachments: function( shortcode ) {
178                                 var shortcodeString = shortcode.string(),
179                                         result = galleries[ shortcodeString ],
180                                         attrs, args, query, others;
181
182                                 delete galleries[ shortcodeString ];
183
184                                 if ( result )
185                                         return result;
186
187                                 // Fill the default shortcode attributes.
188                                 attrs = _.defaults( shortcode.attrs.named, wp.media.gallery.defaults );
189                                 args  = _.pick( attrs, 'orderby', 'order' );
190
191                                 args.type    = 'image';
192                                 args.perPage = -1;
193
194                                 // Mark the `orderby` override attribute.
195                                 if ( 'rand' === attrs.orderby )
196                                         attrs._orderbyRandom = true;
197
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';
201
202                                 // Map the `ids` param to the correct query args.
203                                 if ( attrs.ids ) {
204                                         args.post__in = attrs.ids.split(',');
205                                         args.orderby  = 'post__in';
206                                 } else if ( attrs.include ) {
207                                         args.post__in = attrs.include.split(',');
208                                 }
209
210                                 if ( attrs.exclude )
211                                         args.post__not_in = attrs.exclude.split(',');
212
213                                 if ( ! args.post__in )
214                                         args.uploadedTo = attrs.id;
215
216                                 // Collect the attributes that were not included in `args`.
217                                 others = _.omit( attrs, 'id', 'ids', 'include', 'exclude', 'orderby', 'order' );
218
219                                 query = wp.media.query( args );
220                                 query.gallery = new Backbone.Model( others );
221                                 return query;
222                         },
223
224                         shortcode: function( attachments ) {
225                                 var props = attachments.props.toJSON(),
226                                         attrs = _.pick( props, 'orderby', 'order' ),
227                                         shortcode, clone;
228
229                                 if ( attachments.gallery )
230                                         _.extend( attrs, attachments.gallery.toJSON() );
231
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');
236
237                                 // Copy the `uploadedTo` post ID.
238                                 if ( props.uploadedTo )
239                                         attrs.id = props.uploadedTo;
240
241                                 // Check if the gallery is randomly ordered.
242                                 if ( attrs._orderbyRandom )
243                                         attrs.orderby = 'rand';
244                                 delete attrs._orderbyRandom;
245
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;
250
251                                 // Remove default attributes from the shortcode.
252                                 _.each( wp.media.gallery.defaults, function( value, key ) {
253                                         if ( value === attrs[ key ] )
254                                                 delete attrs[ key ];
255                                 });
256
257                                 shortcode = new wp.shortcode({
258                                         tag:    'gallery',
259                                         attrs:  attrs,
260                                         type:   'single'
261                                 });
262
263                                 // Use a cloned version of the gallery.
264                                 clone = new wp.media.model.Attachments( attachments.models, {
265                                         props: props
266                                 });
267                                 clone.gallery = attachments.gallery;
268                                 galleries[ shortcode.string() ] = clone;
269
270                                 return shortcode;
271                         },
272
273                         edit: function( content ) {
274                                 var shortcode = wp.shortcode.next( 'gallery', content ),
275                                         defaultPostId = wp.media.gallery.defaults.id,
276                                         attachments, selection;
277
278                                 // Bail if we didn't match the shortcode or all of the content.
279                                 if ( ! shortcode || shortcode.content !== content )
280                                         return;
281
282                                 // Ignore the rest of the match object.
283                                 shortcode = shortcode.shortcode;
284
285                                 if ( _.isUndefined( shortcode.get('id') ) && ! _.isUndefined( defaultPostId ) )
286                                         shortcode.set( 'id', defaultPostId );
287
288                                 attachments = wp.media.gallery.attachments( shortcode );
289
290                                 selection = new wp.media.model.Selection( attachments.models, {
291                                         props:    attachments.props.toJSON(),
292                                         multiple: true
293                                 });
294
295                                 selection.gallery = attachments.gallery;
296
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');
304                                 });
305
306                                 // Destroy the previous gallery frame.
307                                 if ( this.frame )
308                                         this.frame.dispose();
309
310                                 // Store the current gallery frame.
311                                 this.frame = wp.media({
312                                         frame:     'post',
313                                         state:     'gallery-edit',
314                                         title:     wp.media.view.l10n.editGalleryTitle,
315                                         editing:   true,
316                                         multiple:  true,
317                                         selection: selection
318                                 }).open();
319
320                                 return this.frame;
321                         }
322                 };
323         }());
324
325         wp.media.featuredImage = {
326                 get: function() {
327                         return wp.media.view.settings.post.featuredImageId;
328                 },
329
330                 set: function( id ) {
331                         var settings = wp.media.view.settings;
332
333                         settings.post.featuredImageId = id;
334
335                         wp.media.post( 'set-post-thumbnail', {
336                                 json:         true,
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 );
342                         });
343                 },
344
345                 frame: function() {
346                         if ( this._frame )
347                                 return this._frame;
348
349                         this._frame = wp.media({
350                                 state: 'featured-image',
351                                 states: [ new wp.media.controller.FeaturedImage() ]
352                         });
353
354                         this._frame.on( 'toolbar:create:featured-image', function( toolbar ) {
355                                 this.createSelectToolbar( toolbar, {
356                                         text: wp.media.view.l10n.setFeaturedImage
357                                 });
358                         }, this._frame );
359
360                         this._frame.state('featured-image').on( 'select', this.select );
361                         return this._frame;
362                 },
363
364                 select: function() {
365                         var settings = wp.media.view.settings,
366                                 selection = this.get('selection').single();
367
368                         if ( ! settings.post.featuredImageId )
369                                 return;
370
371                         wp.media.featuredImage.set( selection ? selection.id : -1 );
372                 },
373
374                 init: function() {
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();
381
382                                 wp.media.featuredImage.frame().open();
383
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;
387                         });
388                 }
389         };
390
391         $( wp.media.featuredImage.init );
392
393         wp.media.editor = {
394                 insert: function( h ) {
395                         var mce = typeof(tinymce) != 'undefined',
396                                 qt = typeof(QTags) != 'undefined',
397                                 wpActiveEditor = window.wpActiveEditor,
398                                 ed;
399
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 );
405
406                         if ( ! wpActiveEditor ) {
407                                 if ( mce && tinymce.activeEditor ) {
408                                         ed = tinymce.activeEditor;
409                                         wpActiveEditor = window.wpActiveEditor = ed.id;
410                                 } else if ( !qt ) {
411                                         return false;
412                                 }
413                         } else if ( mce ) {
414                                 if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') )
415                                         ed = tinymce.activeEditor;
416                                 else
417                                         ed = tinymce.get(wpActiveEditor);
418                         }
419
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);
424
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);
434                                 }
435
436                                 ed.execCommand('mceInsertContent', false, h);
437                         } else if ( qt ) {
438                                 QTags.insertContent(h);
439                         } else {
440                                 document.getElementById(wpActiveEditor).value += h;
441                         }
442
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 ) {}
447                 },
448
449                 add: function( id, options ) {
450                         var workflow = this.get( id );
451
452                         if ( workflow )
453                                 return workflow;
454
455                         workflow = workflows[ id ] = wp.media( _.defaults( options || {}, {
456                                 frame:    'post',
457                                 state:    'insert',
458                                 title:    wp.media.view.l10n.addMedia,
459                                 multiple: true
460                         } ) );
461
462                         workflow.on( 'insert', function( selection ) {
463                                 var state = workflow.state();
464
465                                 selection = selection || state.get('selection');
466
467                                 if ( ! selection )
468                                         return;
469
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") );
475                                 });
476                         }, this );
477
478                         workflow.state('gallery-edit').on( 'update', function( selection ) {
479                                 this.insert( wp.media.gallery.shortcode( selection ).string() );
480                         }, this );
481
482                         workflow.state('embed').on( 'select', function() {
483                                 var state = workflow.state(),
484                                         type = state.get('type'),
485                                         embed = state.props.toJSON();
486
487                                 embed.url = embed.url || '';
488
489                                 if ( 'link' === type ) {
490                                         _.defaults( embed, {
491                                                 title:   embed.url,
492                                                 linkUrl: embed.url
493                                         });
494
495                                         this.send.link( embed ).done( function( resp ) {
496                                                 wp.media.editor.insert( resp );
497                                         });
498
499                                 } else if ( 'image' === type ) {
500                                         _.defaults( embed, {
501                                                 title:   embed.url,
502                                                 linkUrl: '',
503                                                 align:   'none',
504                                                 link:    'none'
505                                         });
506
507                                         if ( 'none' === embed.link )
508                                                 embed.linkUrl = '';
509                                         else if ( 'file' === embed.link )
510                                                 embed.linkUrl = embed.url;
511
512                                         this.insert( wp.media.string.image( embed ) );
513                                 }
514                         }, this );
515
516                         workflow.state('featured-image').on( 'select', wp.media.featuredImage.select );
517                         workflow.setState( workflow.options.state );
518                         return workflow;
519                 },
520
521                 id: function( id ) {
522                         if ( id )
523                                 return id;
524
525                         // If an empty `id` is provided, default to `wpActiveEditor`.
526                         id = wpActiveEditor;
527
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;
531
532                         // Last but not least, fall back to the empty string.
533                         id = id || '';
534                         return id;
535                 },
536
537                 get: function( id ) {
538                         id = this.id( id );
539                         return workflows[ id ];
540                 },
541
542                 remove: function( id ) {
543                         id = this.id( id );
544                         delete workflows[ id ];
545                 },
546
547                 send: {
548                         attachment: function( props, attachment ) {
549                                 var caption = attachment.caption,
550                                         options, html;
551
552                                 // If captions are disabled, clear the caption.
553                                 if ( ! wp.media.view.settings.captions )
554                                         delete attachment.caption;
555
556                                 props = wp.media.string.props( props, attachment );
557
558                                 options = {
559                                         id:           attachment.id,
560                                         post_content: attachment.description,
561                                         post_excerpt: caption
562                                 };
563
564                                 if ( props.linkUrl )
565                                         options.url = props.linkUrl;
566
567                                 if ( 'image' === attachment.type ) {
568                                         html = wp.media.string.image( props );
569
570                                         _.each({
571                                                 align: 'align',
572                                                 size:  'image-size',
573                                                 alt:   'image_alt'
574                                         }, function( option, prop ) {
575                                                 if ( props[ prop ] )
576                                                         options[ option ] = props[ prop ];
577                                         });
578
579                                 } else {
580                                         html = wp.media.string.link( props );
581                                         options.post_title = props.title;
582                                 }
583
584                                 return wp.media.post( 'send-attachment-to-editor', {
585                                         nonce:      wp.media.view.settings.nonce.sendToEditor,
586                                         attachment: options,
587                                         html:       html,
588                                         post_id:    wp.media.view.settings.post.id
589                                 });
590                         },
591
592                         link: function( embed ) {
593                                 return wp.media.post( 'send-link-to-editor', {
594                                         nonce:   wp.media.view.settings.nonce.sendToEditor,
595                                         src:     embed.linkUrl,
596                                         title:   embed.title,
597                                         html:    wp.media.string.link( embed ),
598                                         post_id: wp.media.view.settings.post.id
599                                 });
600                         }
601                 },
602
603                 open: function( id ) {
604                         var workflow, editor;
605
606                         id = this.id( id );
607
608                         // Save a bookmark of the caret position in IE.
609                         if ( typeof tinymce !== 'undefined' ) {
610                                 editor = tinymce.get( id );
611
612                                 if ( tinymce.isIE && editor && ! editor.isHidden() ) {
613                                         editor.focus();
614                                         editor.windowManager.insertimagebookmark = editor.selection.getBookmark();
615                                 }
616                         }
617
618                         workflow = this.get( id );
619
620                         // Initialize the editor's workflow if we haven't yet.
621                         if ( ! workflow )
622                                 workflow = this.add( id );
623
624                         return workflow.open();
625                 },
626
627                 init: function() {
628                         $(document.body).on( 'click', '.insert-media', function( event ) {
629                                 var $this = $(this),
630                                         editor = $this.data('editor');
631
632                                 event.preventDefault();
633
634                                 // Remove focus from the `.insert-media` button.
635                                 // Prevents Opera from showing the outline of the button
636                                 // above the modal.
637                                 //
638                                 // See: http://core.trac.wordpress.org/ticket/22445
639                                 $this.blur();
640
641                                 wp.media.editor.open( editor );
642                         });
643                 }
644         };
645
646         _.bindAll( wp.media.editor, 'open' );
647         $( wp.media.editor.init );
648 }(jQuery));