wp/wp-includes/js/plupload/handlers.js
changeset 16 a86126ab1dd4
parent 7 cf61fcea0001
child 18 be944660c56a
equal deleted inserted replaced
15:3d4e9c994f10 16:a86126ab1dd4
     1 /* global plupload, pluploadL10n, ajaxurl, post_id, wpUploaderInit, deleteUserSetting, setUserSetting, getUserSetting, shortform */
     1 /* global plupload, pluploadL10n, ajaxurl, post_id, wpUploaderInit, deleteUserSetting, setUserSetting, getUserSetting, shortform */
     2 var topWin = window.dialogArguments || opener || parent || top, uploader, uploader_init;
     2 var topWin = window.dialogArguments || opener || parent || top, uploader, uploader_init;
     3 
     3 
     4 // progress and success handlers for media multi uploads
     4 // Progress and success handlers for media multi uploads.
     5 function fileQueued(fileObj) {
     5 function fileQueued( fileObj ) {
     6 	// Get rid of unused form
     6 	// Get rid of unused form.
     7 	jQuery('.media-blank').remove();
     7 	jQuery( '.media-blank' ).remove();
     8 
     8 
     9 	var items = jQuery('#media-items').children(), postid = post_id || 0;
     9 	var items = jQuery( '#media-items' ).children(), postid = post_id || 0;
    10 
    10 
    11 	// Collapse a single item
    11 	// Collapse a single item.
    12 	if ( items.length == 1 ) {
    12 	if ( items.length == 1 ) {
    13 		items.removeClass('open').find('.slidetoggle').slideUp(200);
    13 		items.removeClass( 'open' ).find( '.slidetoggle' ).slideUp( 200 );
    14 	}
    14 	}
    15 	// Create a progress bar containing the filename
    15 	// Create a progress bar containing the filename.
    16 	jQuery('<div class="media-item">')
    16 	jQuery( '<div class="media-item">' )
    17 		.attr( 'id', 'media-item-' + fileObj.id )
    17 		.attr( 'id', 'media-item-' + fileObj.id )
    18 		.addClass('child-of-' + postid)
    18 		.addClass( 'child-of-' + postid )
    19 		.append('<div class="progress"><div class="percent">0%</div><div class="bar"></div></div>',
    19 		.append( '<div class="progress"><div class="percent">0%</div><div class="bar"></div></div>',
    20 			jQuery('<div class="filename original">').text( ' ' + fileObj.name ))
    20 			jQuery( '<div class="filename original">' ).text( ' ' + fileObj.name ) )
    21 		.appendTo( jQuery('#media-items' ) );
    21 		.appendTo( jQuery( '#media-items' ) );
    22 
    22 
    23 	// Disable submit
    23 	// Disable submit.
    24 	jQuery('#insert-gallery').prop('disabled', true);
    24 	jQuery( '#insert-gallery' ).prop( 'disabled', true );
    25 }
    25 }
    26 
    26 
    27 function uploadStart() {
    27 function uploadStart() {
    28 	try {
    28 	try {
    29 		if ( typeof topWin.tb_remove != 'undefined' )
    29 		if ( typeof topWin.tb_remove != 'undefined' )
    30 			topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
    30 			topWin.jQuery( '#TB_overlay' ).unbind( 'click', topWin.tb_remove );
    31 	} catch(e){}
    31 	} catch( e ){}
    32 
    32 
    33 	return true;
    33 	return true;
    34 }
    34 }
    35 
    35 
    36 function uploadProgress(up, file) {
    36 function uploadProgress( up, file ) {
    37 	var item = jQuery('#media-item-' + file.id);
    37 	var item = jQuery( '#media-item-' + file.id );
    38 
    38 
    39 	jQuery('.bar', item).width( (200 * file.loaded) / file.size );
    39 	jQuery( '.bar', item ).width( ( 200 * file.loaded ) / file.size );
    40 	jQuery('.percent', item).html( file.percent + '%' );
    40 	jQuery( '.percent', item ).html( file.percent + '%' );
    41 }
    41 }
    42 
    42 
    43 // check to see if a large file failed to upload
    43 // Check to see if a large file failed to upload.
    44 function fileUploading( up, file ) {
    44 function fileUploading( up, file ) {
    45 	var hundredmb = 100 * 1024 * 1024,
    45 	var hundredmb = 100 * 1024 * 1024,
    46 		max = parseInt( up.settings.max_file_size, 10 );
    46 		max = parseInt( up.settings.max_file_size, 10 );
    47 
    47 
    48 	if ( max > hundredmb && file.size > hundredmb ) {
    48 	if ( max > hundredmb && file.size > hundredmb ) {
    49 		setTimeout( function() {
    49 		setTimeout( function() {
    50 			if ( file.status < 3 && file.loaded === 0 ) { // not uploading
    50 			if ( file.status < 3 && file.loaded === 0 ) { // Not uploading.
    51 				wpFileError( file, pluploadL10n.big_upload_failed.replace( '%1$s', '<a class="uploader-html" href="#">' ).replace( '%2$s', '</a>' ) );
    51 				wpFileError( file, pluploadL10n.big_upload_failed.replace( '%1$s', '<a class="uploader-html" href="#">' ).replace( '%2$s', '</a>' ) );
    52 				up.stop(); // stops the whole queue
    52 				up.stop();  // Stop the whole queue.
    53 				up.removeFile( file );
    53 				up.removeFile( file );
    54 				up.start(); // restart the queue
    54 				up.start(); // Restart the queue.
    55 			}
    55 			}
    56 		}, 10000 ); // wait for 10 sec. for the file to start uploading
    56 		}, 10000 ); // Wait for 10 seconds for the file to start uploading.
    57 	}
    57 	}
    58 }
    58 }
    59 
    59 
    60 function updateMediaForm() {
    60 function updateMediaForm() {
    61 	var items = jQuery('#media-items').children();
    61 	var items = jQuery( '#media-items' ).children();
    62 
    62 
    63 	// Just one file, no need for collapsible part
    63 	// Just one file, no need for collapsible part.
    64 	if ( items.length == 1 ) {
    64 	if ( items.length == 1 ) {
    65 		items.addClass('open').find('.slidetoggle').show();
    65 		items.addClass( 'open' ).find( '.slidetoggle' ).show();
    66 		jQuery('.insert-gallery').hide();
    66 		jQuery( '.insert-gallery' ).hide();
    67 	} else if ( items.length > 1 ) {
    67 	} else if ( items.length > 1 ) {
    68 		items.removeClass('open');
    68 		items.removeClass( 'open' );
    69 		// Only show Gallery/Playlist buttons when there are at least two files.
    69 		// Only show Gallery/Playlist buttons when there are at least two files.
    70 		jQuery('.insert-gallery').show();
    70 		jQuery( '.insert-gallery' ).show();
    71 	}
    71 	}
    72 
    72 
    73 	// Only show Save buttons when there is at least one file.
    73 	// Only show Save buttons when there is at least one file.
    74 	if ( items.not('.media-blank').length > 0 )
    74 	if ( items.not( '.media-blank' ).length > 0 )
    75 		jQuery('.savebutton').show();
    75 		jQuery( '.savebutton' ).show();
    76 	else
    76 	else
    77 		jQuery('.savebutton').hide();
    77 		jQuery( '.savebutton' ).hide();
    78 }
    78 }
    79 
    79 
    80 function uploadSuccess(fileObj, serverData) {
    80 function uploadSuccess( fileObj, serverData ) {
    81 	var item = jQuery('#media-item-' + fileObj.id);
    81 	var item = jQuery( '#media-item-' + fileObj.id );
    82 
    82 
    83 	// on success serverData should be numeric, fix bug in html4 runtime returning the serverData wrapped in a <pre> tag
    83 	// On success serverData should be numeric,
    84 	serverData = serverData.replace(/^<pre>(\d+)<\/pre>$/, '$1');
    84 	// fix bug in html4 runtime returning the serverData wrapped in a <pre> tag.
    85 
    85 	if ( typeof serverData === 'string' ) {
    86 	// if async-upload returned an error message, place it in the media item div and return
    86 		serverData = serverData.replace( /^<pre>(\d+)<\/pre>$/, '$1' );
    87 	if ( serverData.match(/media-upload-error|error-div/) ) {
    87 
    88 		item.html(serverData);
    88 		// If async-upload returned an error message, place it in the media item div and return.
    89 		return;
    89 		if ( /media-upload-error|error-div/.test( serverData ) ) {
    90 	} else {
    90 			item.html( serverData );
    91 		jQuery('.percent', item).html( pluploadL10n.crunching );
    91 			return;
    92 	}
    92 		}
    93 
    93 	}
    94 	prepareMediaItem(fileObj, serverData);
    94 
       
    95 	item.find( '.percent' ).html( pluploadL10n.crunching );
       
    96 
       
    97 	prepareMediaItem( fileObj, serverData );
    95 	updateMediaForm();
    98 	updateMediaForm();
    96 
    99 
    97 	// Increment the counter.
   100 	// Increment the counter.
    98 	if ( post_id && item.hasClass('child-of-' + post_id) )
   101 	if ( post_id && item.hasClass( 'child-of-' + post_id ) ) {
    99 		jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
   102 		jQuery( '#attachments-count' ).text( 1 * jQuery( '#attachments-count' ).text() + 1 );
       
   103 	}
   100 }
   104 }
   101 
   105 
   102 function setResize( arg ) {
   106 function setResize( arg ) {
   103 	if ( arg ) {
   107 	if ( arg ) {
   104 		if ( window.resize_width && window.resize_height ) {
   108 		if ( window.resize_width && window.resize_height ) {
   114 	} else {
   118 	} else {
   115 		delete( uploader.settings.multipart_params.image_resize );
   119 		delete( uploader.settings.multipart_params.image_resize );
   116 	}
   120 	}
   117 }
   121 }
   118 
   122 
   119 function prepareMediaItem(fileObj, serverData) {
   123 function prepareMediaItem( fileObj, serverData ) {
   120 	var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
   124 	var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery( '#media-item-' + fileObj.id );
   121 	if ( f == 2 && shortform > 2 )
   125 	if ( f == 2 && shortform > 2 )
   122 		f = shortform;
   126 		f = shortform;
   123 
   127 
   124 	try {
   128 	try {
   125 		if ( typeof topWin.tb_remove != 'undefined' )
   129 		if ( typeof topWin.tb_remove != 'undefined' )
   126 			topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
   130 			topWin.jQuery( '#TB_overlay' ).click( topWin.tb_remove );
   127 	} catch(e){}
   131 	} catch( e ){}
   128 
   132 
   129 	if ( isNaN(serverData) || !serverData ) { // Old style: Append the HTML returned by the server -- thumbnail and form inputs
   133 	if ( isNaN( serverData ) || !serverData ) {
   130 		item.append(serverData);
   134 		// Old style: Append the HTML returned by the server -- thumbnail and form inputs.
   131 		prepareMediaItemInit(fileObj);
   135 		item.append( serverData );
   132 	} else { // New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
   136 		prepareMediaItemInit( fileObj );
   133 		item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm();});
   137 	} else {
   134 	}
   138 		// New style: server data is just the attachment ID, fetch the thumbnail and form html from the server.
   135 }
   139 		item.load( 'async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit( fileObj );updateMediaForm();});
   136 
   140 	}
   137 function prepareMediaItemInit(fileObj) {
   141 }
   138 	var item = jQuery('#media-item-' + fileObj.id);
   142 
   139 	// Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename
   143 function prepareMediaItemInit( fileObj ) {
   140 	jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item);
   144 	var item = jQuery( '#media-item-' + fileObj.id );
   141 
   145 	// Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename.
   142 	// Replace the original filename with the new (unique) one assigned during upload
   146 	jQuery( '.thumbnail', item ).clone().attr( 'class', 'pinkynail toggle' ).prependTo( item );
   143 	jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
   147 
   144 
   148 	// Replace the original filename with the new (unique) one assigned during upload.
   145 	// Bind AJAX to the new Delete button
   149 	jQuery( '.filename.original', item ).replaceWith( jQuery( '.filename.new', item ) );
   146 	jQuery('a.delete', item).click(function(){
   150 
   147 		// Tell the server to delete it. TODO: handle exceptions
   151 	// Bind Ajax to the new Delete button.
       
   152 	jQuery( 'a.delete', item ).click( function(){
       
   153 		// Tell the server to delete it. TODO: Handle exceptions.
   148 		jQuery.ajax({
   154 		jQuery.ajax({
   149 			url: ajaxurl,
   155 			url: ajaxurl,
   150 			type: 'post',
   156 			type: 'post',
   151 			success: deleteSuccess,
   157 			success: deleteSuccess,
   152 			error: deleteError,
   158 			error: deleteError,
   153 			id: fileObj.id,
   159 			id: fileObj.id,
   154 			data: {
   160 			data: {
   155 				id : this.id.replace(/[^0-9]/g, ''),
   161 				id : this.id.replace(/[^0-9]/g, '' ),
   156 				action : 'trash-post',
   162 				action : 'trash-post',
   157 				_ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
   163 				_ajax_nonce : this.href.replace(/^.*wpnonce=/,'' )
   158 			}
   164 			}
   159 		});
   165 		});
   160 		return false;
   166 		return false;
   161 	});
   167 	});
   162 
   168 
   163 	// Bind AJAX to the new Undo button
   169 	// Bind Ajax to the new Undo button.
   164 	jQuery('a.undo', item).click(function(){
   170 	jQuery( 'a.undo', item ).click( function(){
   165 		// Tell the server to untrash it. TODO: handle exceptions
   171 		// Tell the server to untrash it. TODO: Handle exceptions.
   166 		jQuery.ajax({
   172 		jQuery.ajax({
   167 			url: ajaxurl,
   173 			url: ajaxurl,
   168 			type: 'post',
   174 			type: 'post',
   169 			id: fileObj.id,
   175 			id: fileObj.id,
   170 			data: {
   176 			data: {
   171 				id : this.id.replace(/[^0-9]/g,''),
   177 				id : this.id.replace(/[^0-9]/g,'' ),
   172 				action: 'untrash-post',
   178 				action: 'untrash-post',
   173 				_ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
   179 				_ajax_nonce: this.href.replace(/^.*wpnonce=/,'' )
   174 			},
   180 			},
   175 			success: function( ){
   181 			success: function( ){
   176 				var type,
   182 				var type,
   177 					item = jQuery('#media-item-' + fileObj.id);
   183 					item = jQuery( '#media-item-' + fileObj.id );
   178 
   184 
   179 				if ( type = jQuery('#type-of-' + fileObj.id).val() )
   185 				if ( type = jQuery( '#type-of-' + fileObj.id ).val() )
   180 					jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1);
   186 					jQuery( '#' + type + '-counter' ).text( jQuery( '#' + type + '-counter' ).text()-0+1 );
   181 
   187 
   182 				if ( post_id && item.hasClass('child-of-'+post_id) )
   188 				if ( post_id && item.hasClass( 'child-of-'+post_id ) )
   183 					jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1);
   189 					jQuery( '#attachments-count' ).text( jQuery( '#attachments-count' ).text()-0+1 );
   184 
   190 
   185 				jQuery('.filename .trashnotice', item).remove();
   191 				jQuery( '.filename .trashnotice', item ).remove();
   186 				jQuery('.filename .title', item).css('font-weight','normal');
   192 				jQuery( '.filename .title', item ).css( 'font-weight','normal' );
   187 				jQuery('a.undo', item).addClass('hidden');
   193 				jQuery( 'a.undo', item ).addClass( 'hidden' );
   188 				jQuery('.menu_order_input', item).show();
   194 				jQuery( '.menu_order_input', item ).show();
   189 				item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo');
   195 				item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery( this ).css({backgroundColor:''}); } }).removeClass( 'undo' );
   190 			}
   196 			}
   191 		});
   197 		});
   192 		return false;
   198 		return false;
   193 	});
   199 	});
   194 
   200 
   195 	// Open this item if it says to start open (e.g. to display an error)
   201 	// Open this item if it says to start open (e.g. to display an error).
   196 	jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').addClass('open').find('slidetoggle').fadeIn();
   202 	jQuery( '#media-item-' + fileObj.id + '.startopen' ).removeClass( 'startopen' ).addClass( 'open' ).find( 'slidetoggle' ).fadeIn();
   197 }
   203 }
   198 
   204 
   199 // generic error message
   205 // Generic error message.
   200 function wpQueueError(message) {
   206 function wpQueueError( message ) {
   201 	jQuery('#media-upload-error').show().html( '<div class="error"><p>' + message + '</p></div>' );
   207 	jQuery( '#media-upload-error' ).show().html( '<div class="error"><p>' + message + '</p></div>' );
   202 }
   208 }
   203 
   209 
   204 // file-specific error messages
   210 // File-specific error messages.
   205 function wpFileError(fileObj, message) {
   211 function wpFileError( fileObj, message ) {
   206 	itemAjaxError(fileObj.id, message);
   212 	itemAjaxError( fileObj.id, message );
   207 }
   213 }
   208 
   214 
   209 function itemAjaxError(id, message) {
   215 function itemAjaxError( id, message ) {
   210 	var item = jQuery('#media-item-' + id), filename = item.find('.filename').text(), last_err = item.data('last-err');
   216 	var item = jQuery( '#media-item-' + id ), filename = item.find( '.filename' ).text(), last_err = item.data( 'last-err' );
   211 
   217 
   212 	if ( last_err == id ) // prevent firing an error for the same file twice
   218 	if ( last_err == id ) // Prevent firing an error for the same file twice.
   213 		return;
   219 		return;
   214 
   220 
   215 	item.html('<div class="error-div">' +
   221 	item.html( '<div class="error-div">' +
   216 				'<a class="dismiss" href="#">' + pluploadL10n.dismiss + '</a>' +
   222 				'<a class="dismiss" href="#">' + pluploadL10n.dismiss + '</a>' +
   217 				'<strong>' + pluploadL10n.error_uploading.replace('%s', jQuery.trim(filename)) + '</strong> ' +
   223 				'<strong>' + pluploadL10n.error_uploading.replace( '%s', jQuery.trim( filename )) + '</strong> ' +
   218 				message +
   224 				message +
   219 				'</div>').data('last-err', id);
   225 				'</div>' ).data( 'last-err', id );
   220 }
   226 }
   221 
   227 
   222 function deleteSuccess(data) {
   228 function deleteSuccess( data ) {
   223 	var type, id, item;
   229 	var type, id, item;
   224 	if ( data == '-1' )
   230 	if ( data == '-1' )
   225 		return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
   231 		return itemAjaxError( this.id, 'You do not have permission. Has your session expired?' );
   226 
   232 
   227 	if ( data == '0' )
   233 	if ( data == '0' )
   228 		return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
   234 		return itemAjaxError( this.id, 'Could not be deleted. Has it been deleted already?' );
   229 
   235 
   230 	id = this.id;
   236 	id = this.id;
   231 	item = jQuery('#media-item-' + id);
   237 	item = jQuery( '#media-item-' + id );
   232 
   238 
   233 	// Decrement the counters.
   239 	// Decrement the counters.
   234 	if ( type = jQuery('#type-of-' + id).val() )
   240 	if ( type = jQuery( '#type-of-' + id ).val() )
   235 		jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 );
   241 		jQuery( '#' + type + '-counter' ).text( jQuery( '#' + type + '-counter' ).text() - 1 );
   236 
   242 
   237 	if ( post_id && item.hasClass('child-of-'+post_id) )
   243 	if ( post_id && item.hasClass( 'child-of-'+post_id ) )
   238 		jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 );
   244 		jQuery( '#attachments-count' ).text( jQuery( '#attachments-count' ).text() - 1 );
   239 
   245 
   240 	if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
   246 	if ( jQuery( 'form.type-form #media-items' ).children().length == 1 && jQuery( '.hidden', '#media-items' ).length > 0 ) {
   241 		jQuery('.toggle').toggle();
   247 		jQuery( '.toggle' ).toggle();
   242 		jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
   248 		jQuery( '.slidetoggle' ).slideUp( 200 ).siblings().removeClass( 'hidden' );
   243 	}
   249 	}
   244 
   250 
   245 	// Vanish it.
   251 	// Vanish it.
   246 	jQuery('.toggle', item).toggle();
   252 	jQuery( '.toggle', item ).toggle();
   247 	jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden');
   253 	jQuery( '.slidetoggle', item ).slideUp( 200 ).siblings().removeClass( 'hidden' );
   248 	item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo');
   254 	item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass( 'undo' );
   249 
   255 
   250 	jQuery('.filename:empty', item).remove();
   256 	jQuery( '.filename:empty', item ).remove();
   251 	jQuery('.filename .title', item).css('font-weight','bold');
   257 	jQuery( '.filename .title', item ).css( 'font-weight','bold' );
   252 	jQuery('.filename', item).append('<span class="trashnotice"> ' + pluploadL10n.deleted + ' </span>').siblings('a.toggle').hide();
   258 	jQuery( '.filename', item ).append( '<span class="trashnotice"> ' + pluploadL10n.deleted + ' </span>' ).siblings( 'a.toggle' ).hide();
   253 	jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') );
   259 	jQuery( '.filename', item ).append( jQuery( 'a.undo', item ).removeClass( 'hidden' ) );
   254 	jQuery('.menu_order_input', item).hide();
   260 	jQuery( '.menu_order_input', item ).hide();
   255 
   261 
   256 	return;
   262 	return;
   257 }
   263 }
   258 
   264 
   259 function deleteError() {
   265 function deleteError() {
   260 	// TODO
       
   261 }
   266 }
   262 
   267 
   263 function uploadComplete() {
   268 function uploadComplete() {
   264 	jQuery('#insert-gallery').prop('disabled', false);
   269 	jQuery( '#insert-gallery' ).prop( 'disabled', false );
   265 }
   270 }
   266 
   271 
   267 function switchUploader(s) {
   272 function switchUploader( s ) {
   268 	if ( s ) {
   273 	if ( s ) {
   269 		deleteUserSetting('uploader');
   274 		deleteUserSetting( 'uploader' );
   270 		jQuery('.media-upload-form').removeClass('html-uploader');
   275 		jQuery( '.media-upload-form' ).removeClass( 'html-uploader' );
   271 
   276 
   272 		if ( typeof(uploader) == 'object' )
   277 		if ( typeof( uploader ) == 'object' )
   273 			uploader.refresh();
   278 			uploader.refresh();
   274 	} else {
   279 	} else {
   275 		setUserSetting('uploader', '1'); // 1 == html uploader
   280 		setUserSetting( 'uploader', '1' ); // 1 == html uploader.
   276 		jQuery('.media-upload-form').addClass('html-uploader');
   281 		jQuery( '.media-upload-form' ).addClass( 'html-uploader' );
   277 	}
   282 	}
   278 }
   283 }
   279 
   284 
   280 function uploadError(fileObj, errorCode, message, uploader) {
   285 function uploadError( fileObj, errorCode, message, up ) {
   281 	var hundredmb = 100 * 1024 * 1024, max;
   286 	var hundredmb = 100 * 1024 * 1024, max;
   282 
   287 
   283 	switch (errorCode) {
   288 	switch ( errorCode ) {
   284 		case plupload.FAILED:
   289 		case plupload.FAILED:
   285 			wpFileError(fileObj, pluploadL10n.upload_failed);
   290 			wpFileError( fileObj, pluploadL10n.upload_failed );
   286 			break;
   291 			break;
   287 		case plupload.FILE_EXTENSION_ERROR:
   292 		case plupload.FILE_EXTENSION_ERROR:
   288 			wpFileExtensionError( uploader, fileObj, pluploadL10n.invalid_filetype );
   293 			wpFileExtensionError( up, fileObj, pluploadL10n.invalid_filetype );
   289 			break;
   294 			break;
   290 		case plupload.FILE_SIZE_ERROR:
   295 		case plupload.FILE_SIZE_ERROR:
   291 			uploadSizeError(uploader, fileObj);
   296 			uploadSizeError( up, fileObj );
   292 			break;
   297 			break;
   293 		case plupload.IMAGE_FORMAT_ERROR:
   298 		case plupload.IMAGE_FORMAT_ERROR:
   294 			wpFileError(fileObj, pluploadL10n.not_an_image);
   299 			wpFileError( fileObj, pluploadL10n.not_an_image );
   295 			break;
   300 			break;
   296 		case plupload.IMAGE_MEMORY_ERROR:
   301 		case plupload.IMAGE_MEMORY_ERROR:
   297 			wpFileError(fileObj, pluploadL10n.image_memory_exceeded);
   302 			wpFileError( fileObj, pluploadL10n.image_memory_exceeded );
   298 			break;
   303 			break;
   299 		case plupload.IMAGE_DIMENSIONS_ERROR:
   304 		case plupload.IMAGE_DIMENSIONS_ERROR:
   300 			wpFileError(fileObj, pluploadL10n.image_dimensions_exceeded);
   305 			wpFileError( fileObj, pluploadL10n.image_dimensions_exceeded );
   301 			break;
   306 			break;
   302 		case plupload.GENERIC_ERROR:
   307 		case plupload.GENERIC_ERROR:
   303 			wpQueueError(pluploadL10n.upload_failed);
   308 			wpQueueError( pluploadL10n.upload_failed );
   304 			break;
   309 			break;
   305 		case plupload.IO_ERROR:
   310 		case plupload.IO_ERROR:
   306 			max = parseInt( uploader.settings.filters.max_file_size, 10 );
   311 			max = parseInt( up.settings.filters.max_file_size, 10 );
   307 
   312 
   308 			if ( max > hundredmb && fileObj.size > hundredmb )
   313 			if ( max > hundredmb && fileObj.size > hundredmb ) {
   309 				wpFileError( fileObj, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>') );
   314 				wpFileError( fileObj, pluploadL10n.big_upload_failed.replace( '%1$s', '<a class="uploader-html" href="#">' ).replace( '%2$s', '</a>' ) );
   310 			else
   315 			} else {
   311 				wpQueueError(pluploadL10n.io_error);
   316 				wpQueueError( pluploadL10n.io_error );
       
   317 			}
       
   318 
   312 			break;
   319 			break;
   313 		case plupload.HTTP_ERROR:
   320 		case plupload.HTTP_ERROR:
   314 			wpQueueError(pluploadL10n.http_error);
   321 			wpQueueError( pluploadL10n.http_error );
   315 			break;
   322 			break;
   316 		case plupload.INIT_ERROR:
   323 		case plupload.INIT_ERROR:
   317 			jQuery('.media-upload-form').addClass('html-uploader');
   324 			jQuery( '.media-upload-form' ).addClass( 'html-uploader' );
   318 			break;
   325 			break;
   319 		case plupload.SECURITY_ERROR:
   326 		case plupload.SECURITY_ERROR:
   320 			wpQueueError(pluploadL10n.security_error);
   327 			wpQueueError( pluploadL10n.security_error );
   321 			break;
   328 			break;
   322 /*		case plupload.UPLOAD_ERROR.UPLOAD_STOPPED:
   329 /*		case plupload.UPLOAD_ERROR.UPLOAD_STOPPED:
   323 		case plupload.UPLOAD_ERROR.FILE_CANCELLED:
   330 		case plupload.UPLOAD_ERROR.FILE_CANCELLED:
   324 			jQuery('#media-item-' + fileObj.id).remove();
   331 			jQuery( '#media-item-' + fileObj.id ).remove();
   325 			break;*/
   332 			break;*/
   326 		default:
   333 		default:
   327 			wpFileError(fileObj, pluploadL10n.default_error);
   334 			wpFileError( fileObj, pluploadL10n.default_error );
   328 	}
   335 	}
   329 }
   336 }
   330 
   337 
   331 function uploadSizeError( up, file ) {
   338 function uploadSizeError( up, file ) {
   332 	var message, errorDiv;
   339 	var message, errorDiv;
   333 
   340 
   334 	message = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
   341 	message = pluploadL10n.file_exceeds_size_limit.replace( '%s', file.name );
   335 
   342 
   336 	// Construct the error div.
   343 	// Construct the error div.
   337 	errorDiv = jQuery( '<div />' )
   344 	errorDiv = jQuery( '<div />' )
   338 		.attr( {
   345 		.attr( {
   339 			'id':    'media-item-' + file.id,
   346 			'id':    'media-item-' + file.id,
   343 			jQuery( '<p />' )
   350 			jQuery( '<p />' )
   344 				.text( message )
   351 				.text( message )
   345 		);
   352 		);
   346 
   353 
   347 	// Append the error.
   354 	// Append the error.
   348 	jQuery('#media-items').append( errorDiv );
   355 	jQuery( '#media-items' ).append( errorDiv );
   349 	up.removeFile(file);
   356 	up.removeFile( file );
   350 }
   357 }
   351 
   358 
   352 function wpFileExtensionError( up, file, message ) {
   359 function wpFileExtensionError( up, file, message ) {
   353 	jQuery('#media-items').append('<div id="media-item-' + file.id + '" class="media-item error"><p>' + message + '</p></div>');
   360 	jQuery( '#media-items' ).append( '<div id="media-item-' + file.id + '" class="media-item error"><p>' + message + '</p></div>' );
   354 	up.removeFile(file);
   361 	up.removeFile( file );
   355 }
   362 }
   356 
   363 
   357 jQuery(document).ready(function($){
   364 jQuery( document ).ready( function( $ ) {
   358 	$('.media-upload-form').bind('click.uploader', function(e) {
   365 	var tryAgainCount = {};
   359 		var target = $(e.target), tr, c;
   366 	var tryAgain;
   360 
   367 
   361 		if ( target.is('input[type="radio"]') ) { // remember the last used image size and alignment
   368 	$( '.media-upload-form' ).bind( 'click.uploader', function( e ) {
   362 			tr = target.closest('tr');
   369 		var target = $( e.target ), tr, c;
   363 
   370 
   364 			if ( tr.hasClass('align') )
   371 		if ( target.is( 'input[type="radio"]' ) ) { // Remember the last used image size and alignment.
   365 				setUserSetting('align', target.val());
   372 			tr = target.closest( 'tr' );
   366 			else if ( tr.hasClass('image-size') )
   373 
   367 				setUserSetting('imgsize', target.val());
   374 			if ( tr.hasClass( 'align' ) )
   368 
   375 				setUserSetting( 'align', target.val() );
   369 		} else if ( target.is('button.button') ) { // remember the last used image link url
   376 			else if ( tr.hasClass( 'image-size' ) )
       
   377 				setUserSetting( 'imgsize', target.val() );
       
   378 
       
   379 		} else if ( target.is( 'button.button' ) ) { // Remember the last used image link url.
   370 			c = e.target.className || '';
   380 			c = e.target.className || '';
   371 			c = c.match(/url([^ '"]+)/);
   381 			c = c.match( /url([^ '"]+)/ );
   372 
   382 
   373 			if ( c && c[1] ) {
   383 			if ( c && c[1] ) {
   374 				setUserSetting('urlbutton', c[1]);
   384 				setUserSetting( 'urlbutton', c[1] );
   375 				target.siblings('.urlfield').val( target.data('link-url') );
   385 				target.siblings( '.urlfield' ).val( target.data( 'link-url' ) );
   376 			}
   386 			}
   377 		} else if ( target.is('a.dismiss') ) {
   387 		} else if ( target.is( 'a.dismiss' ) ) {
   378 			target.parents('.media-item').fadeOut(200, function(){
   388 			target.parents( '.media-item' ).fadeOut( 200, function() {
   379 				$(this).remove();
   389 				$( this ).remove();
   380 			});
   390 			} );
   381 		} else if ( target.is('.upload-flash-bypass a') || target.is('a.uploader-html') ) { // switch uploader to html4
   391 		} else if ( target.is( '.upload-flash-bypass a' ) || target.is( 'a.uploader-html' ) ) { // Switch uploader to html4.
   382 			$('#media-items, p.submit, span.big-file-warning').css('display', 'none');
   392 			$( '#media-items, p.submit, span.big-file-warning' ).css( 'display', 'none' );
   383 			switchUploader(0);
   393 			switchUploader( 0 );
   384 			e.preventDefault();
   394 			e.preventDefault();
   385 		} else if ( target.is('.upload-html-bypass a') ) { // switch uploader to multi-file
   395 		} else if ( target.is( '.upload-html-bypass a' ) ) { // Switch uploader to multi-file.
   386 			$('#media-items, p.submit, span.big-file-warning').css('display', '');
   396 			$( '#media-items, p.submit, span.big-file-warning' ).css( 'display', '' );
   387 			switchUploader(1);
   397 			switchUploader( 1 );
   388 			e.preventDefault();
   398 			e.preventDefault();
   389 		} else if ( target.is('a.describe-toggle-on') ) { // Show
   399 		} else if ( target.is( 'a.describe-toggle-on' ) ) { // Show.
   390 			target.parent().addClass('open');
   400 			target.parent().addClass( 'open' );
   391 			target.siblings('.slidetoggle').fadeIn(250, function(){
   401 			target.siblings( '.slidetoggle' ).fadeIn( 250, function() {
   392 				var S = $(window).scrollTop(), H = $(window).height(), top = $(this).offset().top, h = $(this).height(), b, B;
   402 				var S = $( window ).scrollTop(),
       
   403 					H = $( window ).height(),
       
   404 					top = $( this ).offset().top,
       
   405 					h = $( this ).height(),
       
   406 					b,
       
   407 					B;
   393 
   408 
   394 				if ( H && top && h ) {
   409 				if ( H && top && h ) {
   395 					b = top + h;
   410 					b = top + h;
   396 					B = S + H;
   411 					B = S + H;
   397 
   412 
   398 					if ( b > B ) {
   413 					if ( b > B ) {
   399 						if ( b - B < top - S )
   414 						if ( b - B < top - S )
   400 							window.scrollBy(0, (b - B) + 10);
   415 							window.scrollBy( 0, ( b - B ) + 10 );
   401 						else
   416 						else
   402 							window.scrollBy(0, top - S - 40);
   417 							window.scrollBy( 0, top - S - 40 );
   403 					}
   418 					}
   404 				}
   419 				}
   405 			});
   420 			} );
       
   421 
   406 			e.preventDefault();
   422 			e.preventDefault();
   407 		} else if ( target.is('a.describe-toggle-off') ) { // Hide
   423 		} else if ( target.is( 'a.describe-toggle-off' ) ) { // Hide.
   408 			target.siblings('.slidetoggle').fadeOut(250, function(){
   424 			target.siblings( '.slidetoggle' ).fadeOut( 250, function() {
   409 				target.parent().removeClass('open');
   425 				target.parent().removeClass( 'open' );
   410 			});
   426 			} );
       
   427 
   411 			e.preventDefault();
   428 			e.preventDefault();
   412 		}
   429 		}
   413 	});
   430 	});
   414 
   431 
   415 	// init and set the uploader
   432 	// Attempt to create image sub-sizes when an image was uploaded successfully
       
   433 	// but the server responded with an HTTP 5xx error.
       
   434 	tryAgain = function( up, error ) {
       
   435 		var file = error.file;
       
   436 		var times;
       
   437 		var id;
       
   438 
       
   439 		if ( ! error || ! error.responseHeaders ) {
       
   440 			wpQueueError( pluploadL10n.http_error_image );
       
   441 			return;
       
   442 		}
       
   443 
       
   444 		id = error.responseHeaders.match( /x-wp-upload-attachment-id:\s*(\d+)/i );
       
   445 
       
   446 		if ( id && id[1] ) {
       
   447 			id = id[1];
       
   448 		} else {
       
   449 			wpQueueError( pluploadL10n.http_error_image );
       
   450 			return;
       
   451 		}
       
   452 
       
   453 		times = tryAgainCount[ file.id ];
       
   454 
       
   455 		if ( times && times > 4 ) {
       
   456 			/*
       
   457 			 * The file may have been uploaded and attachment post created,
       
   458 			 * but post-processing and resizing failed...
       
   459 			 * Do a cleanup then tell the user to scale down the image and upload it again.
       
   460 			 */
       
   461 			$.ajax({
       
   462 				type: 'post',
       
   463 				url: ajaxurl,
       
   464 				dataType: 'json',
       
   465 				data: {
       
   466 					action: 'media-create-image-subsizes',
       
   467 					_wpnonce: wpUploaderInit.multipart_params._wpnonce,
       
   468 					attachment_id: id,
       
   469 					_wp_upload_failed_cleanup: true,
       
   470 				}
       
   471 			});
       
   472 
       
   473 			if ( error.message && ( error.status < 500 || error.status >= 600 ) ) {
       
   474 				wpQueueError( error.message );
       
   475 			} else {
       
   476 				wpQueueError( pluploadL10n.http_error_image );
       
   477 			}
       
   478 
       
   479 			return;
       
   480 		}
       
   481 
       
   482 		if ( ! times ) {
       
   483 			tryAgainCount[ file.id ] = 1;
       
   484 		} else {
       
   485 			tryAgainCount[ file.id ] = ++times;
       
   486 		}
       
   487 
       
   488 		// Try to create the missing image sizes.
       
   489 		$.ajax({
       
   490 			type: 'post',
       
   491 			url: ajaxurl,
       
   492 			dataType: 'json',
       
   493 			data: {
       
   494 				action: 'media-create-image-subsizes',
       
   495 				_wpnonce: wpUploaderInit.multipart_params._wpnonce,
       
   496 				attachment_id: id,
       
   497 				_legacy_support: 'true',
       
   498 			}
       
   499 		}).done( function( response ) {
       
   500 			var message;
       
   501 
       
   502 			if ( response.success ) {
       
   503 				uploadSuccess( file, response.data.id );
       
   504 			} else {
       
   505 				if ( response.data && response.data.message ) {
       
   506 					message = response.data.message;
       
   507 				}
       
   508 
       
   509 				wpQueueError( message || pluploadL10n.http_error_image );
       
   510 			}
       
   511 		}).fail( function( jqXHR ) {
       
   512 			// If another HTTP 5xx error, try try again...
       
   513 			if ( jqXHR.status >= 500 && jqXHR.status < 600 ) {
       
   514 				tryAgain( up, error );
       
   515 				return;
       
   516 			}
       
   517 
       
   518 			wpQueueError( pluploadL10n.http_error_image );
       
   519 		});
       
   520 	}
       
   521 
       
   522 	// Init and set the uploader.
   416 	uploader_init = function() {
   523 	uploader_init = function() {
   417 		var isIE = navigator.userAgent.indexOf('Trident/') != -1 || navigator.userAgent.indexOf('MSIE ') != -1;
   524 		uploader = new plupload.Uploader( wpUploaderInit );
   418 
   525 
   419 		// Make sure flash sends cookies (seems in IE it does whitout switching to urlstream mode)
   526 		$( '#image_resize' ).bind( 'change', function() {
   420 		if ( ! isIE && 'flash' === plupload.predictRuntime( wpUploaderInit ) &&
   527 			var arg = $( this ).prop( 'checked' );
   421 			( ! wpUploaderInit.required_features || ! wpUploaderInit.required_features.hasOwnProperty( 'send_binary_string' ) ) ) {
       
   422 
       
   423 			wpUploaderInit.required_features = wpUploaderInit.required_features || {};
       
   424 			wpUploaderInit.required_features.send_binary_string = true;
       
   425 		}
       
   426 
       
   427 		uploader = new plupload.Uploader(wpUploaderInit);
       
   428 
       
   429 		$('#image_resize').bind('change', function() {
       
   430 			var arg = $(this).prop('checked');
       
   431 
   528 
   432 			setResize( arg );
   529 			setResize( arg );
   433 
   530 
   434 			if ( arg )
   531 			if ( arg )
   435 				setUserSetting('upload_resize', '1');
   532 				setUserSetting( 'upload_resize', '1' );
   436 			else
   533 			else
   437 				deleteUserSetting('upload_resize');
   534 				deleteUserSetting( 'upload_resize' );
   438 		});
   535 		});
   439 
   536 
   440 		uploader.bind('Init', function(up) {
   537 		uploader.bind( 'Init', function( up ) {
   441 			var uploaddiv = $('#plupload-upload-ui');
   538 			var uploaddiv = $( '#plupload-upload-ui' );
   442 
   539 
   443 			setResize( getUserSetting('upload_resize', false) );
   540 			setResize( getUserSetting( 'upload_resize', false ) );
   444 
   541 
   445 			if ( up.features.dragdrop && ! $(document.body).hasClass('mobile') ) {
   542 			if ( up.features.dragdrop && ! $( document.body ).hasClass( 'mobile' ) ) {
   446 				uploaddiv.addClass('drag-drop');
   543 				uploaddiv.addClass( 'drag-drop' );
   447 				$('#drag-drop-area').on('dragover.wp-uploader', function(){ // dragenter doesn't fire right :(
   544 
   448 					uploaddiv.addClass('drag-over');
   545 				$( '#drag-drop-area' ).on( 'dragover.wp-uploader', function() { // dragenter doesn't fire right :(
   449 				}).on('dragleave.wp-uploader, drop.wp-uploader', function(){
   546 					uploaddiv.addClass( 'drag-over' );
   450 					uploaddiv.removeClass('drag-over');
   547 				}).on( 'dragleave.wp-uploader, drop.wp-uploader', function() {
       
   548 					uploaddiv.removeClass( 'drag-over' );
   451 				});
   549 				});
   452 			} else {
   550 			} else {
   453 				uploaddiv.removeClass('drag-drop');
   551 				uploaddiv.removeClass( 'drag-drop' );
   454 				$('#drag-drop-area').off('.wp-uploader');
   552 				$( '#drag-drop-area' ).off( '.wp-uploader' );
   455 			}
   553 			}
   456 
   554 
   457 			if ( up.runtime === 'html4' ) {
   555 			if ( up.runtime === 'html4' ) {
   458 				$('.upload-flash-bypass').hide();
   556 				$( '.upload-flash-bypass' ).hide();
   459 			}
   557 			}
   460 		});
   558 		});
   461 
   559 
   462 		uploader.bind( 'postinit', function( up ) {
   560 		uploader.bind( 'postinit', function( up ) {
   463 			up.refresh();
   561 			up.refresh();
   464 		});
   562 		});
   465 
   563 
   466 		uploader.init();
   564 		uploader.init();
   467 
   565 
   468 		uploader.bind('FilesAdded', function( up, files ) {
   566 		uploader.bind( 'FilesAdded', function( up, files ) {
   469 			$('#media-upload-error').empty();
   567 			$( '#media-upload-error' ).empty();
   470 			uploadStart();
   568 			uploadStart();
   471 
   569 
   472 			plupload.each( files, function( file ) {
   570 			plupload.each( files, function( file ) {
       
   571 				if ( file.type === 'image/heic' && up.settings.heic_upload_error ) {
       
   572 					// Show error but do not block uploading.
       
   573 					wpQueueError( pluploadL10n.unsupported_image )
       
   574 				}
       
   575 
   473 				fileQueued( file );
   576 				fileQueued( file );
   474 			});
   577 			});
   475 
   578 
   476 			up.refresh();
   579 			up.refresh();
   477 			up.start();
   580 			up.start();
   478 		});
   581 		});
   479 
   582 
   480 		uploader.bind('UploadFile', function(up, file) {
   583 		uploader.bind( 'UploadFile', function( up, file ) {
   481 			fileUploading(up, file);
   584 			fileUploading( up, file );
   482 		});
   585 		});
   483 
   586 
   484 		uploader.bind('UploadProgress', function(up, file) {
   587 		uploader.bind( 'UploadProgress', function( up, file ) {
   485 			uploadProgress(up, file);
   588 			uploadProgress( up, file );
   486 		});
   589 		});
   487 
   590 
   488 		uploader.bind('Error', function(up, err) {
   591 		uploader.bind( 'Error', function( up, error ) {
   489 			uploadError(err.file, err.code, err.message, up);
   592 			var isImage = error.file && error.file.type && error.file.type.indexOf( 'image/' ) === 0;
       
   593 			var status  = error && error.status;
       
   594 
       
   595 			// If the file is an image and the error is HTTP 5xx try to create sub-sizes again.
       
   596 			if ( isImage && status >= 500 && status < 600 ) {
       
   597 				tryAgain( up, error );
       
   598 				return;
       
   599 			}
       
   600 
       
   601 			uploadError( error.file, error.code, error.message, up );
   490 			up.refresh();
   602 			up.refresh();
   491 		});
   603 		});
   492 
   604 
   493 		uploader.bind('FileUploaded', function(up, file, response) {
   605 		uploader.bind( 'FileUploaded', function( up, file, response ) {
   494 			uploadSuccess(file, response.response);
   606 			uploadSuccess( file, response.response );
   495 		});
   607 		});
   496 
   608 
   497 		uploader.bind('UploadComplete', function() {
   609 		uploader.bind( 'UploadComplete', function() {
   498 			uploadComplete();
   610 			uploadComplete();
   499 		});
   611 		});
   500 	};
   612 	};
   501 
   613 
   502 	if ( typeof(wpUploaderInit) == 'object' ) {
   614 	if ( typeof( wpUploaderInit ) == 'object' ) {
   503 		uploader_init();
   615 		uploader_init();
   504 	}
   616 	}
   505 
   617 
   506 });
   618 });