1 /* global pluploadL10n, plupload, _wpPluploadSettings */
3 window.wp = window.wp || {};
5 ( function( exports, $ ) {
8 if ( typeof _wpPluploadSettings === 'undefined' ) {
13 * An object that helps create a WordPress uploader using plupload.
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.
24 * @param attributes - object - Attributes and methods for this specific instance.
26 Uploader = function( options ) {
28 isIE = navigator.userAgent.indexOf('Trident/') != -1 || navigator.userAgent.indexOf('MSIE ') != -1,
30 container: 'container',
31 browser: 'browse_button',
32 dropzone: 'drop_element'
37 upload: Uploader.browser.supported
40 this.supported = this.supports.upload;
42 if ( ! this.supported ) {
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.
50 // Extend the instance with options
52 // Use deep extend to allow options.plupload to override individual
53 // default plupload keys.
54 $.extend( true, this, options );
56 // Proxy all methods so this always refers to the current instance.
58 if ( $.isFunction( this[ key ] ) ) {
59 this[ key ] = $.proxy( this[ key ], this );
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 ] ) {
70 this[ key ] = $( this[ key ] ).first();
72 if ( ! this[ key ].length ) {
77 if ( ! this[ key ].prop('id') ) {
78 this[ key ].prop( 'id', '__wp-uploader-id-' + Uploader.uuid++ );
81 this.plupload[ elements[ key ] ] = this[ key ].prop('id');
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 ) ) {
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' ) ) ) {
93 this.plupload.required_features = this.plupload.required_features || {};
94 this.plupload.required_features.send_binary_string = true;
97 this.uploader = new plupload.Uploader( this.plupload );
100 // Set default params and remove this.params alias.
101 this.param( this.params || {} );
104 error = function( message, data, file ) {
105 if ( file.attachment ) {
106 file.attachment.destroy();
109 Uploader.errors.unshift({
110 message: message || pluploadL10n.default_error,
115 self.error( message, data, file );
118 this.uploader.bind( 'init', function( uploader ) {
119 var timer, active, dragdrop,
120 dropzone = self.dropzone;
122 dragdrop = self.supports.dragdrop = uploader.features.dragdrop && ! Uploader.browser.mobile;
124 // Generate drag/drop helper classes.
129 dropzone.toggleClass( 'supports-drag-drop', !! dragdrop );
132 return dropzone.unbind('.wp-uploader');
135 // 'dragenter' doesn't fire correctly,
136 // simulate it with a limited 'dragover'
137 dropzone.bind( 'dragover.wp-uploader', function() {
139 clearTimeout( timer );
146 dropzone.trigger('dropzone:enter').addClass('drag-over');
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.
155 // See http://core.trac.wordpress.org/ticket/21705
156 timer = setTimeout( function() {
158 dropzone.trigger('dropzone:leave').removeClass('drag-over');
162 $(self).trigger( 'uploader:ready' );
165 this.uploader.init();
167 if ( this.browser ) {
168 this.browser.on( 'mouseenter', this.refresh );
170 this.uploader.disableBrowse( true );
171 // If HTML5 mode, hide the auto-created file container.
172 $('#' + this.uploader.id + '_html5_container').hide();
175 this.uploader.bind( 'FilesAdded', function( up, files ) {
176 _.each( files, function( file ) {
177 var attributes, image;
179 // Ignore failed uploads.
180 if ( plupload.FAILED === file.status ) {
184 // Generate attributes for a new `Attachment` model.
185 attributes = _.extend({
191 uploadedTo: wp.media.model.settings.post.id
192 }, _.pick( file, 'loaded', 'size', 'percent' ) );
194 // Handle early mime type scanning for images.
195 image = /(?:jpe?g|png|gif)$/i.exec( file.name );
197 // Did we find an image?
199 attributes.type = 'image';
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];
206 // Create the `Attachment`.
207 file.attachment = wp.media.model.Attachment.create( attributes );
209 Uploader.queue.add( file.attachment );
211 self.added( file.attachment );
218 this.uploader.bind( 'UploadProgress', function( up, file ) {
219 file.attachment.set( _.pick( file, 'loaded', 'percent' ) );
220 self.progress( file.attachment );
223 this.uploader.bind( 'FileUploaded', function( up, file, response ) {
227 response = JSON.parse( response.response );
229 return error( pluploadL10n.default_error, e, file );
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 );
237 _.each(['file','loaded','size','percent'], function( key ) {
238 file.attachment.unset( key );
241 file.attachment.set( _.extend( response.data, { uploading: false }) );
242 wp.media.model.Attachment.get( response.data.id, file.attachment );
244 complete = Uploader.queue.all( function( attachment ) {
245 return ! attachment.get('uploading');
249 Uploader.queue.reset();
251 self.success( file.attachment );
254 this.uploader.bind( 'Error', function( up, pluploadError ) {
255 var message = pluploadL10n.default_error,
258 // Check for plupload errors.
259 for ( key in Uploader.errorMap ) {
260 if ( pluploadError.code === plupload[ key ] ) {
261 message = Uploader.errorMap[ key ];
263 if ( _.isFunction( message ) ) {
264 message = message( pluploadError.file, pluploadError );
271 error( message, pluploadError, pluploadError.file );
275 this.uploader.bind( 'PostInit', function() {
280 // Adds the 'defaults' and 'browser' properties.
281 $.extend( Uploader, _wpPluploadSettings );
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,
296 'FILE_SIZE_ERROR': function( file ) {
297 return pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
301 $.extend( Uploader.prototype, {
303 * Acts as a shortcut to extending the uploader's multipart_params object.
306 * Returns the value of the key.
308 * param( key, value )
309 * Sets the value of a key.
312 * Sets values for a map of data.
314 param: function( key, value ) {
315 if ( arguments.length === 1 && typeof key === 'string' ) {
316 return this.uploader.settings.multipart_params[ key ];
319 if ( arguments.length > 1 ) {
320 this.uploader.settings.multipart_params[ key ] = value;
322 $.extend( this.uploader.settings.multipart_params, key );
327 error: function() {},
328 success: function() {},
329 added: function() {},
330 progress: function() {},
331 complete: function() {},
332 refresh: function() {
333 var node, attached, container, id;
335 if ( this.browser ) {
336 node = this.browser[0];
338 // Check if the browser node is in the DOM.
340 if ( node === document.body ) {
344 node = node.parentNode;
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.
351 id = 'wp-uploader-browser-' + this.uploader.id;
353 container = $( '#' + id );
354 if ( ! container.length ) {
355 container = $('<div class="wp-uploader-browser" />').css({
361 }).attr( 'id', 'wp-uploader-browser-' + this.uploader.id ).appendTo('body');
364 container.append( this.browser );
368 this.uploader.refresh();
372 Uploader.queue = new wp.media.model.Attachments( [], { query: false });
373 Uploader.errors = new Backbone.Collection();
375 exports.Uploader = Uploader;