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