1 /* global pluploadL10n, plupload, _wpPluploadSettings */
3 window.wp = window.wp || {};
5 ( function( exports, $ ) {
8 if ( typeof _wpPluploadSettings === 'undefined' ) {
13 * A WordPress uploader.
15 * The Plupload library provides cross-browser uploader UI integration.
16 * This object bridges the Plupload API to integrate uploads into the
17 * WordPress back end and the WordPress media experience.
19 * @param {object} options The options passed to the new plupload instance.
20 * @param {object} options.container The id of uploader container.
21 * @param {object} options.browser The id of button to trigger the file select.
22 * @param {object} options.dropzone The id of file drop target.
23 * @param {object} options.plupload An object of parameters to pass to the plupload instance.
24 * @param {object} options.params An object of parameters to pass to $_POST when uploading the file.
25 * Extends this.plupload.multipart_params under the hood.
27 Uploader = function( options ) {
29 isIE = navigator.userAgent.indexOf('Trident/') != -1 || navigator.userAgent.indexOf('MSIE ') != -1,
31 container: 'container',
32 browser: 'browse_button',
33 dropzone: 'drop_element'
38 upload: Uploader.browser.supported
41 this.supported = this.supports.upload;
43 if ( ! this.supported ) {
47 // Arguments to send to pluplad.Uploader().
48 // Use deep extend to ensure that multipart_params and other objects are cloned.
49 this.plupload = $.extend( true, { multipart_params: {} }, Uploader.defaults );
50 this.container = document.body; // Set default container.
52 // Extend the instance with options.
54 // Use deep extend to allow options.plupload to override individual
55 // default plupload keys.
56 $.extend( true, this, options );
58 // Proxy all methods so this always refers to the current instance.
60 if ( $.isFunction( this[ key ] ) ) {
61 this[ key ] = $.proxy( this[ key ], this );
65 // Ensure all elements are jQuery elements and have id attributes,
66 // then set the proper plupload arguments to the ids.
67 for ( key in elements ) {
68 if ( ! this[ key ] ) {
72 this[ key ] = $( this[ key ] ).first();
74 if ( ! this[ key ].length ) {
79 if ( ! this[ key ].prop('id') ) {
80 this[ key ].prop( 'id', '__wp-uploader-id-' + Uploader.uuid++ );
83 this.plupload[ elements[ key ] ] = this[ key ].prop('id');
86 // If the uploader has neither a browse button nor a dropzone, bail.
87 if ( ! ( this.browser && this.browser.length ) && ! ( this.dropzone && this.dropzone.length ) ) {
91 // Make sure flash sends cookies (seems in IE it does without switching to urlstream mode)
92 if ( ! isIE && 'flash' === plupload.predictRuntime( this.plupload ) &&
93 ( ! this.plupload.required_features || ! this.plupload.required_features.hasOwnProperty( 'send_binary_string' ) ) ) {
95 this.plupload.required_features = this.plupload.required_features || {};
96 this.plupload.required_features.send_binary_string = true;
99 // Initialize the plupload instance.
100 this.uploader = new plupload.Uploader( this.plupload );
101 delete this.plupload;
103 // Set default params and remove this.params alias.
104 this.param( this.params || {} );
108 * Custom error callback.
110 * Add a new error to the errors collection, so other modules can track
111 * and display errors. @see wp.Uploader.errors.
113 * @param {string} message
114 * @param {object} data
115 * @param {plupload.File} file File that was uploaded.
117 error = function( message, data, file ) {
118 if ( file.attachment ) {
119 file.attachment.destroy();
122 Uploader.errors.unshift({
123 message: message || pluploadL10n.default_error,
128 self.error( message, data, file );
132 * After the Uploader has been initialized, initialize some behaviors for the dropzone.
134 * @param {plupload.Uploader} uploader Uploader instance.
136 this.uploader.bind( 'init', function( uploader ) {
137 var timer, active, dragdrop,
138 dropzone = self.dropzone;
140 dragdrop = self.supports.dragdrop = uploader.features.dragdrop && ! Uploader.browser.mobile;
142 // Generate drag/drop helper classes.
147 dropzone.toggleClass( 'supports-drag-drop', !! dragdrop );
150 return dropzone.unbind('.wp-uploader');
153 // 'dragenter' doesn't fire correctly, simulate it with a limited 'dragover'.
154 dropzone.bind( 'dragover.wp-uploader', function() {
156 clearTimeout( timer );
163 dropzone.trigger('dropzone:enter').addClass('drag-over');
167 dropzone.bind('dragleave.wp-uploader, drop.wp-uploader', function() {
168 // Using an instant timer prevents the drag-over class from
169 // being quickly removed and re-added when elements inside the
170 // dropzone are repositioned.
172 // @see https://core.trac.wordpress.org/ticket/21705
173 timer = setTimeout( function() {
175 dropzone.trigger('dropzone:leave').removeClass('drag-over');
180 $(self).trigger( 'uploader:ready' );
183 this.uploader.bind( 'postinit', function( up ) {
188 this.uploader.init();
190 if ( this.browser ) {
191 this.browser.on( 'mouseenter', this.refresh );
193 this.uploader.disableBrowse( true );
194 // If HTML5 mode, hide the auto-created file container.
195 $('#' + this.uploader.id + '_html5_container').hide();
199 * After files were filtered and added to the queue, create a model for each.
202 * @param {plupload.Uploader} uploader Uploader instance.
203 * @param {Array} files Array of file objects that were added to queue by the user.
205 this.uploader.bind( 'FilesAdded', function( up, files ) {
206 _.each( files, function( file ) {
207 var attributes, image;
209 // Ignore failed uploads.
210 if ( plupload.FAILED === file.status ) {
214 // Generate attributes for a new `Attachment` model.
215 attributes = _.extend({
221 uploadedTo: wp.media.model.settings.post.id
222 }, _.pick( file, 'loaded', 'size', 'percent' ) );
224 // Handle early mime type scanning for images.
225 image = /(?:jpe?g|png|gif)$/i.exec( file.name );
227 // For images set the model's type and subtype attributes.
229 attributes.type = 'image';
231 // `jpeg`, `png` and `gif` are valid subtypes.
232 // `jpg` is not, so map it to `jpeg`.
233 attributes.subtype = ( 'jpg' === image[0] ) ? 'jpeg' : image[0];
236 // Create a model for the attachment, and add it to the Upload queue collection
237 // so listeners to the upload queue can track and display upload progress.
238 file.attachment = wp.media.model.Attachment.create( attributes );
239 Uploader.queue.add( file.attachment );
241 self.added( file.attachment );
248 this.uploader.bind( 'UploadProgress', function( up, file ) {
249 file.attachment.set( _.pick( file, 'loaded', 'percent' ) );
250 self.progress( file.attachment );
254 * After a file is successfully uploaded, update its model.
256 * @param {plupload.Uploader} uploader Uploader instance.
257 * @param {plupload.File} file File that was uploaded.
258 * @param {Object} response Object with response properties.
261 this.uploader.bind( 'FileUploaded', function( up, file, response ) {
265 response = JSON.parse( response.response );
267 return error( pluploadL10n.default_error, e, file );
270 if ( ! _.isObject( response ) || _.isUndefined( response.success ) )
271 return error( pluploadL10n.default_error, null, file );
272 else if ( ! response.success )
273 return error( response.data && response.data.message, response.data, file );
275 _.each(['file','loaded','size','percent'], function( key ) {
276 file.attachment.unset( key );
279 file.attachment.set( _.extend( response.data, { uploading: false }) );
280 wp.media.model.Attachment.get( response.data.id, file.attachment );
282 complete = Uploader.queue.all( function( attachment ) {
283 return ! attachment.get('uploading');
287 Uploader.queue.reset();
289 self.success( file.attachment );
293 * When plupload surfaces an error, send it to the error handler.
295 * @param {plupload.Uploader} uploader Uploader instance.
296 * @param {Object} error Contains code, message and sometimes file and other details.
298 this.uploader.bind( 'Error', function( up, pluploadError ) {
299 var message = pluploadL10n.default_error,
302 // Check for plupload errors.
303 for ( key in Uploader.errorMap ) {
304 if ( pluploadError.code === plupload[ key ] ) {
305 message = Uploader.errorMap[ key ];
307 if ( _.isFunction( message ) ) {
308 message = message( pluploadError.file, pluploadError );
315 error( message, pluploadError, pluploadError.file );
321 // Adds the 'defaults' and 'browser' properties.
322 $.extend( Uploader, _wpPluploadSettings );
326 // Map Plupload error codes to user friendly error messages.
327 Uploader.errorMap = {
328 'FAILED': pluploadL10n.upload_failed,
329 'FILE_EXTENSION_ERROR': pluploadL10n.invalid_filetype,
330 'IMAGE_FORMAT_ERROR': pluploadL10n.not_an_image,
331 'IMAGE_MEMORY_ERROR': pluploadL10n.image_memory_exceeded,
332 'IMAGE_DIMENSIONS_ERROR': pluploadL10n.image_dimensions_exceeded,
333 'GENERIC_ERROR': pluploadL10n.upload_failed,
334 'IO_ERROR': pluploadL10n.io_error,
335 'HTTP_ERROR': pluploadL10n.http_error,
336 'SECURITY_ERROR': pluploadL10n.security_error,
338 'FILE_SIZE_ERROR': function( file ) {
339 return pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
343 $.extend( Uploader.prototype, {
345 * Acts as a shortcut to extending the uploader's multipart_params object.
348 * Returns the value of the key.
350 * param( key, value )
351 * Sets the value of a key.
354 * Sets values for a map of data.
356 param: function( key, value ) {
357 if ( arguments.length === 1 && typeof key === 'string' ) {
358 return this.uploader.settings.multipart_params[ key ];
361 if ( arguments.length > 1 ) {
362 this.uploader.settings.multipart_params[ key ] = value;
364 $.extend( this.uploader.settings.multipart_params, key );
369 * Make a few internal event callbacks available on the wp.Uploader object
370 * to change the Uploader internals if absolutely necessary.
373 error: function() {},
374 success: function() {},
375 added: function() {},
376 progress: function() {},
377 complete: function() {},
378 refresh: function() {
379 var node, attached, container, id;
381 if ( this.browser ) {
382 node = this.browser[0];
384 // Check if the browser node is in the DOM.
386 if ( node === document.body ) {
390 node = node.parentNode;
393 // If the browser node is not attached to the DOM, use a
394 // temporary container to house it, as the browser button
395 // shims require the button to exist in the DOM at all times.
397 id = 'wp-uploader-browser-' + this.uploader.id;
399 container = $( '#' + id );
400 if ( ! container.length ) {
401 container = $('<div class="wp-uploader-browser" />').css({
407 }).attr( 'id', 'wp-uploader-browser-' + this.uploader.id ).appendTo('body');
410 container.append( this.browser );
414 this.uploader.refresh();
418 // Create a collection of attachments in the upload queue,
419 // so that other modules can track and display upload progress.
420 Uploader.queue = new wp.media.model.Attachments( [], { query: false });
422 // Create a collection to collect errors incurred while attempting upload.
423 Uploader.errors = new Backbone.Collection();
425 exports.Uploader = Uploader;