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