[ Index ]

WordPress Cross Reference

title

Body

[close]

/wp-includes/js/plupload/ -> handlers.js (source)

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


Generated: Tue Mar 25 01:41:18 2014 WordPress honlapkészítés: online1.hu