]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/plupload/wp-plupload.js
WordPress 3.9-scripts
[autoinstalls/wordpress.git] / wp-includes / js / plupload / wp-plupload.js
1 /* global pluploadL10n, plupload, _wpPluploadSettings */
2
3 window.wp = window.wp || {};
4
5 ( function( exports, $ ) {
6         var Uploader;
7
8         if ( typeof _wpPluploadSettings === 'undefined' ) {
9                 return;
10         }
11
12         /**
13          * An object that helps create a WordPress uploader using plupload.
14          *
15          * @param options - object - The options passed to the new plupload instance.
16          *    Accepts the following parameters:
17          *    - container - The id of uploader container.
18          *    - browser   - The id of button to trigger the file select.
19          *    - dropzone  - The id of file drop target.
20          *    - plupload  - An object of parameters to pass to the plupload instance.
21          *    - params    - An object of parameters to pass to $_POST when uploading the file.
22          *                  Extends this.plupload.multipart_params under the hood.
23          *
24          * @param attributes - object - Attributes and methods for this specific instance.
25          */
26         Uploader = function( options ) {
27                 var self = this,
28                         isIE = navigator.userAgent.indexOf('Trident/') != -1 || navigator.userAgent.indexOf('MSIE ') != -1,
29                         elements = {
30                                 container: 'container',
31                                 browser:   'browse_button',
32                                 dropzone:  'drop_element'
33                         },
34                         key, error;
35
36                 this.supports = {
37                         upload: Uploader.browser.supported
38                 };
39
40                 this.supported = this.supports.upload;
41
42                 if ( ! this.supported ) {
43                         return;
44                 }
45
46                 // Use deep extend to ensure that multipart_params and other objects are cloned.
47                 this.plupload = $.extend( true, { multipart_params: {} }, Uploader.defaults );
48                 this.container = document.body; // Set default container.
49
50                 // Extend the instance with options
51                 //
52                 // Use deep extend to allow options.plupload to override individual
53                 // default plupload keys.
54                 $.extend( true, this, options );
55
56                 // Proxy all methods so this always refers to the current instance.
57                 for ( key in this ) {
58                         if ( $.isFunction( this[ key ] ) ) {
59                                 this[ key ] = $.proxy( this[ key ], this );
60                         }
61                 }
62
63                 // Ensure all elements are jQuery elements and have id attributes
64                 // Then set the proper plupload arguments to the ids.
65                 for ( key in elements ) {
66                         if ( ! this[ key ] ) {
67                                 continue;
68                         }
69
70                         this[ key ] = $( this[ key ] ).first();
71
72                         if ( ! this[ key ].length ) {
73                                 delete this[ key ];
74                                 continue;
75                         }
76
77                         if ( ! this[ key ].prop('id') ) {
78                                 this[ key ].prop( 'id', '__wp-uploader-id-' + Uploader.uuid++ );
79                         }
80
81                         this.plupload[ elements[ key ] ] = this[ key ].prop('id');
82                 }
83
84                 // If the uploader has neither a browse button nor a dropzone, bail.
85                 if ( ! ( this.browser && this.browser.length ) && ! ( this.dropzone && this.dropzone.length ) ) {
86                         return;
87                 }
88
89                 // Make sure flash sends cookies (seems in IE it does without switching to urlstream mode)
90                 if ( ! isIE && 'flash' === plupload.predictRuntime( this.plupload ) &&
91                         ( ! this.plupload.required_features || ! this.plupload.required_features.hasOwnProperty( 'send_binary_string' ) ) ) {
92
93                         this.plupload.required_features = this.plupload.required_features || {};
94                         this.plupload.required_features.send_binary_string = true;
95                 }
96
97                 this.uploader = new plupload.Uploader( this.plupload );
98                 delete this.plupload;
99
100                 // Set default params and remove this.params alias.
101                 this.param( this.params || {} );
102                 delete this.params;
103
104                 error = function( message, data, file ) {
105                         if ( file.attachment ) {
106                                 file.attachment.destroy();
107                         }
108
109                         Uploader.errors.unshift({
110                                 message: message || pluploadL10n.default_error,
111                                 data:    data,
112                                 file:    file
113                         });
114
115                         self.error( message, data, file );
116                 };
117
118                 this.uploader.bind( 'init', function( uploader ) {
119                         var timer, active, dragdrop,
120                                 dropzone = self.dropzone;
121
122                         dragdrop = self.supports.dragdrop = uploader.features.dragdrop && ! Uploader.browser.mobile;
123
124                         // Generate drag/drop helper classes.
125                         if ( ! dropzone ) {
126                                 return;
127                         }
128
129                         dropzone.toggleClass( 'supports-drag-drop', !! dragdrop );
130
131                         if ( ! dragdrop ) {
132                                 return dropzone.unbind('.wp-uploader');
133                         }
134
135                         // 'dragenter' doesn't fire correctly,
136                         // simulate it with a limited 'dragover'
137                         dropzone.bind( 'dragover.wp-uploader', function() {
138                                 if ( timer ) {
139                                         clearTimeout( timer );
140                                 }
141
142                                 if ( active ) {
143                                         return;
144                                 }
145
146                                 dropzone.trigger('dropzone:enter').addClass('drag-over');
147                                 active = true;
148                         });
149
150                         dropzone.bind('dragleave.wp-uploader, drop.wp-uploader', function() {
151                                 // Using an instant timer prevents the drag-over class from
152                                 // being quickly removed and re-added when elements inside the
153                                 // dropzone are repositioned.
154                                 //
155                                 // See http://core.trac.wordpress.org/ticket/21705
156                                 timer = setTimeout( function() {
157                                         active = false;
158                                         dropzone.trigger('dropzone:leave').removeClass('drag-over');
159                                 }, 0 );
160                         });
161
162                         $(self).trigger( 'uploader:ready' );
163                 });
164
165                 this.uploader.init();
166
167                 if ( this.browser ) {
168                         this.browser.on( 'mouseenter', this.refresh );
169                 } else {
170                         this.uploader.disableBrowse( true );
171                         // If HTML5 mode, hide the auto-created file container.
172                         $('#' + this.uploader.id + '_html5_container').hide();
173                 }
174
175                 this.uploader.bind( 'FilesAdded', function( up, files ) {
176                         _.each( files, function( file ) {
177                                 var attributes, image;
178
179                                 // Ignore failed uploads.
180                                 if ( plupload.FAILED === file.status ) {
181                                         return;
182                                 }
183
184                                 // Generate attributes for a new `Attachment` model.
185                                 attributes = _.extend({
186                                         file:      file,
187                                         uploading: true,
188                                         date:      new Date(),
189                                         filename:  file.name,
190                                         menuOrder: 0,
191                                         uploadedTo: wp.media.model.settings.post.id
192                                 }, _.pick( file, 'loaded', 'size', 'percent' ) );
193
194                                 // Handle early mime type scanning for images.
195                                 image = /(?:jpe?g|png|gif)$/i.exec( file.name );
196
197                                 // Did we find an image?
198                                 if ( image ) {
199                                         attributes.type = 'image';
200
201                                         // `jpeg`, `png` and `gif` are valid subtypes.
202                                         // `jpg` is not, so map it to `jpeg`.
203                                         attributes.subtype = ( 'jpg' === image[0] ) ? 'jpeg' : image[0];
204                                 }
205
206                                 // Create the `Attachment`.
207                                 file.attachment = wp.media.model.Attachment.create( attributes );
208
209                                 Uploader.queue.add( file.attachment );
210
211                                 self.added( file.attachment );
212                         });
213
214                         up.refresh();
215                         up.start();
216                 });
217
218                 this.uploader.bind( 'UploadProgress', function( up, file ) {
219                         file.attachment.set( _.pick( file, 'loaded', 'percent' ) );
220                         self.progress( file.attachment );
221                 });
222
223                 this.uploader.bind( 'FileUploaded', function( up, file, response ) {
224                         var complete;
225
226                         try {
227                                 response = JSON.parse( response.response );
228                         } catch ( e ) {
229                                 return error( pluploadL10n.default_error, e, file );
230                         }
231
232                         if ( ! _.isObject( response ) || _.isUndefined( response.success ) )
233                                 return error( pluploadL10n.default_error, null, file );
234                         else if ( ! response.success )
235                                 return error( response.data && response.data.message, response.data, file );
236
237                         _.each(['file','loaded','size','percent'], function( key ) {
238                                 file.attachment.unset( key );
239                         });
240
241                         file.attachment.set( _.extend( response.data, { uploading: false }) );
242                         wp.media.model.Attachment.get( response.data.id, file.attachment );
243
244                         complete = Uploader.queue.all( function( attachment ) {
245                                 return ! attachment.get('uploading');
246                         });
247
248                         if ( complete )
249                                 Uploader.queue.reset();
250
251                         self.success( file.attachment );
252                 });
253
254                 this.uploader.bind( 'Error', function( up, pluploadError ) {
255                         var message = pluploadL10n.default_error,
256                                 key;
257
258                         // Check for plupload errors.
259                         for ( key in Uploader.errorMap ) {
260                                 if ( pluploadError.code === plupload[ key ] ) {
261                                         message = Uploader.errorMap[ key ];
262
263                                         if ( _.isFunction( message ) ) {
264                                                 message = message( pluploadError.file, pluploadError );
265                                         }
266
267                                         break;
268                                 }
269                         }
270
271                         error( message, pluploadError, pluploadError.file );
272                         up.refresh();
273                 });
274
275                 this.uploader.bind( 'PostInit', function() {
276                         self.init();
277                 });
278         };
279
280         // Adds the 'defaults' and 'browser' properties.
281         $.extend( Uploader, _wpPluploadSettings );
282
283         Uploader.uuid = 0;
284
285         Uploader.errorMap = {
286                 'FAILED':                 pluploadL10n.upload_failed,
287                 'FILE_EXTENSION_ERROR':   pluploadL10n.invalid_filetype,
288                 'IMAGE_FORMAT_ERROR':     pluploadL10n.not_an_image,
289                 'IMAGE_MEMORY_ERROR':     pluploadL10n.image_memory_exceeded,
290                 'IMAGE_DIMENSIONS_ERROR': pluploadL10n.image_dimensions_exceeded,
291                 'GENERIC_ERROR':          pluploadL10n.upload_failed,
292                 'IO_ERROR':               pluploadL10n.io_error,
293                 'HTTP_ERROR':             pluploadL10n.http_error,
294                 'SECURITY_ERROR':         pluploadL10n.security_error,
295
296                 'FILE_SIZE_ERROR': function( file ) {
297                         return pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
298                 }
299         };
300
301         $.extend( Uploader.prototype, {
302                 /**
303                  * Acts as a shortcut to extending the uploader's multipart_params object.
304                  *
305                  * param( key )
306                  *    Returns the value of the key.
307                  *
308                  * param( key, value )
309                  *    Sets the value of a key.
310                  *
311                  * param( map )
312                  *    Sets values for a map of data.
313                  */
314                 param: function( key, value ) {
315                         if ( arguments.length === 1 && typeof key === 'string' ) {
316                                 return this.uploader.settings.multipart_params[ key ];
317                         }
318
319                         if ( arguments.length > 1 ) {
320                                 this.uploader.settings.multipart_params[ key ] = value;
321                         } else {
322                                 $.extend( this.uploader.settings.multipart_params, key );
323                         }
324                 },
325
326                 init:     function() {},
327                 error:    function() {},
328                 success:  function() {},
329                 added:    function() {},
330                 progress: function() {},
331                 complete: function() {},
332                 refresh:  function() {
333                         var node, attached, container, id;
334
335                         if ( this.browser ) {
336                                 node = this.browser[0];
337
338                                 // Check if the browser node is in the DOM.
339                                 while ( node ) {
340                                         if ( node === document.body ) {
341                                                 attached = true;
342                                                 break;
343                                         }
344                                         node = node.parentNode;
345                                 }
346
347                                 // If the browser node is not attached to the DOM, use a
348                                 // temporary container to house it, as the browser button
349                                 // shims require the button to exist in the DOM at all times.
350                                 if ( ! attached ) {
351                                         id = 'wp-uploader-browser-' + this.uploader.id;
352
353                                         container = $( '#' + id );
354                                         if ( ! container.length ) {
355                                                 container = $('<div class="wp-uploader-browser" />').css({
356                                                         position: 'fixed',
357                                                         top: '-1000px',
358                                                         left: '-1000px',
359                                                         height: 0,
360                                                         width: 0
361                                                 }).attr( 'id', 'wp-uploader-browser-' + this.uploader.id ).appendTo('body');
362                                         }
363
364                                         container.append( this.browser );
365                                 }
366                         }
367
368                         this.uploader.refresh();
369                 }
370         });
371
372         Uploader.queue = new wp.media.model.Attachments( [], { query: false });
373         Uploader.errors = new Backbone.Collection();
374
375         exports.Uploader = Uploader;
376 })( wp, jQuery );