]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/plupload/handlers.js
WordPress 4.4
[autoinstalls/wordpress.git] / wp-includes / js / plupload / handlers.js
1 /* global plupload, pluploadL10n, ajaxurl, post_id, wpUploaderInit, deleteUserSetting, setUserSetting, getUserSetting, shortform */
2 var topWin = window.dialogArguments || opener || parent || top, uploader, uploader_init;
3
4 // progress and success handlers for media multi uploads
5 function fileQueued(fileObj) {
6         // Get rid of unused form
7         jQuery('.media-blank').remove();
8
9         var items = jQuery('#media-items').children(), postid = post_id || 0;
10
11         // Collapse a single item
12         if ( items.length == 1 ) {
13                 items.removeClass('open').find('.slidetoggle').slideUp(200);
14         }
15         // Create a progress bar containing the filename
16         jQuery('<div class="media-item">')
17                 .attr( 'id', 'media-item-' + fileObj.id )
18                 .addClass('child-of-' + postid)
19                 .append('<div class="progress"><div class="percent">0%</div><div class="bar"></div></div>',
20                         jQuery('<div class="filename original">').text( ' ' + fileObj.name ))
21                 .appendTo( jQuery('#media-items' ) );
22
23         // Disable submit
24         jQuery('#insert-gallery').prop('disabled', true);
25 }
26
27 function uploadStart() {
28         try {
29                 if ( typeof topWin.tb_remove != 'undefined' )
30                         topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
31         } catch(e){}
32
33         return true;
34 }
35
36 function uploadProgress(up, file) {
37         var item = jQuery('#media-item-' + file.id);
38
39         jQuery('.bar', item).width( (200 * file.loaded) / file.size );
40         jQuery('.percent', item).html( file.percent + '%' );
41 }
42
43 // check to see if a large file failed to upload
44 function fileUploading( up, file ) {
45         var hundredmb = 100 * 1024 * 1024,
46                 max = parseInt( up.settings.max_file_size, 10 );
47
48         if ( max > hundredmb && file.size > hundredmb ) {
49                 setTimeout( function() {
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>' ) );
52                                 up.stop(); // stops the whole queue
53                                 up.removeFile( file );
54                                 up.start(); // restart the queue
55                         }
56                 }, 10000 ); // wait for 10 sec. for the file to start uploading
57         }
58 }
59
60 function updateMediaForm() {
61         var items = jQuery('#media-items').children();
62
63         // Just one file, no need for collapsible part
64         if ( items.length == 1 ) {
65                 items.addClass('open').find('.slidetoggle').show();
66                 jQuery('.insert-gallery').hide();
67         } else if ( items.length > 1 ) {
68                 items.removeClass('open');
69                 // Only show Gallery/Playlist buttons when there are at least two files.
70                 jQuery('.insert-gallery').show();
71         }
72
73         // Only show Save buttons when there is at least one file.
74         if ( items.not('.media-blank').length > 0 )
75                 jQuery('.savebutton').show();
76         else
77                 jQuery('.savebutton').hide();
78 }
79
80 function uploadSuccess(fileObj, serverData) {
81         var item = jQuery('#media-item-' + fileObj.id);
82
83         // on success serverData should be numeric, fix bug in html4 runtime returning the serverData wrapped in a <pre> tag
84         serverData = serverData.replace(/^<pre>(\d+)<\/pre>$/, '$1');
85
86         // if async-upload returned an error message, place it in the media item div and return
87         if ( serverData.match(/media-upload-error|error-div/) ) {
88                 item.html(serverData);
89                 return;
90         } else {
91                 jQuery('.percent', item).html( pluploadL10n.crunching );
92         }
93
94         prepareMediaItem(fileObj, serverData);
95         updateMediaForm();
96
97         // Increment the counter.
98         if ( post_id && item.hasClass('child-of-' + post_id) )
99                 jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
100 }
101
102 function setResize( arg ) {
103         if ( arg ) {
104                 if ( window.resize_width && window.resize_height ) {
105                         uploader.settings.resize = {
106                                 enabled: true,
107                                 width: window.resize_width,
108                                 height: window.resize_height,
109                                 quality: 100
110                         };
111                 } else {
112                         uploader.settings.multipart_params.image_resize = true;
113                 }
114         } else {
115                 delete( uploader.settings.multipart_params.image_resize );
116         }
117 }
118
119 function prepareMediaItem(fileObj, serverData) {
120         var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
121         if ( f == 2 && shortform > 2 )
122                 f = shortform;
123
124         try {
125                 if ( typeof topWin.tb_remove != 'undefined' )
126                         topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
127         } catch(e){}
128
129         if ( isNaN(serverData) || !serverData ) { // Old style: Append the HTML returned by the server -- thumbnail and form inputs
130                 item.append(serverData);
131                 prepareMediaItemInit(fileObj);
132         } else { // New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
133                 item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm();});
134         }
135 }
136
137 function prepareMediaItemInit(fileObj) {
138         var item = jQuery('#media-item-' + fileObj.id);
139         // Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename
140         jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item);
141
142         // Replace the original filename with the new (unique) one assigned during upload
143         jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
144
145         // Bind AJAX to the new Delete button
146         jQuery('a.delete', item).click(function(){
147                 // Tell the server to delete it. TODO: handle exceptions
148                 jQuery.ajax({
149                         url: ajaxurl,
150                         type: 'post',
151                         success: deleteSuccess,
152                         error: deleteError,
153                         id: fileObj.id,
154                         data: {
155                                 id : this.id.replace(/[^0-9]/g, ''),
156                                 action : 'trash-post',
157                                 _ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
158                         }
159                 });
160                 return false;
161         });
162
163         // Bind AJAX to the new Undo button
164         jQuery('a.undo', item).click(function(){
165                 // Tell the server to untrash it. TODO: handle exceptions
166                 jQuery.ajax({
167                         url: ajaxurl,
168                         type: 'post',
169                         id: fileObj.id,
170                         data: {
171                                 id : this.id.replace(/[^0-9]/g,''),
172                                 action: 'untrash-post',
173                                 _ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
174                         },
175                         success: function( ){
176                                 var type,
177                                         item = jQuery('#media-item-' + fileObj.id);
178
179                                 if ( type = jQuery('#type-of-' + fileObj.id).val() )
180                                         jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1);
181
182                                 if ( post_id && item.hasClass('child-of-'+post_id) )
183                                         jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1);
184
185                                 jQuery('.filename .trashnotice', item).remove();
186                                 jQuery('.filename .title', item).css('font-weight','normal');
187                                 jQuery('a.undo', item).addClass('hidden');
188                                 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');
190                         }
191                 });
192                 return false;
193         });
194
195         // 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();
197 }
198
199 // generic error message
200 function wpQueueError(message) {
201         jQuery('#media-upload-error').show().html( '<div class="error"><p>' + message + '</p></div>' );
202 }
203
204 // file-specific error messages
205 function wpFileError(fileObj, message) {
206         itemAjaxError(fileObj.id, message);
207 }
208
209 function itemAjaxError(id, message) {
210         var item = jQuery('#media-item-' + id), filename = item.find('.filename').text(), last_err = item.data('last-err');
211
212         if ( last_err == id ) // prevent firing an error for the same file twice
213                 return;
214
215         item.html('<div class="error-div">' +
216                                 '<a class="dismiss" href="#">' + pluploadL10n.dismiss + '</a>' +
217                                 '<strong>' + pluploadL10n.error_uploading.replace('%s', jQuery.trim(filename)) + '</strong> ' +
218                                 message +
219                                 '</div>').data('last-err', id);
220 }
221
222 function deleteSuccess(data) {
223         var type, id, item;
224         if ( data == '-1' )
225                 return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
226
227         if ( data == '0' )
228                 return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
229
230         id = this.id;
231         item = jQuery('#media-item-' + id);
232
233         // Decrement the counters.
234         if ( type = jQuery('#type-of-' + id).val() )
235                 jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 );
236
237         if ( post_id && item.hasClass('child-of-'+post_id) )
238                 jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 );
239
240         if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
241                 jQuery('.toggle').toggle();
242                 jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
243         }
244
245         // Vanish it.
246         jQuery('.toggle', item).toggle();
247         jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden');
248         item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo');
249
250         jQuery('.filename:empty', item).remove();
251         jQuery('.filename .title', item).css('font-weight','bold');
252         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') );
254         jQuery('.menu_order_input', item).hide();
255
256         return;
257 }
258
259 function deleteError() {
260         // TODO
261 }
262
263 function uploadComplete() {
264         jQuery('#insert-gallery').prop('disabled', false);
265 }
266
267 function switchUploader(s) {
268         if ( s ) {
269                 deleteUserSetting('uploader');
270                 jQuery('.media-upload-form').removeClass('html-uploader');
271
272                 if ( typeof(uploader) == 'object' )
273                         uploader.refresh();
274         } else {
275                 setUserSetting('uploader', '1'); // 1 == html uploader
276                 jQuery('.media-upload-form').addClass('html-uploader');
277         }
278 }
279
280 function uploadError(fileObj, errorCode, message, uploader) {
281         var hundredmb = 100 * 1024 * 1024, max;
282
283         switch (errorCode) {
284                 case plupload.FAILED:
285                         wpFileError(fileObj, pluploadL10n.upload_failed);
286                         break;
287                 case plupload.FILE_EXTENSION_ERROR:
288                         wpFileError(fileObj, pluploadL10n.invalid_filetype);
289                         break;
290                 case plupload.FILE_SIZE_ERROR:
291                         uploadSizeError(uploader, fileObj);
292                         break;
293                 case plupload.IMAGE_FORMAT_ERROR:
294                         wpFileError(fileObj, pluploadL10n.not_an_image);
295                         break;
296                 case plupload.IMAGE_MEMORY_ERROR:
297                         wpFileError(fileObj, pluploadL10n.image_memory_exceeded);
298                         break;
299                 case plupload.IMAGE_DIMENSIONS_ERROR:
300                         wpFileError(fileObj, pluploadL10n.image_dimensions_exceeded);
301                         break;
302                 case plupload.GENERIC_ERROR:
303                         wpQueueError(pluploadL10n.upload_failed);
304                         break;
305                 case plupload.IO_ERROR:
306                         max = parseInt( uploader.settings.filters.max_file_size, 10 );
307
308                         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>') );
310                         else
311                                 wpQueueError(pluploadL10n.io_error);
312                         break;
313                 case plupload.HTTP_ERROR:
314                         wpQueueError(pluploadL10n.http_error);
315                         break;
316                 case plupload.INIT_ERROR:
317                         jQuery('.media-upload-form').addClass('html-uploader');
318                         break;
319                 case plupload.SECURITY_ERROR:
320                         wpQueueError(pluploadL10n.security_error);
321                         break;
322 /*              case plupload.UPLOAD_ERROR.UPLOAD_STOPPED:
323                 case plupload.UPLOAD_ERROR.FILE_CANCELLED:
324                         jQuery('#media-item-' + fileObj.id).remove();
325                         break;*/
326                 default:
327                         wpFileError(fileObj, pluploadL10n.default_error);
328         }
329 }
330
331 function uploadSizeError( up, file, over100mb ) {
332         var message;
333
334         if ( over100mb )
335                 message = pluploadL10n.big_upload_queued.replace('%s', file.name) + ' ' + pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>');
336         else
337                 message = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
338
339         jQuery('#media-items').append('<div id="media-item-' + file.id + '" class="media-item error"><p>' + message + '</p></div>');
340         up.removeFile(file);
341 }
342
343 jQuery(document).ready(function($){
344         $('.media-upload-form').bind('click.uploader', function(e) {
345                 var target = $(e.target), tr, c;
346
347                 if ( target.is('input[type="radio"]') ) { // remember the last used image size and alignment
348                         tr = target.closest('tr');
349
350                         if ( tr.hasClass('align') )
351                                 setUserSetting('align', target.val());
352                         else if ( tr.hasClass('image-size') )
353                                 setUserSetting('imgsize', target.val());
354
355                 } else if ( target.is('button.button') ) { // remember the last used image link url
356                         c = e.target.className || '';
357                         c = c.match(/url([^ '"]+)/);
358
359                         if ( c && c[1] ) {
360                                 setUserSetting('urlbutton', c[1]);
361                                 target.siblings('.urlfield').val( target.data('link-url') );
362                         }
363                 } else if ( target.is('a.dismiss') ) {
364                         target.parents('.media-item').fadeOut(200, function(){
365                                 $(this).remove();
366                         });
367                 } else if ( target.is('.upload-flash-bypass a') || target.is('a.uploader-html') ) { // switch uploader to html4
368                         $('#media-items, p.submit, span.big-file-warning').css('display', 'none');
369                         switchUploader(0);
370                         e.preventDefault();
371                 } else if ( target.is('.upload-html-bypass a') ) { // switch uploader to multi-file
372                         $('#media-items, p.submit, span.big-file-warning').css('display', '');
373                         switchUploader(1);
374                         e.preventDefault();
375                 } else if ( target.is('a.describe-toggle-on') ) { // Show
376                         target.parent().addClass('open');
377                         target.siblings('.slidetoggle').fadeIn(250, function(){
378                                 var S = $(window).scrollTop(), H = $(window).height(), top = $(this).offset().top, h = $(this).height(), b, B;
379
380                                 if ( H && top && h ) {
381                                         b = top + h;
382                                         B = S + H;
383
384                                         if ( b > B ) {
385                                                 if ( b - B < top - S )
386                                                         window.scrollBy(0, (b - B) + 10);
387                                                 else
388                                                         window.scrollBy(0, top - S - 40);
389                                         }
390                                 }
391                         });
392                         e.preventDefault();
393                 } else if ( target.is('a.describe-toggle-off') ) { // Hide
394                         target.siblings('.slidetoggle').fadeOut(250, function(){
395                                 target.parent().removeClass('open');
396                         });
397                         e.preventDefault();
398                 }
399         });
400
401         // init and set the uploader
402         uploader_init = function() {
403                 var isIE = navigator.userAgent.indexOf('Trident/') != -1 || navigator.userAgent.indexOf('MSIE ') != -1;
404
405                 // Make sure flash sends cookies (seems in IE it does whitout switching to urlstream mode)
406                 if ( ! isIE && 'flash' === plupload.predictRuntime( wpUploaderInit ) &&
407                         ( ! wpUploaderInit.required_features || ! wpUploaderInit.required_features.hasOwnProperty( 'send_binary_string' ) ) ) {
408
409                         wpUploaderInit.required_features = wpUploaderInit.required_features || {};
410                         wpUploaderInit.required_features.send_binary_string = true;
411                 }
412
413                 uploader = new plupload.Uploader(wpUploaderInit);
414
415                 $('#image_resize').bind('change', function() {
416                         var arg = $(this).prop('checked');
417
418                         setResize( arg );
419
420                         if ( arg )
421                                 setUserSetting('upload_resize', '1');
422                         else
423                                 deleteUserSetting('upload_resize');
424                 });
425
426                 uploader.bind('Init', function(up) {
427                         var uploaddiv = $('#plupload-upload-ui');
428
429                         setResize( getUserSetting('upload_resize', false) );
430
431                         if ( up.features.dragdrop && ! $(document.body).hasClass('mobile') ) {
432                                 uploaddiv.addClass('drag-drop');
433                                 $('#drag-drop-area').bind('dragover.wp-uploader', function(){ // dragenter doesn't fire right :(
434                                         uploaddiv.addClass('drag-over');
435                                 }).bind('dragleave.wp-uploader, drop.wp-uploader', function(){
436                                         uploaddiv.removeClass('drag-over');
437                                 });
438                         } else {
439                                 uploaddiv.removeClass('drag-drop');
440                                 $('#drag-drop-area').unbind('.wp-uploader');
441                         }
442
443                         if ( up.runtime === 'html4' ) {
444                                 $('.upload-flash-bypass').hide();
445                         }
446                 });
447
448                 uploader.init();
449
450                 uploader.bind('FilesAdded', function( up, files ) {
451                         $('#media-upload-error').empty();
452                         uploadStart();
453
454                         plupload.each( files, function( file ) {
455                                 fileQueued( file );
456                         });
457
458                         up.refresh();
459                         up.start();
460                 });
461
462                 uploader.bind('UploadFile', function(up, file) {
463                         fileUploading(up, file);
464                 });
465
466                 uploader.bind('UploadProgress', function(up, file) {
467                         uploadProgress(up, file);
468                 });
469
470                 uploader.bind('Error', function(up, err) {
471                         uploadError(err.file, err.code, err.message, up);
472                         up.refresh();
473                 });
474
475                 uploader.bind('FileUploaded', function(up, file, response) {
476                         uploadSuccess(file, response.response);
477                 });
478
479                 uploader.bind('UploadComplete', function() {
480                         uploadComplete();
481                 });
482         };
483
484         if ( typeof(wpUploaderInit) == 'object' ) {
485                 uploader_init();
486         }
487
488 });