home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress / wp-includes / js / plupload / handlers.js next >
Encoding:
JavaScript  |  2017-05-16  |  15.8 KB  |  507 lines

  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.             wpFileExtensionError( uploader, 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 ) {
  332.     var message, errorDiv;
  333.  
  334.     message = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
  335.  
  336.     // Construct the error div.
  337.     errorDiv = jQuery( '<div />' )
  338.         .attr( {
  339.             'id':    'media-item-' + file.id,
  340.             'class': 'media-item error'
  341.         } )
  342.         .append(
  343.             jQuery( '<p />' )
  344.                 .text( message )
  345.         );
  346.  
  347.     // Append the error.
  348.     jQuery('#media-items').append( errorDiv );
  349.     up.removeFile(file);
  350. }
  351.  
  352. function wpFileExtensionError( up, file, message ) {
  353.     jQuery('#media-items').append('<div id="media-item-' + file.id + '" class="media-item error"><p>' + message + '</p></div>');
  354.     up.removeFile(file);
  355. }
  356.  
  357. jQuery(document).ready(function($){
  358.     $('.media-upload-form').bind('click.uploader', function(e) {
  359.         var target = $(e.target), tr, c;
  360.  
  361.         if ( target.is('input[type="radio"]') ) { // remember the last used image size and alignment
  362.             tr = target.closest('tr');
  363.  
  364.             if ( tr.hasClass('align') )
  365.                 setUserSetting('align', target.val());
  366.             else if ( tr.hasClass('image-size') )
  367.                 setUserSetting('imgsize', target.val());
  368.  
  369.         } else if ( target.is('button.button') ) { // remember the last used image link url
  370.             c = e.target.className || '';
  371.             c = c.match(/url([^ '"]+)/);
  372.  
  373.             if ( c && c[1] ) {
  374.                 setUserSetting('urlbutton', c[1]);
  375.                 target.siblings('.urlfield').val( target.data('link-url') );
  376.             }
  377.         } else if ( target.is('a.dismiss') ) {
  378.             target.parents('.media-item').fadeOut(200, function(){
  379.                 $(this).remove();
  380.             });
  381.         } 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');
  383.             switchUploader(0);
  384.             e.preventDefault();
  385.         } else if ( target.is('.upload-html-bypass a') ) { // switch uploader to multi-file
  386.             $('#media-items, p.submit, span.big-file-warning').css('display', '');
  387.             switchUploader(1);
  388.             e.preventDefault();
  389.         } else if ( target.is('a.describe-toggle-on') ) { // Show
  390.             target.parent().addClass('open');
  391.             target.siblings('.slidetoggle').fadeIn(250, function(){
  392.                 var S = $(window).scrollTop(), H = $(window).height(), top = $(this).offset().top, h = $(this).height(), b, B;
  393.  
  394.                 if ( H && top && h ) {
  395.                     b = top + h;
  396.                     B = S + H;
  397.  
  398.                     if ( b > B ) {
  399.                         if ( b - B < top - S )
  400.                             window.scrollBy(0, (b - B) + 10);
  401.                         else
  402.                             window.scrollBy(0, top - S - 40);
  403.                     }
  404.                 }
  405.             });
  406.             e.preventDefault();
  407.         } else if ( target.is('a.describe-toggle-off') ) { // Hide
  408.             target.siblings('.slidetoggle').fadeOut(250, function(){
  409.                 target.parent().removeClass('open');
  410.             });
  411.             e.preventDefault();
  412.         }
  413.     });
  414.  
  415.     // init and set the uploader
  416.     uploader_init = function() {
  417.         var isIE = navigator.userAgent.indexOf('Trident/') != -1 || navigator.userAgent.indexOf('MSIE ') != -1;
  418.  
  419.         // Make sure flash sends cookies (seems in IE it does whitout switching to urlstream mode)
  420.         if ( ! isIE && 'flash' === plupload.predictRuntime( wpUploaderInit ) &&
  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.  
  432.             setResize( arg );
  433.  
  434.             if ( arg )
  435.                 setUserSetting('upload_resize', '1');
  436.             else
  437.                 deleteUserSetting('upload_resize');
  438.         });
  439.  
  440.         uploader.bind('Init', function(up) {
  441.             var uploaddiv = $('#plupload-upload-ui');
  442.  
  443.             setResize( getUserSetting('upload_resize', false) );
  444.  
  445.             if ( up.features.dragdrop && ! $(document.body).hasClass('mobile') ) {
  446.                 uploaddiv.addClass('drag-drop');
  447.                 $('#drag-drop-area').on('dragover.wp-uploader', function(){ // dragenter doesn't fire right :(
  448.                     uploaddiv.addClass('drag-over');
  449.                 }).on('dragleave.wp-uploader, drop.wp-uploader', function(){
  450.                     uploaddiv.removeClass('drag-over');
  451.                 });
  452.             } else {
  453.                 uploaddiv.removeClass('drag-drop');
  454.                 $('#drag-drop-area').off('.wp-uploader');
  455.             }
  456.  
  457.             if ( up.runtime === 'html4' ) {
  458.                 $('.upload-flash-bypass').hide();
  459.             }
  460.         });
  461.  
  462.         uploader.bind( 'postinit', function( up ) {
  463.             up.refresh();
  464.         });
  465.  
  466.         uploader.init();
  467.  
  468.         uploader.bind('FilesAdded', function( up, files ) {
  469.             $('#media-upload-error').empty();
  470.             uploadStart();
  471.  
  472.             plupload.each( files, function( file ) {
  473.                 fileQueued( file );
  474.             });
  475.  
  476.             up.refresh();
  477.             up.start();
  478.         });
  479.  
  480.         uploader.bind('UploadFile', function(up, file) {
  481.             fileUploading(up, file);
  482.         });
  483.  
  484.         uploader.bind('UploadProgress', function(up, file) {
  485.             uploadProgress(up, file);
  486.         });
  487.  
  488.         uploader.bind('Error', function(up, err) {
  489.             uploadError(err.file, err.code, err.message, up);
  490.             up.refresh();
  491.         });
  492.  
  493.         uploader.bind('FileUploaded', function(up, file, response) {
  494.             uploadSuccess(file, response.response);
  495.         });
  496.  
  497.         uploader.bind('UploadComplete', function() {
  498.             uploadComplete();
  499.         });
  500.     };
  501.  
  502.     if ( typeof(wpUploaderInit) == 'object' ) {
  503.         uploader_init();
  504.     }
  505.  
  506. });
  507.