Make WordPress Core

Changeset 45934


Ignore:
Timestamp:
09/04/2019 01:10:57 AM (7 years ago)
Author:
azaozz
Message:

Uploads: After an image is uploaded and PHP times out or runs out of memory during post-processing (the server response is HTTP 500 error), try to resize it three more times. Then, if all attempts fail, do a cleanup of any sub-sizes that may have been created and show an error message asking the user to scale the image and upload it again.

See #47872.

Location:
trunk/src
Files:
8 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/js/_enqueues/vendor/plupload/handlers.js

    r43309 r45934  
    33
    44// progress and success handlers for media multi uploads
    5 function fileQueued(fileObj) {
     5function fileQueued( fileObj ) {
    66        // Get rid of unused form
    7         jQuery('.media-blank').remove();
    8 
    9         var items = jQuery('#media-items').children(), postid = post_id || 0;
     7        jQuery( '.media-blank' ).remove();
     8
     9        var items = jQuery( '#media-items' ).children(), postid = post_id || 0;
    1010
    1111        // Collapse a single item
    1212        if ( items.length == 1 ) {
    13                 items.removeClass('open').find('.slidetoggle').slideUp(200);
     13                items.removeClass( 'open' ).find( '.slidetoggle' ).slideUp( 200 );
    1414        }
    1515        // Create a progress bar containing the filename
    16         jQuery('<div class="media-item">')
     16        jQuery( '<div class="media-item">' )
    1717                .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' ) );
     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' ) );
    2222
    2323        // Disable submit
    24         jQuery('#insert-gallery').prop('disabled', true);
     24        jQuery( '#insert-gallery' ).prop( 'disabled', true );
    2525}
    2626
     
    2828        try {
    2929                if ( typeof topWin.tb_remove != 'undefined' )
    30                         topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
    31         } catch(e){}
     30                        topWin.jQuery( '#TB_overlay' ).unbind( 'click', topWin.tb_remove );
     31        } catch( e ){}
    3232
    3333        return true;
    3434}
    3535
    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 + '%' );
     36function 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 + '%' );
    4141}
    4242
     
    5959
    6060function updateMediaForm() {
    61         var items = jQuery('#media-items').children();
     61        var items = jQuery( '#media-items' ).children();
    6262
    6363        // Just one file, no need for collapsible part
    6464        if ( items.length == 1 ) {
    65                 items.addClass('open').find('.slidetoggle').show();
    66                 jQuery('.insert-gallery').hide();
     65                items.addClass( 'open' ).find( '.slidetoggle' ).show();
     66                jQuery( '.insert-gallery' ).hide();
    6767        } else if ( items.length > 1 ) {
    68                 items.removeClass('open');
     68                items.removeClass( 'open' );
    6969                // Only show Gallery/Playlist buttons when there are at least two files.
    70                 jQuery('.insert-gallery').show();
     70                jQuery( '.insert-gallery' ).show();
    7171        }
    7272
    7373        // Only show Save buttons when there is at least one file.
    74         if ( items.not('.media-blank').length > 0 )
    75                 jQuery('.savebutton').show();
     74        if ( items.not( '.media-blank' ).length > 0 )
     75                jQuery( '.savebutton' ).show();
    7676        else
    77                 jQuery('.savebutton').hide();
    78 }
    79 
    80 function uploadSuccess(fileObj, serverData) {
    81         var item = jQuery('#media-item-' + fileObj.id);
     77                jQuery( '.savebutton' ).hide();
     78}
     79
     80function uploadSuccess( fileObj, serverData ) {
     81        var item = jQuery( '#media-item-' + fileObj.id );
    8282
    8383        // 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);
     84        if ( typeof serverData === 'string' ) {
     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 ( /media-upload-error|error-div/.test( serverData ) ) {
     89                        item.html( serverData );
     90                        return;
     91                }
     92        }
     93
     94        item.find( '.percent' ).html( pluploadL10n.crunching );
     95
     96        prepareMediaItem( fileObj, serverData );
    9597        updateMediaForm();
    9698
    9799        // 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        if ( post_id && item.hasClass( 'child-of-' + post_id ) ) {
     101                jQuery( '#attachments-count' ).text( 1 * jQuery( '#attachments-count' ).text() + 1 );
     102        }
    100103}
    101104
     
    117120}
    118121
    119 function prepareMediaItem(fileObj, serverData) {
    120         var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
     122function prepareMediaItem( fileObj, serverData ) {
     123        var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery( '#media-item-' + fileObj.id );
    121124        if ( f == 2 && shortform > 2 )
    122125                f = shortform;
     
    124127        try {
    125128                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);
     129                        topWin.jQuery( '#TB_overlay' ).click( topWin.tb_remove );
     130        } catch( e ){}
     131
     132        if ( isNaN( serverData ) || !serverData ) { // Old style: Append the HTML returned by the server -- thumbnail and form inputs
     133                item.append( serverData );
     134                prepareMediaItemInit( fileObj );
    132135        } 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);
     136                item.load( 'async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit( fileObj );updateMediaForm();});
     137        }
     138}
     139
     140function prepareMediaItemInit( fileObj ) {
     141        var item = jQuery( '#media-item-' + fileObj.id );
    139142        // 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);
     143        jQuery( '.thumbnail', item ).clone().attr( 'class', 'pinkynail toggle' ).prependTo( item );
    141144
    142145        // Replace the original filename with the new (unique) one assigned during upload
    143         jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
     146        jQuery( '.filename.original', item ).replaceWith( jQuery( '.filename.new', item ) );
    144147
    145148        // Bind AJAX to the new Delete button
    146         jQuery('a.delete', item).click(function(){
     149        jQuery( 'a.delete', item ).click( function(){
    147150                // Tell the server to delete it. TODO: handle exceptions
    148151                jQuery.ajax({
     
    153156                        id: fileObj.id,
    154157                        data: {
    155                                 id : this.id.replace(/[^0-9]/g, ''),
     158                                id : this.id.replace(/[^0-9]/g, '' ),
    156159                                action : 'trash-post',
    157                                 _ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
     160                                _ajax_nonce : this.href.replace(/^.*wpnonce=/,'' )
    158161                        }
    159162                });
     
    162165
    163166        // Bind AJAX to the new Undo button
    164         jQuery('a.undo', item).click(function(){
     167        jQuery( 'a.undo', item ).click( function(){
    165168                // Tell the server to untrash it. TODO: handle exceptions
    166169                jQuery.ajax({
     
    169172                        id: fileObj.id,
    170173                        data: {
    171                                 id : this.id.replace(/[^0-9]/g,''),
     174                                id : this.id.replace(/[^0-9]/g,'' ),
    172175                                action: 'untrash-post',
    173                                 _ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
     176                                _ajax_nonce: this.href.replace(/^.*wpnonce=/,'' )
    174177                        },
    175178                        success: function( ){
    176179                                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');
     180                                        item = jQuery( '#media-item-' + fileObj.id );
     181
     182                                if ( type = jQuery( '#type-of-' + fileObj.id ).val() )
     183                                        jQuery( '#' + type + '-counter' ).text( jQuery( '#' + type + '-counter' ).text()-0+1 );
     184
     185                                if ( post_id && item.hasClass( 'child-of-'+post_id ) )
     186                                        jQuery( '#attachments-count' ).text( jQuery( '#attachments-count' ).text()-0+1 );
     187
     188                                jQuery( '.filename .trashnotice', item ).remove();
     189                                jQuery( '.filename .title', item ).css( 'font-weight','normal' );
     190                                jQuery( 'a.undo', item ).addClass( 'hidden' );
     191                                jQuery( '.menu_order_input', item ).show();
     192                                item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery( this ).css({backgroundColor:''}); } }).removeClass( 'undo' );
    190193                        }
    191194                });
     
    194197
    195198        // 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();
     199        jQuery( '#media-item-' + fileObj.id + '.startopen' ).removeClass( 'startopen' ).addClass( 'open' ).find( 'slidetoggle' ).fadeIn();
    197200}
    198201
    199202// generic error message
    200 function wpQueueError(message) {
    201         jQuery('#media-upload-error').show().html( '<div class="error"><p>' + message + '</p></div>' );
     203function wpQueueError( message ) {
     204        jQuery( '#media-upload-error' ).show().html( '<div class="error"><p>' + message + '</p></div>' );
    202205}
    203206
    204207// 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');
     208function wpFileError( fileObj, message ) {
     209        itemAjaxError( fileObj.id, message );
     210}
     211
     212function itemAjaxError( id, message ) {
     213        var item = jQuery( '#media-item-' + id ), filename = item.find( '.filename' ).text(), last_err = item.data( 'last-err' );
    211214
    212215        if ( last_err == id ) // prevent firing an error for the same file twice
    213216                return;
    214217
    215         item.html('<div class="error-div">' +
     218        item.html( '<div class="error-div">' +
    216219                                '<a class="dismiss" href="#">' + pluploadL10n.dismiss + '</a>' +
    217                                 '<strong>' + pluploadL10n.error_uploading.replace('%s', jQuery.trim(filename)) + '</strong> ' +
     220                                '<strong>' + pluploadL10n.error_uploading.replace( '%s', jQuery.trim( filename )) + '</strong> ' +
    218221                                message +
    219                                 '</div>').data('last-err', id);
    220 }
    221 
    222 function deleteSuccess(data) {
     222                                '</div>' ).data( 'last-err', id );
     223}
     224
     225function deleteSuccess( data ) {
    223226        var type, id, item;
    224227        if ( data == '-1' )
    225                 return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
     228                return itemAjaxError( this.id, 'You do not have permission. Has your session expired?' );
    226229
    227230        if ( data == '0' )
    228                 return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
     231                return itemAjaxError( this.id, 'Could not be deleted. Has it been deleted already?' );
    229232
    230233        id = this.id;
    231         item = jQuery('#media-item-' + id);
     234        item = jQuery( '#media-item-' + id );
    232235
    233236        // 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');
     237        if ( type = jQuery( '#type-of-' + id ).val() )
     238                jQuery( '#' + type + '-counter' ).text( jQuery( '#' + type + '-counter' ).text() - 1 );
     239
     240        if ( post_id && item.hasClass( 'child-of-'+post_id ) )
     241                jQuery( '#attachments-count' ).text( jQuery( '#attachments-count' ).text() - 1 );
     242
     243        if ( jQuery( 'form.type-form #media-items' ).children().length == 1 && jQuery( '.hidden', '#media-items' ).length > 0 ) {
     244                jQuery( '.toggle' ).toggle();
     245                jQuery( '.slidetoggle' ).slideUp( 200 ).siblings().removeClass( 'hidden' );
    243246        }
    244247
    245248        // 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();
     249        jQuery( '.toggle', item ).toggle();
     250        jQuery( '.slidetoggle', item ).slideUp( 200 ).siblings().removeClass( 'hidden' );
     251        item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass( 'undo' );
     252
     253        jQuery( '.filename:empty', item ).remove();
     254        jQuery( '.filename .title', item ).css( 'font-weight','bold' );
     255        jQuery( '.filename', item ).append( '<span class="trashnotice"> ' + pluploadL10n.deleted + ' </span>' ).siblings( 'a.toggle' ).hide();
     256        jQuery( '.filename', item ).append( jQuery( 'a.undo', item ).removeClass( 'hidden' ) );
     257        jQuery( '.menu_order_input', item ).hide();
    255258
    256259        return;
     
    258261
    259262function deleteError() {
    260         // TODO
    261263}
    262264
    263265function uploadComplete() {
    264         jQuery('#insert-gallery').prop('disabled', false);
    265 }
    266 
    267 function switchUploader(s) {
     266        jQuery( '#insert-gallery' ).prop( 'disabled', false );
     267}
     268
     269function switchUploader( s ) {
    268270        if ( s ) {
    269                 deleteUserSetting('uploader');
    270                 jQuery('.media-upload-form').removeClass('html-uploader');
    271 
    272                 if ( typeof(uploader) == 'object' )
     271                deleteUserSetting( 'uploader' );
     272                jQuery( '.media-upload-form' ).removeClass( 'html-uploader' );
     273
     274                if ( typeof( uploader ) == 'object' )
    273275                        uploader.refresh();
    274276        } 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) {
     277                setUserSetting( 'uploader', '1' ); // 1 == html uploader
     278                jQuery( '.media-upload-form' ).addClass( 'html-uploader' );
     279        }
     280}
     281
     282function uploadError( fileObj, errorCode, message, up ) {
    281283        var hundredmb = 100 * 1024 * 1024, max;
    282284
    283         switch (errorCode) {
     285        switch ( errorCode ) {
    284286                case plupload.FAILED:
    285                         wpFileError(fileObj, pluploadL10n.upload_failed);
     287                        wpFileError( fileObj, pluploadL10n.upload_failed );
    286288                        break;
    287289                case plupload.FILE_EXTENSION_ERROR:
    288                         wpFileExtensionError( uploader, fileObj, pluploadL10n.invalid_filetype );
     290                        wpFileExtensionError( up, fileObj, pluploadL10n.invalid_filetype );
    289291                        break;
    290292                case plupload.FILE_SIZE_ERROR:
    291                         uploadSizeError(uploader, fileObj);
     293                        uploadSizeError( up, fileObj );
    292294                        break;
    293295                case plupload.IMAGE_FORMAT_ERROR:
    294                         wpFileError(fileObj, pluploadL10n.not_an_image);
     296                        wpFileError( fileObj, pluploadL10n.not_an_image );
    295297                        break;
    296298                case plupload.IMAGE_MEMORY_ERROR:
    297                         wpFileError(fileObj, pluploadL10n.image_memory_exceeded);
     299                        wpFileError( fileObj, pluploadL10n.image_memory_exceeded );
    298300                        break;
    299301                case plupload.IMAGE_DIMENSIONS_ERROR:
    300                         wpFileError(fileObj, pluploadL10n.image_dimensions_exceeded);
     302                        wpFileError( fileObj, pluploadL10n.image_dimensions_exceeded );
    301303                        break;
    302304                case plupload.GENERIC_ERROR:
    303                         wpQueueError(pluploadL10n.upload_failed);
     305                        wpQueueError( pluploadL10n.upload_failed );
    304306                        break;
    305307                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);
     308                        max = parseInt( up.settings.filters.max_file_size, 10 );
     309
     310                        if ( max > hundredmb && fileObj.size > hundredmb ) {
     311                                wpFileError( fileObj, pluploadL10n.big_upload_failed.replace( '%1$s', '<a class="uploader-html" href="#">' ).replace( '%2$s', '</a>' ) );
     312                        } else {
     313                                wpQueueError( pluploadL10n.io_error );
     314                        }
     315
    312316                        break;
    313317                case plupload.HTTP_ERROR:
    314                         wpQueueError(pluploadL10n.http_error);
     318                        wpQueueError( pluploadL10n.http_error );
    315319                        break;
    316320                case plupload.INIT_ERROR:
    317                         jQuery('.media-upload-form').addClass('html-uploader');
     321                        jQuery( '.media-upload-form' ).addClass( 'html-uploader' );
    318322                        break;
    319323                case plupload.SECURITY_ERROR:
    320                         wpQueueError(pluploadL10n.security_error);
     324                        wpQueueError( pluploadL10n.security_error );
    321325                        break;
    322326/*              case plupload.UPLOAD_ERROR.UPLOAD_STOPPED:
    323327                case plupload.UPLOAD_ERROR.FILE_CANCELLED:
    324                         jQuery('#media-item-' + fileObj.id).remove();
     328                        jQuery( '#media-item-' + fileObj.id ).remove();
    325329                        break;*/
    326330                default:
    327                         wpFileError(fileObj, pluploadL10n.default_error);
     331                        wpFileError( fileObj, pluploadL10n.default_error );
    328332        }
    329333}
     
    332336        var message, errorDiv;
    333337
    334         message = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
     338        message = pluploadL10n.file_exceeds_size_limit.replace( '%s', file.name );
    335339
    336340        // Construct the error div.
     
    346350
    347351        // Append the error.
    348         jQuery('#media-items').append( errorDiv );
    349         up.removeFile(file);
     352        jQuery( '#media-items' ).append( errorDiv );
     353        up.removeFile( file );
    350354}
    351355
    352356function 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
     357        jQuery( '#media-items' ).append( '<div id="media-item-' + file.id + '" class="media-item error"><p>' + message + '</p></div>' );
     358        up.removeFile( file );
     359}
     360
     361jQuery( document ).ready( function( $ ) {
     362        var tryAgainCount = {};
     363        var tryAgain;
     364
     365        $( '.media-upload-form' ).bind( 'click.uploader', function( e ) {
     366                var target = $( e.target ), tr, c;
     367
     368                if ( target.is( 'input[type="radio"]' ) ) { // remember the last used image size and alignment
     369                        tr = target.closest( 'tr' );
     370
     371                        if ( tr.hasClass( 'align' ) )
     372                                setUserSetting( 'align', target.val() );
     373                        else if ( tr.hasClass( 'image-size' ) )
     374                                setUserSetting( 'imgsize', target.val() );
     375
     376                } else if ( target.is( 'button.button' ) ) { // remember the last used image link url
    370377                        c = e.target.className || '';
    371                         c = c.match(/url([^ '"]+)/);
     378                        c = c.match( /url([^ '"]+)/ );
    372379
    373380                        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);
     381                                setUserSetting( 'urlbutton', c[1] );
     382                                target.siblings( '.urlfield' ).val( target.data( 'link-url' ) );
     383                        }
     384                } else if ( target.is( 'a.dismiss' ) ) {
     385                        target.parents( '.media-item' ).fadeOut( 200, function() {
     386                                $( this ).remove();
     387                        } );
     388                } else if ( target.is( '.upload-flash-bypass a' ) || target.is( 'a.uploader-html' ) ) { // switch uploader to html4
     389                        $( '#media-items, p.submit, span.big-file-warning' ).css( 'display', 'none' );
     390                        switchUploader( 0 );
    384391                        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);
     392                } else if ( target.is( '.upload-html-bypass a' ) ) { // switch uploader to multi-file
     393                        $( '#media-items, p.submit, span.big-file-warning' ).css( 'display', '' );
     394                        switchUploader( 1 );
    388395                        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;
     396                } else if ( target.is( 'a.describe-toggle-on' ) ) { // Show
     397                        target.parent().addClass( 'open' );
     398                        target.siblings( '.slidetoggle' ).fadeIn( 250, function() {
     399                                var S = $( window ).scrollTop(),
     400                                        H = $( window ).height(),
     401                                        top = $( this ).offset().top,
     402                                        h = $( this ).height(),
     403                                        b,
     404                                        B;
    393405
    394406                                if ( H && top && h ) {
     
    398410                                        if ( b > B ) {
    399411                                                if ( b - B < top - S )
    400                                                         window.scrollBy(0, (b - B) + 10);
     412                                                        window.scrollBy( 0, ( b - B ) + 10 );
    401413                                                else
    402                                                         window.scrollBy(0, top - S - 40);
     414                                                        window.scrollBy( 0, top - S - 40 );
    403415                                        }
    404416                                }
    405                         });
     417                        } );
     418
    406419                        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                         });
     420                } else if ( target.is( 'a.describe-toggle-off' ) ) { // Hide
     421                        target.siblings( '.slidetoggle' ).fadeOut( 250, function() {
     422                                target.parent().removeClass( 'open' );
     423                        } );
     424
    411425                        e.preventDefault();
    412426                }
    413427        });
    414428
     429        // Attempt to create image sub-sizes when an image was uploaded successfully
     430        // but the server responded with HTTP 500 error.
     431        tryAgain = function( up, error ) {
     432                var file = error.file;
     433                var times;
     434
     435                if ( ! file || ! file.id ) {
     436                        wpQueueError( error.message || pluploadL10n.default_error );
     437                        return;
     438                }
     439
     440                times = tryAgainCount[ file.id ];
     441
     442                if ( times && times > 4 ) {
     443                        // The file may have been uploaded and attachment post created,
     444                        // but post-processing and resizing failed...
     445                        // Do a cleanup then tell the user to scale down the image and upload it again.
     446                        $.ajax({
     447                                type: 'post',
     448                                url: ajaxurl,
     449                                dataType: 'json',
     450                                data: {
     451                                        action: 'media-create-image-subsizes',
     452                                        _wpnonce: _wpPluploadSettings.defaults.multipart_params._wpnonce,
     453                                        _wp_temp_image_ref: file.id,
     454                                        _wp_upload_failed_cleanup: true,
     455                                }
     456                        });
     457
     458                        if ( error.message && error.status !== 500 ) {
     459                                wpQueueError( error.message );
     460                        } else {
     461                                wpQueueError( pluploadL10n.http_error_image );
     462                        }
     463
     464                        return;
     465                }
     466
     467                if ( ! times ) {
     468                        tryAgainCount[ file.id ] = 1;
     469                } else {
     470                        tryAgainCount[ file.id ] = ++times;
     471                }
     472
     473                // Try to create the missing image sizes.
     474                $.ajax({
     475                        type: 'post',
     476                        url: ajaxurl,
     477                        dataType: 'json',
     478                        data: {
     479                                action: 'media-create-image-subsizes',
     480                                _wpnonce: wpUploaderInit.multipart_params._wpnonce,
     481                                _wp_temp_image_ref: file.id,
     482                                _legasy_support: 'true',
     483                        }
     484                }).done( function( response ) {
     485                        var message;
     486
     487                        if ( response.success ) {
     488                                uploadSuccess( file, response.data.id );
     489                        } else {
     490                                if ( response.data && response.data.message ) {
     491                                        message = response.data.message;
     492                                }
     493
     494                                wpQueueError( message || pluploadL10n.http_error_image );
     495                        }
     496                }).fail( function( jqXHR ) {
     497                        // If another HTTP 500 error, try try again...
     498                        if ( jqXHR.status === 500 ) {
     499                                tryAgain( up, error );
     500                                return;
     501                        }
     502
     503                        wpQueueError( pluploadL10n.http_error_image );
     504                });
     505        }
     506
    415507        // init and set the uploader
    416508        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');
     509                uploader = new plupload.Uploader( wpUploaderInit );
     510
     511                $( '#image_resize' ).bind( 'change', function() {
     512                        var arg = $( this ).prop( 'checked' );
    431513
    432514                        setResize( arg );
    433515
    434516                        if ( arg )
    435                                 setUserSetting('upload_resize', '1');
     517                                setUserSetting( 'upload_resize', '1' );
    436518                        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');
     519                                deleteUserSetting( 'upload_resize' );
     520                });
     521
     522                uploader.bind( 'Init', function( up ) {
     523                        var uploaddiv = $( '#plupload-upload-ui' );
     524
     525                        setResize( getUserSetting( 'upload_resize', false ) );
     526
     527                        if ( up.features.dragdrop && ! $( document.body ).hasClass( 'mobile' ) ) {
     528                                uploaddiv.addClass( 'drag-drop' );
     529
     530                                $( '#drag-drop-area' ).on( 'dragover.wp-uploader', function() { // dragenter doesn't fire right :(
     531                                        uploaddiv.addClass( 'drag-over' );
     532                                }).on( 'dragleave.wp-uploader, drop.wp-uploader', function() {
     533                                        uploaddiv.removeClass( 'drag-over' );
    451534                                });
    452535                        } else {
    453                                 uploaddiv.removeClass('drag-drop');
    454                                 $('#drag-drop-area').off('.wp-uploader');
     536                                uploaddiv.removeClass( 'drag-drop' );
     537                                $( '#drag-drop-area' ).off( '.wp-uploader' );
    455538                        }
    456539
    457540                        if ( up.runtime === 'html4' ) {
    458                                 $('.upload-flash-bypass').hide();
     541                                $( '.upload-flash-bypass' ).hide();
    459542                        }
    460543                });
     
    466549                uploader.init();
    467550
    468                 uploader.bind('FilesAdded', function( up, files ) {
    469                         $('#media-upload-error').empty();
     551                uploader.bind( 'FilesAdded', function( up, files ) {
     552                        $( '#media-upload-error' ).empty();
    470553                        uploadStart();
    471554
     
    478561                });
    479562
    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);
     563                uploader.bind( 'UploadFile', function( up, file ) {
     564                        fileUploading( up, file );
     565                });
     566
     567                uploader.bind( 'UploadProgress', function( up, file ) {
     568                        uploadProgress( up, file );
     569                });
     570
     571                uploader.bind( 'Error', function( up, error ) {
     572                        var isImage = error.file && error.file.type && error.file.type.indexOf( 'image/' ) === 0;
     573                        var status  = error && error.status;
     574
     575                        // If the file is an image and the error is HTTP 500 try to create sub-sizes again.
     576                        if ( status === 500 && isImage ) {
     577                                tryAgain( up, error );
     578                                return;
     579                        }
     580
     581                        uploadError( error.file, error.code, error.message, up );
    490582                        up.refresh();
    491583                });
    492584
    493                 uploader.bind('FileUploaded', function(up, file, response) {
    494                         uploadSuccess(file, response.response);
    495                 });
    496 
    497                 uploader.bind('UploadComplete', function() {
     585                uploader.bind( 'FileUploaded', function( up, file, response ) {
     586                        uploadSuccess( file, response.response );
     587                });
     588
     589                uploader.bind( 'UploadComplete', function() {
    498590                        uploadComplete();
    499591                });
     592
     593                /**
     594                 * When uploading images add a file reference used to retrieve the attachment_id
     595                 * if the uploading fails due to a server timeout of out of memoty (HTTP 500) error.
     596                 *
     597                 * @param {plupload.Uploader} up   Uploader instance.
     598                 * @param {plupload.File}     file File for uploading.
     599                 */
     600                uploader.bind( 'BeforeUpload', function( up, file ) {
     601                        if ( file.type && file.type.indexOf( 'image/' ) === 0 ) {
     602                                up.settings.multipart_params._wp_temp_image_ref = file.id;
     603                        } else {
     604                                unset( up.settings.multipart_params._wp_temp_image_ref );
     605                        }
     606                } );
    500607        };
    501608
    502         if ( typeof(wpUploaderInit) == 'object' ) {
     609        if ( typeof( wpUploaderInit ) == 'object' ) {
    503610                uploader_init();
    504611        }
  • trunk/src/js/_enqueues/vendor/plupload/wp-plupload.js

    r43309 r45934  
    3434        Uploader = function( options ) {
    3535                var self = this,
    36                         isIE = navigator.userAgent.indexOf('Trident/') != -1 || navigator.userAgent.indexOf('MSIE ') != -1,
     36                        isIE, // not used, back-compat
    3737                        elements = {
    3838                                container: 'container',
     
    4040                                dropzone:  'drop_element'
    4141                        },
    42                         key, error;
     42                        tryAgainCount = {},
     43                        tryAgain,
     44                        key,
     45                        error,
     46                        fileUploaded;
    4347
    4448                this.supports = {
     
    96100                }
    97101
    98                 // Make sure flash sends cookies (seems in IE it does without switching to urlstream mode)
    99                 if ( ! isIE && 'flash' === plupload.predictRuntime( this.plupload ) &&
    100                         ( ! this.plupload.required_features || ! this.plupload.required_features.hasOwnProperty( 'send_binary_string' ) ) ) {
    101 
    102                         this.plupload.required_features = this.plupload.required_features || {};
    103                         this.plupload.required_features.send_binary_string = true;
    104                 }
    105 
    106102                // Initialize the plupload instance.
    107103                this.uploader = new plupload.Uploader( this.plupload );
     
    113109
    114110                /**
     111                 * Attempt to create image sub-sizes when an image was uploaded successfully
     112                 * but the server responded with HTTP 500 error.
     113                 *
     114                 * @since 5.3.0
     115                 *
     116                 * @param  {string}        message  Error message.
     117                 * @param  {object}        data     Error data from Plupload.
     118                 * @param  {plupload.File} file     File that was uploaded.
     119                 */
     120                tryAgain = function( message, data, file ) {
     121                        var times;
     122
     123                        if ( ! file || ! file.id ) {
     124                                error( pluploadL10n.upload_failed, data, file, 'no-retry' );
     125                                return;
     126                        }
     127
     128                        times = tryAgainCount[ file.id ];
     129
     130                        if ( times && times > 4 ) {
     131                                // The file may have been uploaded and attachment post created,
     132                                // but post-processing and resizing failed...
     133                                // Do a cleanup then tell the user to scale down the image and upload it again.
     134                                $.ajax({
     135                                        type: 'post',
     136                                        url: ajaxurl,
     137                                        dataType: 'json',
     138                                        data: {
     139                                                action: 'media-create-image-subsizes',
     140                                                _wpnonce: _wpPluploadSettings.defaults.multipart_params._wpnonce,
     141                                                _wp_temp_image_ref: file.id,
     142                                                _wp_upload_failed_cleanup: true,
     143                                        }
     144                                });
     145
     146                                error( message, data, file, 'no-retry' );
     147                                return;
     148                        }
     149
     150                        if ( ! times ) {
     151                                tryAgainCount[ file.id ] = 1;
     152                        } else {
     153                                tryAgainCount[ file.id ] = ++times;
     154                        }
     155
     156                        // Another request to try to create the missing image sub-sizes.
     157                        $.ajax({
     158                                type: 'post',
     159                                url: ajaxurl,
     160                                dataType: 'json',
     161                                data: {
     162                                        action: 'media-create-image-subsizes',
     163                                        _wpnonce: _wpPluploadSettings.defaults.multipart_params._wpnonce,
     164                                        _wp_temp_image_ref: file.id, // Used to find the new attachment_id.
     165                                }
     166                        }).done( function( response ) {
     167                                if ( response.success ) {
     168                                        fileUploaded( self.uploader, file, response );
     169                                } else {
     170                                        if ( response.data && response.data.message ) {
     171                                                message = response.data.message;
     172                                        }
     173
     174                                        error( message, data, file, 'no-retry' );
     175                                }
     176                        }).fail( function( jqXHR ) {
     177                                // If another HTTP 500 error, try try again...
     178                                if ( jqXHR.status === 500 ) {
     179                                        tryAgain( message, data, file );
     180                                        return;
     181                                }
     182
     183                                error( message, data, file, 'no-retry' );
     184                        });
     185                }
     186
     187                /**
    115188                 * Custom error callback.
    116189                 *
     
    118191                 * and display errors. @see wp.Uploader.errors.
    119192                 *
    120                  * @param  {string}        message
    121                  * @param  {object}        data
     193                 * @param  {string}        message  Error message.
     194                 * @param  {object}        data     Error data from Plupload.
    122195                 * @param  {plupload.File} file     File that was uploaded.
    123                  */
    124                 error = function( message, data, file ) {
     196                 * @param  {string}        retry    Whether to try again to create image sub-sizes. Passing 'no-retry' will prevent it.
     197                 */
     198                error = function( message, data, file, retry ) {
     199                        var isImage = file.type && file.type.indexOf( 'image/' ) === 0;
     200                        var status  = data && data.status;
     201
     202                        // If the file is an image and the error is HTTP 500 try to create sub-sizes again.
     203                        if ( retry !== 'no-retry' && status === 500 && isImage ) {
     204                                tryAgain( message, data, file );
     205                                return;
     206                        }
     207
    125208                        if ( file.attachment ) {
    126209                                file.attachment.destroy();
     
    135218                        self.error( message, data, file );
    136219                };
     220
     221                /**
     222                 * After a file is successfully uploaded, update its model.
     223                 *
     224                 * @param {plupload.Uploader} up       Uploader instance.
     225                 * @param {plupload.File}     file     File that was uploaded.
     226                 * @param {Object}            response Object with response properties.
     227                 */
     228                fileUploaded = function( up, file, response ) {
     229                        var complete;
     230
     231                        // Remove the "uploading" UI elements
     232                        _.each( ['file','loaded','size','percent'], function( key ) {
     233                                file.attachment.unset( key );
     234                        } );
     235
     236                        file.attachment.set( _.extend( response.data, { uploading: false } ) );
     237
     238                        wp.media.model.Attachment.get( response.data.id, file.attachment );
     239
     240                        complete = Uploader.queue.all( function( attachment ) {
     241                                return ! attachment.get( 'uploading' );
     242                        });
     243
     244                        if ( complete ) {
     245                                Uploader.queue.reset();
     246                        }
     247
     248                        self.success( file.attachment );
     249                }
    137250
    138251                /**
     
    204317
    205318                /**
     319                 * When uploading images add a reference used to retrieve the attachment_id.
     320                 * Used if the uploading fails due to a server timeout of out of memoty error (HTTP 500).
     321                 *
     322                 * @param {plupload.Uploader} up   Uploader instance.
     323                 * @param {plupload.File}     file File for uploading.
     324                 */
     325                this.uploader.bind( 'BeforeUpload', function( up, file ) {
     326                        if ( file.type && file.type.indexOf( 'image/' ) === 0 ) {
     327                                up.settings.multipart_params._wp_temp_image_ref = file.id;
     328                        } else {
     329                                unset( up.settings.multipart_params._wp_temp_image_ref );
     330                        }
     331                } );
     332
     333                /**
    206334                 * After files were filtered and added to the queue, create a model for each.
    207335                 *
    208                  * @param {plupload.Uploader} uploader Uploader instance.
    209                  * @param {Array}             files    Array of file objects that were added to queue by the user.
     336                 * @param {plupload.Uploader} up    Uploader instance.
     337                 * @param {Array}             files Array of file objects that were added to queue by the user.
    210338                 */
    211339                this.uploader.bind( 'FilesAdded', function( up, files ) {
     
    260388                 * After a file is successfully uploaded, update its model.
    261389                 *
    262                  * @param {plupload.Uploader} uploader Uploader instance.
     390                 * @param {plupload.Uploader} up      Uploader instance.
    263391                 * @param {plupload.File}     file     File that was uploaded.
    264392                 * @param {Object}            response Object with response properties.
     
    266394                 */
    267395                this.uploader.bind( 'FileUploaded', function( up, file, response ) {
    268                         var complete;
    269396
    270397                        try {
     
    274401                        }
    275402
    276                         if ( ! _.isObject( response ) || _.isUndefined( response.success ) )
     403                        if ( ! _.isObject( response ) || _.isUndefined( response.success ) ) {
    277404                                return error( pluploadL10n.default_error, null, file );
    278                         else if ( ! response.success )
     405                        } else if ( ! response.success ) {
    279406                                return error( response.data && response.data.message, response.data, file );
    280 
    281                         _.each(['file','loaded','size','percent'], function( key ) {
    282                                 file.attachment.unset( key );
    283                         });
    284 
    285                         file.attachment.set( _.extend( response.data, { uploading: false }) );
    286                         wp.media.model.Attachment.get( response.data.id, file.attachment );
    287 
    288                         complete = Uploader.queue.all( function( attachment ) {
    289                                 return ! attachment.get('uploading');
    290                         });
    291 
    292                         if ( complete )
    293                                 Uploader.queue.reset();
    294 
    295                         self.success( file.attachment );
     407                        }
     408
     409                        // Success. Update the UI with the new attachment.
     410                        fileUploaded( up, file, response );
    296411                });
    297412
     
    299414                 * When plupload surfaces an error, send it to the error handler.
    300415                 *
    301                  * @param {plupload.Uploader} uploader Uploader instance.
    302                  * @param {Object}            error    Contains code, message and sometimes file and other details.
     416                 * @param {plupload.Uploader} up            Uploader instance.
     417                 * @param {Object}            pluploadError Contains code, message and sometimes file and other details.
    303418                 */
    304419                this.uploader.bind( 'Error', function( up, pluploadError ) {
     
    339454                'GENERIC_ERROR':          pluploadL10n.upload_failed,
    340455                'IO_ERROR':               pluploadL10n.io_error,
    341                 'HTTP_ERROR':             pluploadL10n.http_error,
    342456                'SECURITY_ERROR':         pluploadL10n.security_error,
    343457
    344458                'FILE_SIZE_ERROR': function( file ) {
    345                         return pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
    346                 }
     459                        return pluploadL10n.file_exceeds_size_limit.replace( '%s', file.name );
     460                },
     461
     462                'HTTP_ERROR': function( file ) {
     463                        if ( file.type && file.type.indexOf( 'image/' ) === 0 ) {
     464                                return pluploadL10n.http_error_image;
     465                        }
     466
     467                        return pluploadL10n.http_error;
     468                },
    347469        };
    348470
  • trunk/src/js/media/views/uploader/status.js

    r45524 r45934  
    112112         */
    113113        error: function( error ) {
    114                 this.views.add( '.upload-errors', new wp.media.view.UploaderStatusError({
    115                         filename: this.filename( error.get('file').name ),
    116                         message:  error.get('message')
    117                 }), { at: 0 });
     114                var statusError = new wp.media.view.UploaderStatusError( {
     115                        filename: this.filename( error.get( 'file' ).name ),
     116                        message:  error.get( 'message' )
     117                } );
     118
     119                // Can show additional info here while retrying to create image sub-sizes.
     120                this.views.add( '.upload-errors', statusError, { at: 0 } );
    118121        },
    119122
  • trunk/src/wp-admin/admin-ajax.php

    r45650 r45934  
    106106        'send-attachment-to-editor',
    107107        'save-attachment-order',
     108        'media-create-image-subsizes',
    108109        'heartbeat',
    109110        'get-revision-diffs',
  • trunk/src/wp-admin/includes/ajax-actions.php

    r45932 r45934  
    112112        $taxonomy = sanitize_key( $_GET['tax'] );
    113113        $tax      = get_taxonomy( $taxonomy );
     114
    114115        if ( ! $tax ) {
    115116                wp_die( 0 );
     
    126127                $s = str_replace( $comma, ',', $s );
    127128        }
     129
    128130        if ( false !== strpos( $s, ',' ) ) {
    129131                $s = explode( ',', $s );
    130132                $s = $s[ count( $s ) - 1 ];
    131133        }
     134
    132135        $s = trim( $s );
    133136
     
    194197                                wp_die( -1 );
    195198                        }
     199
    196200                        if ( false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate' ) && function_exists( 'gzdeflate' ) && ! $force_gzip ) {
    197201                                header( 'Content-Encoding: deflate' );
     
    203207                                wp_die( -1 );
    204208                        }
     209
    205210                        echo $out;
    206211                        wp_die();
     
    231236
    232237        include_once( ABSPATH . 'wp-admin/includes/image-edit.php' );
     238
    233239        if ( ! stream_preview_image( $post_id ) ) {
    234240                wp_die( -1 );
     
    296302                )
    297303        ) : array() );
     304
    298305        $exclude_blog_users = ( $type == 'add' ? get_users(
    299306                array(
     
    482489                $status = 'all';
    483490                $parsed = parse_url( $url );
     491
    484492                if ( isset( $parsed['query'] ) ) {
    485493                        parse_str( $parsed['query'], $query_vars );
     494
    486495                        if ( ! empty( $query_vars['comment_status'] ) ) {
    487496                                $status = $query_vars['comment_status'];
    488497                        }
     498
    489499                        if ( ! empty( $query_vars['p'] ) ) {
    490500                                $post_id = (int) $query_vars['p'];
    491501                        }
     502
    492503                        if ( ! empty( $query_vars['comment_type'] ) ) {
    493504                                $type = $query_vars['comment_type'];
     
    551562        $taxonomy = get_taxonomy( substr( $action, 4 ) );
    552563        check_ajax_referer( $action, '_ajax_nonce-add-' . $taxonomy->name );
     564
    553565        if ( ! current_user_can( $taxonomy->cap->edit_terms ) ) {
    554566                wp_die( -1 );
    555567        }
     568
    556569        $names  = explode( ',', $_POST[ 'new' . $taxonomy->name ] );
    557570        $parent = isset( $_POST[ 'new' . $taxonomy->name . '_parent' ] ) ? (int) $_POST[ 'new' . $taxonomy->name . '_parent' ] : 0;
     571
    558572        if ( 0 > $parent ) {
    559573                $parent = 0;
    560574        }
     575
    561576        if ( $taxonomy->name == 'category' ) {
    562577                $post_category = isset( $_POST['post_category'] ) ? (array) $_POST['post_category'] : array();
     
    564579                $post_category = ( isset( $_POST['tax_input'] ) && isset( $_POST['tax_input'][ $taxonomy->name ] ) ) ? (array) $_POST['tax_input'][ $taxonomy->name ] : array();
    565580        }
     581
    566582        $checked_categories = array_map( 'absint', (array) $post_category );
    567583        $popular_ids        = wp_popular_terms_checklist( $taxonomy->name, 0, 10, false );
     
    570586                $cat_name          = trim( $cat_name );
    571587                $category_nicename = sanitize_title( $cat_name );
     588
    572589                if ( '' === $category_nicename ) {
    573590                        continue;
     
    575592
    576593                $cat_id = wp_insert_term( $cat_name, $taxonomy->name, array( 'parent' => $parent ) );
     594
    577595                if ( ! $cat_id || is_wp_error( $cat_id ) ) {
    578596                        continue;
     
    580598                        $cat_id = $cat_id['term_id'];
    581599                }
     600
    582601                $checked_categories[] = $cat_id;
     602
    583603                if ( $parent ) { // Do these all at once in a second
    584604                        continue;
     
    671691
    672692        $comment = get_comment( $id );
     693
    673694        if ( ! $comment ) {
    674695                wp_die( time() );
    675696        }
     697
    676698        if ( ! current_user_can( 'edit_comment', $comment->comment_ID ) ) {
    677699                wp_die( -1 );
     
    680702        check_ajax_referer( "delete-comment_$id" );
    681703        $status = wp_get_comment_status( $comment );
    682 
    683         $delta = -1;
     704        $delta  = -1;
     705
    684706        if ( isset( $_POST['trash'] ) && 1 == $_POST['trash'] ) {
    685707                if ( 'trash' == $status ) {
    686708                        wp_die( time() );
    687709                }
     710
    688711                $r = wp_trash_comment( $comment );
    689712        } elseif ( isset( $_POST['untrash'] ) && 1 == $_POST['untrash'] ) {
     
    691714                        wp_die( time() );
    692715                }
     716
    693717                $r = wp_untrash_comment( $comment );
     718
    694719                if ( ! isset( $_POST['comment_status'] ) || $_POST['comment_status'] != 'trash' ) { // undo trash, not in trash
    695720                        $delta = 1;
     
    699724                        wp_die( time() );
    700725                }
     726
    701727                $r = wp_spam_comment( $comment );
    702728        } elseif ( isset( $_POST['unspam'] ) && 1 == $_POST['unspam'] ) {
     
    704730                        wp_die( time() );
    705731                }
     732
    706733                $r = wp_unspam_comment( $comment );
     734
    707735                if ( ! isset( $_POST['comment_status'] ) || $_POST['comment_status'] != 'spam' ) { // undo spam, not in spam
    708736                        $delta = 1;
     
    717745                _wp_ajax_delete_comment_response( $comment->comment_ID, $delta );
    718746        }
     747
    719748        wp_die( 0 );
    720749}
     
    735764        $taxonomy = ! empty( $_POST['taxonomy'] ) ? $_POST['taxonomy'] : 'post_tag';
    736765        $tag      = get_term( $tag_id, $taxonomy );
     766
    737767        if ( ! $tag || is_wp_error( $tag ) ) {
    738768                wp_die( 1 );
     
    755785
    756786        check_ajax_referer( "delete-bookmark_$id" );
     787
    757788        if ( ! current_user_can( 'manage_links' ) ) {
    758789                wp_die( -1 );
     
    781812        check_ajax_referer( "delete-meta_$id" );
    782813        $meta = get_metadata_by_mid( 'post', $id );
     814
    783815        if ( ! $meta ) {
    784816                wp_die( 1 );
     
    788820                wp_die( -1 );
    789821        }
     822
    790823        if ( delete_meta( $meta->meta_id ) ) {
    791824                wp_die( 1 );
    792825        }
     826
    793827        wp_die( 0 );
    794828}
     
    805839                $action = 'delete-post';
    806840        }
     841
    807842        $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
    808 
    809843        check_ajax_referer( "{$action}_$id" );
     844
    810845        if ( ! current_user_can( 'delete_post', $id ) ) {
    811846                wp_die( -1 );
     
    834869                $action = 'trash-post';
    835870        }
     871
    836872        $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
    837 
    838873        check_ajax_referer( "{$action}_$id" );
     874
    839875        if ( ! current_user_can( 'delete_post', $id ) ) {
    840876                wp_die( -1 );
     
    869905                $action = 'untrash-post';
    870906        }
     907
    871908        wp_ajax_trash_post( $action );
    872909}
     
    883920                $action = 'delete-page';
    884921        }
     922
    885923        $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
    886 
    887924        check_ajax_referer( "{$action}_$id" );
     925
    888926        if ( ! current_user_can( 'delete_page', $id ) ) {
    889927                wp_die( -1 );
     
    907945 */
    908946function wp_ajax_dim_comment() {
    909         $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
    910 
     947        $id      = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0;
    911948        $comment = get_comment( $id );
     949
    912950        if ( ! $comment ) {
    913951                $x = new WP_Ajax_Response(
     
    929967
    930968        $current = wp_get_comment_status( $comment );
     969
    931970        if ( isset( $_POST['new'] ) && $_POST['new'] == $current ) {
    932971                wp_die( time() );
     
    934973
    935974        check_ajax_referer( "approve-comment_$id" );
     975
    936976        if ( in_array( $current, array( 'unapproved', 'spam' ) ) ) {
    937977                $result = wp_set_comment_status( $comment, 'approve', true );
     
    9661006                $action = 'add-link-category';
    9671007        }
     1008
    9681009        check_ajax_referer( $action );
    9691010        $tax = get_taxonomy( 'link_category' );
     1011
    9701012        if ( ! current_user_can( $tax->cap->manage_terms ) ) {
    9711013                wp_die( -1 );
    9721014        }
     1015
    9731016        $names = explode( ',', wp_unslash( $_POST['newcat'] ) );
    9741017        $x     = new WP_Ajax_Response();
     1018
    9751019        foreach ( $names as $cat_name ) {
    9761020                $cat_name = trim( $cat_name );
    9771021                $slug     = sanitize_title( $cat_name );
     1022
    9781023                if ( '' === $slug ) {
    9791024                        continue;
     
    9811026
    9821027                $cat_id = wp_insert_term( $cat_name, 'link_category' );
     1028
    9831029                if ( ! $cat_id || is_wp_error( $cat_id ) ) {
    9841030                        continue;
     
    9861032                        $cat_id = $cat_id['term_id'];
    9871033                }
     1034
    9881035                $cat_name = esc_html( $cat_name );
     1036
    9891037                $x->add(
    9901038                        array(
     
    10231071        if ( ! $tag || is_wp_error( $tag ) ) {
    10241072                $message = __( 'An error has occurred. Please reload the page and try again.' );
     1073
    10251074                if ( is_wp_error( $tag ) && $tag->get_error_message() ) {
    10261075                        $message = $tag->get_error_message();
     
    10581107                )
    10591108        );
     1109
    10601110        $x->add(
    10611111                array(
     
    10651115                )
    10661116        );
     1117
    10671118        $x->send();
    10681119}
     
    10801131        $taxonomy = sanitize_key( $_POST['tax'] );
    10811132        $tax      = get_taxonomy( $taxonomy );
     1133
    10821134        if ( ! $tax ) {
    10831135                wp_die( 0 );
     
    11241176
    11251177        echo $return;
    1126 
    11271178        wp_die();
    11281179}
     
    11391190function wp_ajax_get_comments( $action ) {
    11401191        global $post_id;
     1192
    11411193        if ( empty( $action ) ) {
    11421194                $action = 'get-comments';
    11431195        }
     1196
    11441197        check_ajax_referer( $action );
    11451198
     
    11681221
    11691222        $x = new WP_Ajax_Response();
     1223
    11701224        ob_start();
    11711225        foreach ( $wp_list_table->items as $comment ) {
     
    11841238                )
    11851239        );
     1240
    11861241        $x->send();
    11871242}
     
    12031258        $comment_post_ID = (int) $_POST['comment_post_ID'];
    12041259        $post            = get_post( $comment_post_ID );
     1260
    12051261        if ( ! $post ) {
    12061262                wp_die( -1 );
     
    12181274
    12191275        $user = wp_get_current_user();
     1276
    12201277        if ( $user->exists() ) {
    12211278                $user_ID              = $user->ID;
     
    12251282                $comment_content      = trim( $_POST['content'] );
    12261283                $comment_type         = isset( $_POST['comment_type'] ) ? trim( $_POST['comment_type'] ) : '';
     1284
    12271285                if ( current_user_can( 'unfiltered_html' ) ) {
    12281286                        if ( ! isset( $_POST['_wp_unfiltered_html_comment'] ) ) {
     
    12461304
    12471305        $comment_parent = 0;
     1306
    12481307        if ( isset( $_POST['comment_ID'] ) ) {
    12491308                $comment_parent = absint( $_POST['comment_ID'] );
    12501309        }
     1310
    12511311        $comment_auto_approved = false;
    12521312        $commentdata           = compact( 'comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID' );
     
    12741334
    12751335        $comment = get_comment( $comment_id );
     1336
    12761337        if ( ! $comment ) {
    12771338                wp_die( 1 );
     
    13351396
    13361397        $comment_id = (int) $_POST['comment_ID'];
     1398
    13371399        if ( ! current_user_can( 'edit_comment', $comment_id ) ) {
    13381400                wp_die( -1 );
     
    13531415
    13541416        $comment = get_comment( $comment_id );
     1417
    13551418        if ( empty( $comment->comment_ID ) ) {
    13561419                wp_die( -1 );
     
    13911454        // For performance reasons, we omit some object properties from the checklist.
    13921455        // The following is a hacky way to restore them when adding non-custom items.
    1393 
    13941456        $menu_items_data = array();
     1457
    13951458        foreach ( (array) $_POST['menu-item'] as $menu_item_data ) {
    13961459                if (
     
    14321495        foreach ( (array) $item_ids as $menu_item_id ) {
    14331496                $menu_obj = get_post( $menu_item_id );
     1497
    14341498                if ( ! empty( $menu_obj->ID ) ) {
    14351499                        $menu_obj        = wp_setup_nav_menu_item( $menu_obj );
     
    14551519                        'walker'      => new $walker_class_name,
    14561520                );
     1521
    14571522                echo walk_nav_menu_tree( $menu_items, 0, (object) $args );
    14581523        }
     1524
    14591525        wp_die();
    14601526}
     
    14751541                        wp_die( -1 );
    14761542                }
     1543
    14771544                if ( isset( $_POST['metakeyselect'] ) && '#NONE#' == $_POST['metakeyselect'] && empty( $_POST['metakeyinput'] ) ) {
    14781545                        wp_die( 1 );
     
    14911558
    14921559                        $pid = edit_post( $post_data );
     1560
    14931561                        if ( $pid ) {
    14941562                                if ( is_wp_error( $pid ) ) {
     
    15191587                $pid  = (int) $meta->post_id;
    15201588                $meta = get_object_vars( $meta );
    1521                 $x    = new WP_Ajax_Response(
     1589
     1590                $x = new WP_Ajax_Response(
    15221591                        array(
    15231592                                'what'         => 'meta',
     
    15321601                $key   = wp_unslash( $_POST['meta'][ $mid ]['key'] );
    15331602                $value = wp_unslash( $_POST['meta'][ $mid ]['value'] );
     1603
    15341604                if ( '' == trim( $key ) ) {
    15351605                        wp_die( __( 'Please provide a custom field name.' ) );
    15361606                }
     1607
    15371608                $meta = get_metadata_by_mid( 'post', $mid );
     1609
    15381610                if ( ! $meta ) {
    15391611                        wp_die( 0 ); // if meta doesn't exist
    15401612                }
    1541                 if ( is_protected_meta( $meta->meta_key, 'post' ) || is_protected_meta( $key, 'post' ) ||
     1613
     1614                if (
     1615                        is_protected_meta( $meta->meta_key, 'post' ) || is_protected_meta( $key, 'post' ) ||
    15421616                        ! current_user_can( 'edit_post_meta', $meta->post_id, $meta->meta_key ) ||
    1543                         ! current_user_can( 'edit_post_meta', $meta->post_id, $key ) ) {
     1617                        ! current_user_can( 'edit_post_meta', $meta->post_id, $key )
     1618                ) {
    15441619                        wp_die( -1 );
    15451620                }
     1621
    15461622                if ( $meta->meta_value != $value || $meta->meta_key != $key ) {
    15471623                        $u = update_metadata_by_mid( 'post', $mid, $value, $key );
     
    15851661
    15861662        check_ajax_referer( $action );
     1663
    15871664        if ( ! current_user_can( 'create_users' ) ) {
    15881665                wp_die( -1 );
    15891666        }
     1667
    15901668        $user_id = edit_user();
     1669
    15911670        if ( ! $user_id ) {
    15921671                wp_die( 0 );
     
    16001679                $x->send();
    16011680        }
    1602         $user_object = get_userdata( $user_id );
    1603 
     1681
     1682        $user_object   = get_userdata( $user_id );
    16041683        $wp_list_table = _get_list_table( 'WP_Users_List_Table' );
    16051684
     
    18001879                wp_die( -1 );
    18011880        }
     1881
    18021882        check_ajax_referer( 'add-menu_item', 'menu-settings-column-nonce' );
     1883
    18031884        if ( ! isset( $_POST['menu-locations'] ) ) {
    18041885                wp_die( 0 );
    18051886        }
     1887
    18061888        set_theme_mod( 'nav_menu_locations', array_map( 'absint', $_POST['menu-locations'] ) );
    18071889        wp_die( 1 );
     
    19582040                $data['comment_status'] = 'closed';
    19592041        }
     2042
    19602043        if ( empty( $data['ping_status'] ) ) {
    19612044                $data['ping_status'] = 'closed';
     
    20132096        $taxonomy = sanitize_key( $_POST['taxonomy'] );
    20142097        $tax      = get_taxonomy( $taxonomy );
     2098
    20152099        if ( ! $tax ) {
    20162100                wp_die( 0 );
     
    20332117
    20342118        $updated = wp_update_term( $id, $taxonomy, $_POST );
     2119
    20352120        if ( $updated && ! is_wp_error( $updated ) ) {
    20362121                $tag = get_term( $updated['term_id'], $taxonomy );
     
    20472132                wp_die( __( 'Item not updated.' ) );
    20482133        }
     2134
    20492135        $level  = 0;
    20502136        $parent = $tag->parent;
     2137
    20512138        while ( $parent > 0 ) {
    20522139                $parent_tag = get_term( $parent, $taxonomy );
     
    20542141                $level++;
    20552142        }
     2143
    20562144        $wp_list_table->single_row( $tag, $level );
    20572145        wp_die();
     
    20772165                'posts_per_page' => 50,
    20782166        );
     2167
    20792168        if ( '' !== $s ) {
    20802169                $args['s'] = $s;
     
    21422231        if ( is_array( $_POST['sidebars'] ) ) {
    21432232                $sidebars = array();
     2233
    21442234                foreach ( wp_unslash( $_POST['sidebars'] ) as $key => $val ) {
    21452235                        $sb = array();
     2236
    21462237                        if ( ! empty( $val ) ) {
    21472238                                $val = explode( ',', $val );
     2239
    21482240                                foreach ( $val as $k => $v ) {
    21492241                                        if ( strpos( $v, 'widget-' ) === false ) {
     
    21562248                        $sidebars[ $key ] = $sb;
    21572249                }
     2250
    21582251                wp_set_sidebars_widgets( $sidebars );
    21592252                wp_die( 1 );
     
    23192412
    23202413        wp_die();
     2414}
     2415
     2416/**
     2417 * Ajax handler for creating missing image sub-sizes for just uploaded images.
     2418 *
     2419 * @since 5.3.0
     2420 */
     2421function wp_ajax_media_create_image_subsizes() {
     2422        check_ajax_referer( 'media-form' );
     2423
     2424        if ( ! current_user_can( 'upload_files' ) ) {
     2425                wp_send_json_error( array( 'message' => __( 'Sorry, you are not allowed to upload files.' ) ) );
     2426        }
     2427
     2428        // Using Plupload `file.id` as ref.
     2429        if ( ! empty( $_POST['_wp_temp_image_ref'] ) ) {
     2430                $image_ref = preg_replace( '/[^a-zA-Z0-9_]/', '', $_POST['_wp_temp_image_ref'] );
     2431        } else {
     2432                wp_send_json_error( array( 'message' => __( 'Invalid file reference.' ) ) );
     2433        }
     2434
     2435        // Uploading of images usually fails while creating the sub-sizes, either because of a timeout or out of memory.
     2436        // At this point the file has been uploaded and an attachment post created, but because of the PHP fatal error
     2437        // the cliend doesn't know the attachment ID yet.
     2438        // To be able to find the new attachment_id in these cases we temporarily store an upload reference sent by the client
     2439        // in the original upload request. It is used to save a transient with the attachment_id as value.
     2440        // That reference currently is Plupload's `file.id` but can be any sufficiently random alpha-numeric string.
     2441        $attachment_id = get_transient( '_wp_temp_image_ref:' . $image_ref );
     2442
     2443        if ( empty( $attachment_id ) ) {
     2444                wp_send_json_error( array( 'message' => __( 'Upload failed. Please reload and try again.' ) ) );
     2445        }
     2446
     2447        if ( ! empty( $_POST['_wp_upload_failed_cleanup'] ) ) {
     2448                // Upload failed. Cleanup.
     2449                if ( wp_attachment_is_image( $attachment_id ) ) {
     2450                        $attachment = get_post( $attachment_id );
     2451
     2452                        // Posted at most 10 min ago.
     2453                        if ( $attachment && ( time() - strtotime( $attachment->post_date_gmt ) < 600 ) ) {
     2454                                /**
     2455                                 * Runs when an image upload fails during the post-processing phase,
     2456                                 * and the newly created attachment post is about to be deleted.
     2457                                 *
     2458                                 * @since 5.3.0
     2459                                 *
     2460                                 * @param int $attachment_id The attachment post ID.
     2461                                 */
     2462                                do_action( 'wp_upload_failed_cleanup', $attachment_id );
     2463
     2464                                wp_delete_attachment( $attachment_id, true );
     2465                                wp_send_json_success();
     2466                        }
     2467                }
     2468        }
     2469
     2470        // This can still be pretty slow and cause timeout or out of memory errors.
     2471        // The js that handles the response would need to also handle HTTP 500 errors.
     2472        wp_update_image_subsizes( $attachment_id );
     2473
     2474        if ( ! empty( $_POST['_legasy_support'] ) ) {
     2475                // The old (inline) uploader. Only needs the attachment_id.
     2476                $response = array( 'id' => $attachment_id );
     2477        } else {
     2478                // Media modal and Media Library grid view.
     2479                $response = wp_prepare_attachment_for_js( $attachment_id );
     2480
     2481                if ( ! $response ) {
     2482                        wp_send_json_error( array( 'message' => __( 'Upload failed.' ) ) );
     2483                }
     2484        }
     2485
     2486        // At this point the image has been uploaded successfully.
     2487        delete_transient( '_wp_temp_image_ref:' . $image_ref );
     2488
     2489        wp_send_json_success( $response );
    23212490}
    23222491
     
    23502519        if ( isset( $_REQUEST['post_id'] ) ) {
    23512520                $post_id = $_REQUEST['post_id'];
     2521
    23522522                if ( ! current_user_can( 'edit_post', $post_id ) ) {
    23532523                        echo wp_json_encode(
     
    23762546        if ( isset( $post_data['context'] ) && in_array( $post_data['context'], array( 'custom-header', 'custom-background' ) ) ) {
    23772547                $wp_filetype = wp_check_filetype_and_ext( $_FILES['async-upload']['tmp_name'], $_FILES['async-upload']['name'] );
     2548
    23782549                if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) ) {
    23792550                        echo wp_json_encode(
     
    24392610function wp_ajax_image_editor() {
    24402611        $attachment_id = intval( $_POST['postid'] );
     2612
    24412613        if ( empty( $attachment_id ) || ! current_user_can( 'edit_post', $attachment_id ) ) {
    24422614                wp_die( -1 );
     
    26502822                wp_die( 0 );
    26512823        }
     2824
    26522825        $post_id = (int) $_POST['post_ID'];
    26532826        $post    = get_post( $post_id );
     2827
    26542828        if ( ! $post ) {
    26552829                wp_die( 0 );
     
    26632837
    26642838        $active_lock = array_map( 'absint', explode( ':', $_POST['active_post_lock'] ) );
     2839
    26652840        if ( $active_lock[1] != get_current_user_id() ) {
    26662841                wp_die( 0 );
     
    26872862function wp_ajax_dismiss_wp_pointer() {
    26882863        $pointer = $_POST['pointer'];
     2864
    26892865        if ( $pointer != sanitize_key( $pointer ) ) {
    26902866                wp_die( 0 );
     
    27672943                'monthnum',
    27682944        );
     2945
    27692946        foreach ( get_taxonomies_for_attachments( 'objects' ) as $t ) {
    27702947                if ( $t->query_var && isset( $query[ $t->query_var ] ) ) {
     
    27752952        $query              = array_intersect_key( $query, array_flip( $keys ) );
    27762953        $query['post_type'] = 'attachment';
    2777         if ( MEDIA_TRASH
    2778                 && ! empty( $_REQUEST['query']['post_status'] )
    2779                 && 'trash' === $_REQUEST['query']['post_status'] ) {
     2954
     2955        if (
     2956                MEDIA_TRASH &&
     2957                ! empty( $_REQUEST['query']['post_status'] ) &&
     2958                'trash' === $_REQUEST['query']['post_status']
     2959        ) {
    27802960                $query['post_status'] = 'trash';
    27812961        } else {
     
    28703050                $changed = false;
    28713051                $id3data = wp_get_attachment_metadata( $post['ID'] );
     3052
    28723053                if ( ! is_array( $id3data ) ) {
    28733054                        $changed = true;
    28743055                        $id3data = array();
    28753056                }
     3057
    28763058                foreach ( wp_get_attachment_id3_keys( (object) $post, 'edit' ) as $key => $label ) {
    28773059                        if ( isset( $changes[ $key ] ) ) {
     
    29133095                wp_send_json_error();
    29143096        }
     3097
    29153098        $attachment_data = $_REQUEST['attachments'][ $id ];
    29163099
     
    29443127
    29453128        $attachment = wp_prepare_attachment_for_js( $id );
     3129
    29463130        if ( ! $attachment ) {
    29473131                wp_send_json_error();
     
    29823166                        continue;
    29833167                }
     3168
    29843169                $attachment = get_post( $attachment_id );
     3170
    29853171                if ( ! $attachment ) {
    29863172                        continue;
    29873173                }
     3174
    29883175                if ( 'attachment' != $attachment->post_type ) {
    29893176                        continue;
     
    30293216                // If this attachment is unattached, attach it. Primarily a back compat thing.
    30303217                $insert_into_post_id = intval( $_POST['post_id'] );
     3218
    30313219                if ( 0 == $post->post_parent && $insert_into_post_id ) {
    30323220                        wp_update_post(
     
    33473535
    33483536        $update_php = network_admin_url( 'update.php?action=install-theme' );
     3537
    33493538        foreach ( $api->themes as &$theme ) {
    33503539                $theme->install_url = add_query_arg(
     
    33913580                $theme->version     = wp_kses( $theme->version, $themes_allowedtags );
    33923581                $theme->description = wp_kses( $theme->description, $themes_allowedtags );
    3393                 $theme->stars       = wp_star_rating(
     3582
     3583                $theme->stars = wp_star_rating(
    33943584                        array(
    33953585                                'rating' => $theme->rating,
     
    33993589                        )
    34003590                );
     3591
    34013592                $theme->num_ratings = number_format_i18n( $theme->num_ratings );
    34023593                $theme->preview_url = set_url_scheme( $theme->preview_url );
     
    34223613                wp_send_json_error();
    34233614        }
     3615
    34243616        $post_id = isset( $_POST['post_ID'] ) ? intval( $_POST['post_ID'] ) : 0;
     3617
    34253618        if ( $post_id > 0 ) {
    34263619                $post = get_post( $post_id );
     3620
    34273621                if ( ! $post || ! current_user_can( 'edit_post', $post->ID ) ) {
    34283622                        wp_send_json_error();
     
    34373631        preg_match( '/' . get_shortcode_regex() . '/s', $shortcode, $matches );
    34383632        $atts = shortcode_parse_atts( $matches[3] );
     3633
    34393634        if ( ! empty( $matches[5] ) ) {
    34403635                $url = $matches[5];
     
    34943689                $styles     = '';
    34953690                $mce_styles = wpview_media_sandbox_styles();
     3691
    34963692                foreach ( $mce_styles as $style ) {
    34973693                        $styles .= sprintf( '<link rel="stylesheet" href="%s"/>', $style );
     
    35013697
    35023698                global $wp_scripts;
     3699
    35033700                if ( ! empty( $wp_scripts ) ) {
    35043701                        $wp_scripts->done = array();
    35053702                }
     3703
    35063704                ob_start();
    35073705                wp_print_scripts( array( 'mediaelement-vimeo', 'wp-mediaelement' ) );
     
    36183816function wp_ajax_destroy_sessions() {
    36193817        $user = get_userdata( (int) $_POST['user_id'] );
     3818
    36203819        if ( $user ) {
    36213820                if ( ! current_user_can( 'edit_user', $user->ID ) ) {
     
    36573856
    36583857        check_ajax_referer( 'image_editor-' . $attachment_id, 'nonce' );
     3858
    36593859        if ( empty( $attachment_id ) || ! current_user_can( 'edit_post', $attachment_id ) ) {
    36603860                wp_send_json_error();
     
    40474247        // Check filesystem credentials. `delete_theme()` will bail otherwise.
    40484248        $url = wp_nonce_url( 'themes.php?action=delete&stylesheet=' . urlencode( $stylesheet ), 'delete-theme_' . $stylesheet );
     4249
    40494250        ob_start();
    40504251        $credentials = request_filesystem_credentials( $url );
    40514252        ob_end_clean();
     4253
    40524254        if ( false === $credentials || ! WP_Filesystem( $credentials ) ) {
    40534255                global $wp_filesystem;
     
    43404542        // Check filesystem credentials. `delete_plugins()` will bail otherwise.
    43414543        $url = wp_nonce_url( 'plugins.php?action=delete-selected&verify-delete=1&checked[]=' . $plugin, 'bulk-plugins' );
     4544
    43424545        ob_start();
    43434546        $credentials = request_filesystem_credentials( $url );
    43444547        ob_end_clean();
     4548
    43454549        if ( false === $credentials || ! WP_Filesystem( $credentials ) ) {
    43464550                global $wp_filesystem;
     
    44824686function wp_ajax_edit_theme_plugin_file() {
    44834687        $r = wp_edit_theme_plugin_file( wp_unslash( $_POST ) ); // Validation of args is done in wp_edit_theme_plugin_file().
     4688
    44844689        if ( is_wp_error( $r ) ) {
    44854690                wp_send_json_error(
     
    45114716                wp_send_json_error( __( 'Missing request ID.' ) );
    45124717        }
     4718
    45134719        $request_id = (int) $_POST['id'];
    45144720
     
    45384744                wp_send_json_error( __( 'Missing exporter index.' ) );
    45394745        }
     4746
    45404747        $exporter_index = (int) $_POST['exporter'];
    45414748
     
    45434750                wp_send_json_error( __( 'Missing page index.' ) );
    45444751        }
     4752
    45454753        $page = (int) $_POST['page'];
    45464754
     
    45964804                        );
    45974805                }
     4806
    45984807                if ( ! array_key_exists( 'exporter_friendly_name', $exporter ) ) {
    45994808                        wp_send_json_error(
     
    46114820                        );
    46124821                }
     4822
    46134823                if ( ! is_callable( $exporter['callback'] ) ) {
    46144824                        wp_send_json_error(
     
    46314841                        );
    46324842                }
     4843
    46334844                if ( ! array_key_exists( 'data', $response ) ) {
    46344845                        wp_send_json_error(
     
    46374848                        );
    46384849                }
     4850
    46394851                if ( ! is_array( $response['data'] ) ) {
    46404852                        wp_send_json_error(
     
    46434855                        );
    46444856                }
     4857
    46454858                if ( ! array_key_exists( 'done', $response ) ) {
    46464859                        wp_send_json_error(
  • trunk/src/wp-admin/includes/image.php

    r45871 r45934  
    132132 *
    133133 * @param int $attachment_id The image attachment post ID.
    134  * @return array The updated image meta data array.
     134 * @return array|WP_Error The updated image meta data array or WP_Error object
     135 *                        if both the image meta and the attached file are missing.
    135136 */
    136137function wp_update_image_subsizes( $attachment_id ) {
     138        $image_meta = wp_get_attachment_metadata( $attachment_id );
     139        $image_file = get_attached_file( $attachment_id );
     140
     141        if ( empty( $image_meta ) || ! is_array( $image_meta ) ) {
     142                // Previously failed upload?
     143                // If there is an uploaded file, make all sub-sizes and generate all of the attachment meta.
     144                if ( ! empty( $image_file ) ) {
     145                        return wp_create_image_subsizes( $image_file, array(), $attachment_id );
     146                } else {
     147                        return new WP_Error( 'invalid_attachment', __( 'The attached file cannot be found.' ) );
     148                }
     149        }
     150
    137151        $missing_sizes = wp_get_missing_image_subsizes( $attachment_id );
    138         $image_meta    = wp_get_attachment_metadata( $attachment_id );
    139152
    140153        if ( empty( $missing_sizes ) ) {
    141154                return $image_meta;
    142155        }
    143 
    144         $image_file = get_attached_file( $attachment_id );
    145156
    146157        // This also updates the image meta.
  • trunk/src/wp-admin/includes/media.php

    r45932 r45934  
    8181        if ( ! empty( $tabs ) ) {
    8282                echo "<ul id='sidemenu'>\n";
     83
    8384                if ( isset( $redir_tab ) && array_key_exists( $redir_tab, $tabs ) ) {
    8485                        $current = $redir_tab;
     
    109110                        echo "\t<li id='" . esc_attr( "tab-$callback" ) . "'>$link</li>\n";
    110111                }
     112
    111113                echo "</ul>\n";
    112114        }
     
    266268function media_send_to_editor( $html ) {
    267269        ?>
    268 <script type="text/javascript">
    269 var win = window.dialogArguments || opener || parent || top;
    270 win.send_to_editor( <?php echo wp_json_encode( $html ); ?> );
    271 </script>
     270        <script type="text/javascript">
     271        var win = window.dialogArguments || opener || parent || top;
     272        win.send_to_editor( <?php echo wp_json_encode( $html ); ?> );
     273        </script>
    272274        <?php
    273275        exit;
     
    287289 */
    288290function media_handle_upload( $file_id, $post_id, $post_data = array(), $overrides = array( 'test_form' => false ) ) {
    289 
    290291        $time = current_time( 'mysql' );
    291292        $post = get_post( $post_id );
     293
    292294        if ( $post ) {
    293295                // The post date doesn't usually matter for pages, so don't backdate this upload.
     
    307309        $name = wp_basename( $name, ".$ext" );
    308310
    309         $url     = $file['url'];
    310         $type    = $file['type'];
    311         $file    = $file['file'];
    312         $title   = sanitize_text_field( $name );
    313         $content = '';
    314         $excerpt = '';
     311        $url       = $file['url'];
     312        $type      = $file['type'];
     313        $file      = $file['file'];
     314        $title     = sanitize_text_field( $name );
     315        $content   = '';
     316        $excerpt   = '';
     317        $image_ref = false;
    315318
    316319        if ( preg_match( '#^audio#', $type ) ) {
     
    357360                if ( ! empty( $meta['track_number'] ) ) {
    358361                        $track_number = explode( '/', $meta['track_number'] );
     362
    359363                        if ( isset( $track_number[1] ) ) {
    360364                                /* translators: Audio file track information. 1: Audio track number, 2: Total audio tracks. */
     
    373377                // Use image exif/iptc data for title and caption defaults if possible.
    374378        } elseif ( 0 === strpos( $type, 'image/' ) ) {
     379                // Image file reference passed by the uploader.
     380                if ( ! empty( $_POST['_wp_temp_image_ref'] ) ) {
     381                        $image_ref = preg_replace( '/[^a-zA-Z0-9_]/', '', $_POST['_wp_temp_image_ref'] );
     382                }
     383
    375384                $image_meta = wp_read_image_metadata( $file );
     385
    376386                if ( $image_meta ) {
    377387                        if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
     
    402412
    403413        // Save the data
    404         $id = wp_insert_attachment( $attachment, $file, $post_id, true );
    405         if ( ! is_wp_error( $id ) ) {
    406                 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
    407         }
    408 
    409         return $id;
    410 
     414        $attachment_id = wp_insert_attachment( $attachment, $file, $post_id, true );
     415
     416        if ( ! is_wp_error( $attachment_id ) ) {
     417                // If an image, keep the upload reference until all image sub-sizes are created.
     418                if ( $image_ref ) {
     419                        set_transient( '_wp_temp_image_ref:' . $image_ref, $attachment_id, HOUR_IN_SECONDS );
     420                }
     421
     422                // The image sub-sizes are created during wp_generate_attachment_metadata().
     423                // This is generally slow and may cause timeouts or out of memory errors.
     424                wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
     425
     426                // At this point the image is uploaded successfully even if there were specific errors or some sub-sizes were not created.
     427                // The transient is not needed any more.
     428                if ( $image_ref ) {
     429                        delete_transient( '_wp_temp_image_ref:' . $image_ref );
     430                }
     431        }
     432
     433        return $attachment_id;
    411434}
    412435
     
    427450        $time = current_time( 'mysql' );
    428451        $post = get_post( $post_id );
     452
    429453        if ( $post ) {
    430454                if ( substr( $post->post_date, 0, 4 ) > 0 ) {
     
    434458
    435459        $file = wp_handle_sideload( $file_array, $overrides, $time );
     460
    436461        if ( isset( $file['error'] ) ) {
    437462                return new WP_Error( 'upload_error', $file['error'] );
     
    446471        // Use image exif/iptc data for title and caption defaults if possible.
    447472        $image_meta = wp_read_image_metadata( $file );
     473
    448474        if ( $image_meta ) {
    449475                if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
    450476                        $title = $image_meta['title'];
    451477                }
     478
    452479                if ( trim( $image_meta['caption'] ) ) {
    453480                        $content = $image_meta['caption'];
     
    475502
    476503        // Save the attachment metadata
    477         $id = wp_insert_attachment( $attachment, $file, $post_id, true );
    478         if ( ! is_wp_error( $id ) ) {
    479                 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
    480         }
    481 
    482         return $id;
     504        $attachment_id = wp_insert_attachment( $attachment, $file, $post_id, true );
     505
     506        if ( ! is_wp_error( $attachment_id ) ) {
     507                wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
     508        }
     509
     510        return $attachment_id;
    483511}
    484512
     
    496524        _wp_admin_html_begin();
    497525        ?>
    498 <title><?php bloginfo( 'name' ); ?> &rsaquo; <?php _e( 'Uploads' ); ?> &#8212; <?php _e( 'WordPress' ); ?></title>
     526        <title><?php bloginfo( 'name' ); ?> &rsaquo; <?php _e( 'Uploads' ); ?> &#8212; <?php _e( 'WordPress' ); ?></title>
    499527        <?php
    500528
    501529        wp_enqueue_style( 'colors' );
    502530        // Check callback name for 'media'
    503         if ( ( is_array( $content_func ) && ! empty( $content_func[1] ) && 0 === strpos( (string) $content_func[1], 'media' ) )
    504         || ( ! is_array( $content_func ) && 0 === strpos( $content_func, 'media' ) ) ) {
     531        if (
     532                ( is_array( $content_func ) && ! empty( $content_func[1] ) && 0 === strpos( (string) $content_func[1], 'media' ) ) ||
     533                ( ! is_array( $content_func ) && 0 === strpos( $content_func, 'media' ) )
     534        ) {
    505535                wp_enqueue_style( 'deprecated-media' );
    506536        }
    507537        wp_enqueue_style( 'ie' );
     538
    508539        ?>
    509 <script type="text/javascript">
    510 addLoadEvent = function(func){if(typeof jQuery!="undefined")jQuery(document).ready(func);else if(typeof wpOnload!='function'){wpOnload=func;}else{var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}};
    511 var ajaxurl = '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>', pagenow = 'media-upload-popup', adminpage = 'media-upload-popup',
    512 isRtl = <?php echo (int) is_rtl(); ?>;
    513 </script>
     540        <script type="text/javascript">
     541        addLoadEvent = function(func){if(typeof jQuery!="undefined")jQuery(document).ready(func);else if(typeof wpOnload!='function'){wpOnload=func;}else{var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}};
     542        var ajaxurl = '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>', pagenow = 'media-upload-popup', adminpage = 'media-upload-popup',
     543        isRtl = <?php echo (int) is_rtl(); ?>;
     544        </script>
    514545        <?php
    515546        /** This action is documented in wp-admin/admin-header.php */
     
    563594
    564595        $body_id_attr = '';
     596
    565597        if ( isset( $GLOBALS['body_id'] ) ) {
    566598                $body_id_attr = ' id="' . $GLOBALS['body_id'] . '"';
    567599        }
     600
    568601        ?>
    569 </head>
    570 <body<?php echo $body_id_attr; ?> class="wp-core-ui no-js">
    571 <script type="text/javascript">
    572 document.body.className = document.body.className.replace('no-js', 'js');
    573 </script>
     602        </head>
     603        <body<?php echo $body_id_attr; ?> class="wp-core-ui no-js">
     604        <script type="text/javascript">
     605        document.body.className = document.body.className.replace('no-js', 'js');
     606        </script>
    574607        <?php
     608
    575609        $args = func_get_args();
    576610        $args = array_slice( $args, 1 );
     
    579613        /** This action is documented in wp-admin/admin-footer.php */
    580614        do_action( 'admin_print_footer_scripts' );
     615
    581616        ?>
    582 <script type="text/javascript">if(typeof wpOnload=='function')wpOnload();</script>
    583 </body>
    584 </html>
     617        <script type="text/javascript">if(typeof wpOnload=='function')wpOnload();</script>
     618        </body>
     619        </html>
    585620        <?php
    586621}
     
    602637
    603638        $post = get_post();
     639
    604640        if ( ! $post && ! empty( $GLOBALS['post_ID'] ) ) {
    605641                $post = $GLOBALS['post_ID'];
    606642        }
    607643
    608         wp_enqueue_media(
    609                 array(
    610                         'post' => $post,
    611                 )
    612         );
     644        wp_enqueue_media( array( 'post' => $post ) );
    613645
    614646        $img = '<span class="wp-media-buttons-icon"></span> ';
    615647
    616648        $id_attribute = $instance === 1 ? ' id="insert-media-button"' : '';
     649
    617650        printf(
    618651                '<button type="button"%s class="button insert-media add_media" data-editor="%s">%s</button>',
     
    621654                $img . __( 'Add Media' )
    622655        );
     656
    623657        /**
    624658         * Filters the legacy (pre-3.5.0) media buttons.
     
    710744                                $post['post_content'] = $attachment['post_content'];
    711745                        }
     746
    712747                        if ( isset( $attachment['post_title'] ) ) {
    713748                                $post['post_title'] = $attachment['post_title'];
    714749                        }
     750
    715751                        if ( isset( $attachment['post_excerpt'] ) ) {
    716752                                $post['post_excerpt'] = $attachment['post_excerpt'];
    717753                        }
     754
    718755                        if ( isset( $attachment['menu_order'] ) ) {
    719756                                $post['menu_order'] = $attachment['menu_order'];
     
    740777                        if ( isset( $attachment['image_alt'] ) ) {
    741778                                $image_alt = wp_unslash( $attachment['image_alt'] );
     779
    742780                                if ( $image_alt != get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) {
    743781                                        $image_alt = wp_strip_all_tags( $image_alt, true );
     
    772810                </script>
    773811                <?php
     812
    774813                exit;
    775814        }
     
    777816        if ( isset( $send_id ) ) {
    778817                $attachment = wp_unslash( $_POST['attachments'][ $send_id ] );
    779 
    780                 $html = isset( $attachment['post_title'] ) ? $attachment['post_title'] : '';
     818                $html       = isset( $attachment['post_title'] ) ? $attachment['post_title'] : '';
     819
    781820                if ( ! empty( $attachment['url'] ) ) {
    782821                        $rel = '';
     822
    783823                        if ( strpos( $attachment['url'], 'attachment_id' ) || get_attachment_link( $send_id ) == $attachment['url'] ) {
    784824                                $rel = " rel='attachment wp-att-" . esc_attr( $send_id ) . "'";
    785825                        }
     826
    786827                        $html = "<a href='{$attachment['url']}'$rel>$html</a>";
    787828                }
     
    799840                 */
    800841                $html = apply_filters( 'media_send_to_editor', $html, $send_id, $attachment );
     842
    801843                return media_send_to_editor( $html );
    802844        }
     
    821863                $id = media_handle_upload( 'async-upload', $_REQUEST['post_id'] );
    822864                unset( $_FILES );
     865
    823866                if ( is_wp_error( $id ) ) {
    824867                        $errors['upload_error'] = $id;
     
    829872        if ( ! empty( $_POST['insertonlybutton'] ) ) {
    830873                $src = $_POST['src'];
     874
    831875                if ( ! empty( $src ) && ! strpos( $src, '://' ) ) {
    832876                        $src = "http://$src";
     
    845889                        $type = 'file';
    846890                        $ext  = preg_replace( '/^.+?\.([^.]+)$/', '$1', $src );
     891
    847892                        if ( $ext ) {
    848893                                $ext_type = wp_ext2type( $ext );
     
    868913                        $align = '';
    869914                        $alt   = esc_attr( wp_unslash( $_POST['alt'] ) );
     915
    870916                        if ( isset( $_POST['align'] ) ) {
    871917                                $align = esc_attr( wp_unslash( $_POST['align'] ) );
    872918                                $class = " class='align$align'";
    873919                        }
     920
    874921                        if ( ! empty( $src ) ) {
    875922                                $html = "<img src='" . esc_url( $src ) . "' alt='$alt'$class />";
     
    896943                $errors['upload_notice'] = __( 'Saved.' );
    897944                wp_enqueue_script( 'admin-gallery' );
     945
    898946                return wp_iframe( 'media_upload_gallery_form', $errors );
    899947
     
    904952                        return $return;
    905953                }
     954
    906955                if ( is_array( $return ) ) {
    907956                        $errors = $return;
     
    911960        if ( isset( $_GET['tab'] ) && $_GET['tab'] == 'type_url' ) {
    912961                $type = 'image';
     962
    913963                if ( isset( $_GET['type'] ) && in_array( $_GET['type'], array( 'video', 'audio', 'file' ) ) ) {
    914964                        $type = $_GET['type'];
    915965                }
     966
    916967                return wp_iframe( 'media_upload_type_url_form', $type, $errors, $id );
    917968        }
     
    938989                // Set variables for storage, fix file filename for query strings.
    939990                preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
     991
    940992                if ( ! $matches ) {
    941993                        return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL' ) );
     
    9761028                $alt  = isset( $desc ) ? esc_attr( $desc ) : '';
    9771029                $html = "<img src='$src' alt='$alt' />";
     1030
    9781031                return $html;
    9791032        } else {
     
    9981051                        return $return;
    9991052                }
     1053
    10001054                if ( is_array( $return ) ) {
    10011055                        $errors = $return;
     
    10161070function media_upload_library() {
    10171071        $errors = array();
     1072
    10181073        if ( ! empty( $_POST ) ) {
    10191074                $return = media_upload_form_handler();
     
    10511106                'right'  => __( 'Right' ),
    10521107        );
     1108
    10531109        if ( ! array_key_exists( (string) $checked, $alignments ) ) {
    10541110                $checked = 'none';
     
    10561112
    10571113        $out = array();
     1114
    10581115        foreach ( $alignments as $name => $label ) {
    10591116                $name  = esc_attr( $name );
     
    10621119                        " /><label for='image-align-{$name}-{$post->ID}' class='align image-align-{$name}-label'>$label</label>";
    10631120        }
     1121
    10641122        return join( "\n", $out );
    10651123}
     
    10961154                $check = get_user_setting( 'imgsize', 'medium' );
    10971155        }
     1156
    10981157        $out = array();
    10991158
     
    11611220
    11621221        $url = '';
     1222
    11631223        if ( $url_type == 'file' ) {
    11641224                $url = $file;
     
    12681328function image_media_send_to_editor( $html, $attachment_id, $attachment ) {
    12691329        $post = get_post( $attachment_id );
     1330
    12701331        if ( substr( $post->post_mime_type, 0, 5 ) == 'image' ) {
    12711332                $url   = $attachment['url'];
     
    12941355                $post = get_post( $post );
    12951356        }
     1357
    12961358        if ( is_array( $post ) ) {
    12971359                $post = new WP_Post( (object) $post );
     
    13391401        foreach ( get_attachment_taxonomies( $post ) as $taxonomy ) {
    13401402                $t = (array) get_taxonomy( $taxonomy );
     1403
    13411404                if ( ! $t['public'] || ! $t['show_ui'] ) {
    13421405                        continue;
    13431406                }
     1407
    13441408                if ( empty( $t['label'] ) ) {
    13451409                        $t['label'] = $taxonomy;
    13461410                }
     1411
    13471412                if ( empty( $t['args'] ) ) {
    13481413                        $t['args'] = array();
     
    13501415
    13511416                $terms = get_object_term_cache( $post->ID, $taxonomy );
     1417
    13521418                if ( false === $terms ) {
    13531419                        $terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] );
     
    13591425                        $values[] = $term->slug;
    13601426                }
     1427
    13611428                $t['value'] = join( ', ', $values );
    13621429
     
    13711438        if ( substr( $post->post_mime_type, 0, 5 ) == 'image' ) {
    13721439                $alt = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
     1440
    13731441                if ( empty( $alt ) ) {
    13741442                        $alt = '';
     
    14251493function get_media_items( $post_id, $errors ) {
    14261494        $attachments = array();
     1495
    14271496        if ( $post_id ) {
    14281497                $post = get_post( $post_id );
     1498
    14291499                if ( $post && $post->post_type == 'attachment' ) {
    14301500                        $attachments = array( $post->ID => $post );
     
    14521522                        continue;
    14531523                }
     1524
    14541525                $item = get_media_item( $id, array( 'errors' => isset( $errors[ $id ] ) ? $errors[ $id ] : null ) );
     1526
    14551527                if ( $item ) {
    14561528                        $output .= "\n<div id='media-item-$id' class='media-item child-of-$attachment->post_parent preloaded'><div class='progress hidden'><div class='bar'></div></div><div id='media-upload-error-$id' class='hidden'></div><div class='filename hidden'></div>$item\n</div>";
     
    14801552        if ( $attachment_id ) {
    14811553                $thumb_url = wp_get_attachment_image_src( $attachment_id, 'thumbnail', true );
     1554
    14821555                if ( $thumb_url ) {
    14831556                        $thumb_url = $thumb_url[0];
     
    15261599                $class        = empty( $parsed_args['errors'] ) ? 'startclosed' : 'startopen';
    15271600                $toggle_links = "
    1528         <a class='toggle describe-toggle-on' href='#'>$toggle_on</a>
    1529         <a class='toggle describe-toggle-off' href='#'>$toggle_off</a>";
     1601                <a class='toggle describe-toggle-on' href='#'>$toggle_on</a>
     1602                <a class='toggle describe-toggle-off' href='#'>$toggle_off</a>";
    15301603        } else {
    15311604                $class        = '';
     
    15541627        $media_dims = '';
    15551628        $meta       = wp_get_attachment_metadata( $post->ID );
     1629
    15561630        if ( isset( $meta['width'], $meta['height'] ) ) {
    15571631                $media_dims .= "<span id='media-dims-$post->ID'>{$meta['width']}&nbsp;&times;&nbsp;{$meta['height']}</span> ";
     
    15691643
    15701644        $image_edit_button = '';
     1645
    15711646        if ( wp_attachment_is_image( $post->ID ) && wp_image_editor_supports( array( 'mime_type' => $post->post_mime_type ) ) ) {
    15721647                $nonce             = wp_create_nonce( "image_editor-$post->ID" );
     
    15771652
    15781653        $item = "
    1579         $type_html
    1580         $toggle_links
    1581         $order
    1582         $display_title
    1583         <table class='slidetoggle describe $class'>
    1584                 <thead class='media-item-info' id='media-head-$post->ID'>
    1585                 <tr>
     1654                $type_html
     1655                $toggle_links
     1656                $order
     1657                $display_title
     1658                <table class='slidetoggle describe $class'>
     1659                        <thead class='media-item-info' id='media-head-$post->ID'>
     1660                        <tr>
    15861661                        <td class='A1B1' id='thumbnail-head-$post->ID'>
    15871662                        <p><a href='$attachment_url' target='_blank'><img class='thumbnail' src='$thumb_url' alt='' /></a></p>
     
    15921667                        <p><strong>" . __( 'File type:' ) . "</strong> $post->post_mime_type</p>
    15931668                        <p><strong>" . __( 'Upload date:' ) . '</strong> ' . mysql2date( __( 'F j, Y' ), $post->post_date ) . '</p>';
     1669
    15941670        if ( ! empty( $media_dims ) ) {
    15951671                $item .= '<p><strong>' . __( 'Dimensions:' ) . "</strong> $media_dims</p>\n";
    15961672        }
    15971673
    1598                         $item .= "</td></tr>\n";
     1674        $item .= "</td></tr>\n";
    15991675
    16001676        $item .= "
     
    16411717        $thumbnail       = '';
    16421718        $calling_post_id = 0;
     1719
    16431720        if ( isset( $_GET['post_id'] ) ) {
    16441721                $calling_post_id = absint( $_GET['post_id'] );
     
    16461723                $calling_post_id = $post->post_parent;
    16471724        }
     1725
    16481726        if ( 'image' == $type && $calling_post_id && current_theme_supports( 'post-thumbnails', get_post_type( $calling_post_id ) )
    16491727                && post_type_supports( get_post_type( $calling_post_id ), 'thumbnail' ) && get_post_thumbnail_id( $calling_post_id ) != $attachment_id ) {
     
    16591737                $form_fields['buttons'] = array( 'tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>" . $parsed_args['send'] . " $thumbnail $delete</td></tr>\n" );
    16601738        }
     1739
    16611740        $hidden_fields = array();
    16621741
     
    16851764
    16861765                $item .= "\t\t<tr class='$class'>\n\t\t\t<th scope='row' class='label'><label for='$name'><span class='alignleft'>{$field['label']}{$required}</span><br class='clear' /></label></th>\n\t\t\t<td class='field'>";
     1766
    16871767                if ( ! empty( $field[ $field['input'] ] ) ) {
    16881768                        $item .= $field[ $field['input'] ];
     
    16971777                        $item .= "<input type='text' class='text' id='$name' name='$name' value='" . esc_attr( $field['value'] ) . "'{$required_attr} />";
    16981778                }
     1779
    16991780                if ( ! empty( $field['helps'] ) ) {
    17001781                        $item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique( (array) $field['helps'] ) ) . '</p>';
     
    17281809                $item .= "\t\t<tr class='final'><td colspan='2'>{$form_fields['_final']}</td></tr>\n";
    17291810        }
     1811
    17301812        $item .= "\t</tbody>\n";
    17311813        $item .= "\t</table>\n";
     
    17711853                foreach ( get_attachment_taxonomies( $post ) as $taxonomy ) {
    17721854                        $t = (array) get_taxonomy( $taxonomy );
     1855
    17731856                        if ( ! $t['public'] || ! $t['show_ui'] ) {
    17741857                                continue;
    17751858                        }
     1859
    17761860                        if ( empty( $t['label'] ) ) {
    17771861                                $t['label'] = $taxonomy;
    17781862                        }
     1863
    17791864                        if ( empty( $t['args'] ) ) {
    17801865                                $t['args'] = array();
     
    17821867
    17831868                        $terms = get_object_term_cache( $post->ID, $taxonomy );
     1869
    17841870                        if ( false === $terms ) {
    17851871                                $terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] );
     
    17911877                                $values[] = $term->slug;
    17921878                        }
     1879
    17931880                        $t['value']    = join( ', ', $values );
    17941881                        $t['taxonomy'] = true;
     
    18321919
    18331920        $item = '';
     1921
    18341922        foreach ( $form_fields as $id => $field ) {
    18351923                if ( $id[0] == '_' ) {
     
    18771965                        $item .= "<input type='text' class='text' id='$id_attr' name='$name' value='" . esc_attr( $field['value'] ) . "' $readonly{$required_attr} />";
    18781966                }
     1967
    18791968                if ( ! empty( $field['helps'] ) ) {
    18801969                        $item .= "<p class='help'>" . join( "</p>\n<p class='help'>", array_unique( (array) $field['helps'] ) ) . '</p>';
    18811970                }
     1971
    18821972                $item .= "</td>\n\t\t</tr>\n";
    18831973
     
    19402030
    19412031        echo '<script type="text/javascript">post_id = ' . $post_id . ';</script>';
     2032
    19422033        if ( empty( $_GET['chromeless'] ) ) {
    19432034                echo '<div id="media-upload-header">';
     
    19802071                $max_upload_size = 0;
    19812072        }
     2073
    19822074        ?>
    1983 
    1984 <div id="media-upload-notice">
     2075        <div id="media-upload-notice">
    19852076        <?php
    19862077
     
    19902081
    19912082        ?>
    1992 </div>
    1993 <div id="media-upload-error">
     2083        </div>
     2084        <div id="media-upload-error">
    19942085        <?php
    19952086
     
    19992090
    20002091        ?>
    2001 </div>
     2092        </div>
    20022093        <?php
     2094
    20032095        if ( is_multisite() && ! is_upload_space_available() ) {
    20042096                /**
     
    20462138                'file_data_name'   => 'async-upload',
    20472139                'url'              => $upload_action_url,
    2048                 'filters'          => array(
    2049                         'max_file_size' => $max_upload_size . 'b',
    2050                 ),
     2140                'filters'          => array( 'max_file_size' => $max_upload_size . 'b' ),
    20512141                'multipart_params' => $post_params,
    20522142        );
     
    20542144        // Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
    20552145        // when enabled. See #29602.
    2056         if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
    2057         strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
    2058 
     2146        if (
     2147                wp_is_mobile() &&
     2148                strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
     2149                strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false
     2150        ) {
    20592151                $plupload_init['multi_selection'] = false;
    20602152        }
     
    20702162
    20712163        ?>
    2072 
    2073 <script type="text/javascript">
     2164        <script type="text/javascript">
    20742165        <?php
    20752166        // Verify size is an int. If not return default value.
    20762167        $large_size_h = absint( get_option( 'large_size_h' ) );
     2168
    20772169        if ( ! $large_size_h ) {
    20782170                $large_size_h = 1024;
    20792171        }
     2172
    20802173        $large_size_w = absint( get_option( 'large_size_w' ) );
     2174
    20812175        if ( ! $large_size_w ) {
    20822176                $large_size_w = 1024;
    20832177        }
     2178
    20842179        ?>
    2085 var resize_height = <?php echo $large_size_h; ?>, resize_width = <?php echo $large_size_w; ?>,
    2086 wpUploaderInit = <?php echo wp_json_encode( $plupload_init ); ?>;
    2087 </script>
    2088 
    2089 <div id="plupload-upload-ui" class="hide-if-no-js">
     2180        var resize_height = <?php echo $large_size_h; ?>, resize_width = <?php echo $large_size_w; ?>,
     2181        wpUploaderInit = <?php echo wp_json_encode( $plupload_init ); ?>;
     2182        </script>
     2183
     2184        <div id="plupload-upload-ui" class="hide-if-no-js">
    20902185        <?php
    20912186        /**
     
    20962191         */
    20972192        do_action( 'pre-plupload-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
     2193
    20982194        ?>
    2099 <div id="drag-drop-area">
    2100         <div class="drag-drop-inside">
    2101         <p class="drag-drop-info"><?php _e( 'Drop files to upload' ); ?></p>
    2102         <p><?php _ex( 'or', 'Uploader: Drop files here - or - Select Files' ); ?></p>
    2103         <p class="drag-drop-buttons"><input id="plupload-browse-button" type="button" value="<?php esc_attr_e( 'Select Files' ); ?>" class="button" /></p>
     2195        <div id="drag-drop-area">
     2196                <div class="drag-drop-inside">
     2197                <p class="drag-drop-info"><?php _e( 'Drop files to upload' ); ?></p>
     2198                <p><?php _ex( 'or', 'Uploader: Drop files here - or - Select Files' ); ?></p>
     2199                <p class="drag-drop-buttons"><input id="plupload-browse-button" type="button" value="<?php esc_attr_e( 'Select Files' ); ?>" class="button" /></p>
     2200                </div>
    21042201        </div>
    2105 </div>
    21062202        <?php
    21072203        /**
     
    21132209        do_action( 'post-plupload-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
    21142210        ?>
    2115 </div>
    2116 
    2117 <div id="html-upload-ui" class="hide-if-js">
     2211        </div>
     2212
     2213        <div id="html-upload-ui" class="hide-if-js">
    21182214        <?php
    21192215        /**
     
    21232219         */
    21242220        do_action( 'pre-html-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
     2221
    21252222        ?>
    21262223        <p id="async-upload-wrap">
     
    21382235         */
    21392236        do_action( 'post-html-upload-ui' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
     2237
    21402238        ?>
    2141 </div>
     2239        </div>
    21422240
    21432241<p class="max-upload-size">
     
    21902288                $form_class .= ' html-uploader';
    21912289        }
     2290
    21922291        ?>
    2193 
    2194 <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="<?php echo $type; ?>-form">
    2195         <?php submit_button( '', 'hidden', 'save', false ); ?>
    2196 <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
    2197         <?php wp_nonce_field( 'media-form' ); ?>
    2198 
    2199 <h3 class="media-title"><?php _e( 'Add media files from your computer' ); ?></h3>
     2292        <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="<?php echo $type; ?>-form">
     2293                <?php submit_button( '', 'hidden', 'save', false ); ?>
     2294        <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
     2295                <?php wp_nonce_field( 'media-form' ); ?>
     2296
     2297        <h3 class="media-title"><?php _e( 'Add media files from your computer' ); ?></h3>
    22002298
    22012299        <?php media_upload_form( $errors ); ?>
    22022300
    2203 <script type="text/javascript">
    2204 jQuery(function($){
    2205         var preloaded = $(".media-item.preloaded");
    2206         if ( preloaded.length > 0 ) {
    2207                 preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
    2208         }
    2209         updateMediaForm();
    2210 });
    2211 </script>
    2212 <div id="media-items">
     2301        <script type="text/javascript">
     2302        jQuery(function($){
     2303                var preloaded = $(".media-item.preloaded");
     2304                if ( preloaded.length > 0 ) {
     2305                        preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
     2306                }
     2307                updateMediaForm();
     2308        });
     2309        </script>
     2310        <div id="media-items">
    22132311        <?php
    22142312
     
    22222320                }
    22232321        }
     2322
    22242323        ?>
    2225 </div>
    2226 
    2227 <p class="savebutton ml-submit">
    2228         <?php submit_button( __( 'Save all changes' ), '', 'save', false ); ?>
    2229 </p>
    2230 </form>
     2324        </div>
     2325
     2326        <p class="savebutton ml-submit">
     2327                <?php submit_button( __( 'Save all changes' ), '', 'save', false ); ?>
     2328        </p>
     2329        </form>
    22312330        <?php
    22322331}
     
    22582357                $form_class .= ' html-uploader';
    22592358        }
     2359
    22602360        ?>
    2261 
    2262 <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="<?php echo $type; ?>-form">
    2263 <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
    2264         <?php wp_nonce_field( 'media-form' ); ?>
    2265 
    2266 <h3 class="media-title"><?php _e( 'Insert media from another website' ); ?></h3>
    2267 
    2268 <script type="text/javascript">
    2269 var addExtImage = {
     2361        <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="<?php echo $type; ?>-form">
     2362        <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
     2363                <?php wp_nonce_field( 'media-form' ); ?>
     2364
     2365        <h3 class="media-title"><?php _e( 'Insert media from another website' ); ?></h3>
     2366
     2367        <script type="text/javascript">
     2368        var addExtImage = {
    22702369
    22712370        width : '',
     
    22822381                        alt = f.alt.value.replace(/'/g, '&#039;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    22832382
    2284         <?php
    2285         /** This filter is documented in wp-admin/includes/media.php */
    2286         if ( ! apply_filters( 'disable_captions', '' ) ) {
     2383                <?php
     2384                /** This filter is documented in wp-admin/includes/media.php */
     2385                if ( ! apply_filters( 'disable_captions', '' ) ) {
     2386                        ?>
     2387                        if ( f.caption.value ) {
     2388                                caption = f.caption.value.replace(/\r\n|\r/g, '\n');
     2389                                caption = caption.replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){
     2390                                        return a.replace(/[\r\n\t]+/, ' ');
     2391                                });
     2392
     2393                                caption = caption.replace(/\s*\n\s*/g, '<br />');
     2394                        }
     2395                        <?php
     2396                }
     2397
    22872398                ?>
    2288         if ( f.caption.value ) {
    2289                 caption = f.caption.value.replace(/\r\n|\r/g, '\n');
    2290                 caption = caption.replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){
    2291                         return a.replace(/[\r\n\t]+/, ' ');
    2292                 });
    2293 
    2294                 caption = caption.replace(/\s*\n\s*/g, '<br />');
    2295         }
    2296         <?php } ?>
    2297 
    22982399                cls = caption ? '' : ' class="'+t.align+'"';
    22992400
     
    23492450                t.preloadImg.src = src;
    23502451        }
    2351 };
    2352 
    2353 jQuery(document).ready( function($) {
    2354         $('.media-types input').click( function() {
    2355                 $('table.describe').toggleClass('not-image', $('#not-image').prop('checked') );
     2452        };
     2453
     2454        jQuery(document).ready( function($) {
     2455                $('.media-types input').click( function() {
     2456                        $('table.describe').toggleClass('not-image', $('#not-image').prop('checked') );
     2457                });
    23562458        });
    2357 });
    2358 </script>
    2359 
    2360 <div id="media-items">
    2361 <div class="media-item media-blank">
     2459        </script>
     2460
     2461        <div id="media-items">
     2462        <div class="media-item media-blank">
    23622463        <?php
    23632464        /**
     
    23692470         */
    23702471        echo apply_filters( 'type_url_form_media', wp_media_insert_url_form( $type ) );
     2472
    23712473        ?>
    2372 </div>
    2373 </div>
    2374 </form>
     2474        </div>
     2475        </div>
     2476        </form>
    23752477        <?php
    23762478}
     
    24022504                $form_class .= ' html-uploader';
    24032505        }
     2506
    24042507        ?>
    2405 
    2406 <script type="text/javascript">
    2407 jQuery(function($){
    2408         var preloaded = $(".media-item.preloaded");
    2409         if ( preloaded.length > 0 ) {
    2410                 preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
    2411                 updateMediaForm();
    2412         }
    2413 });
    2414 </script>
    2415 <div id="sort-buttons" class="hide-if-no-js">
    2416 <span>
    2417         <?php _e( 'All Tabs:' ); ?>
    2418 <a href="#" id="showall"><?php _e( 'Show' ); ?></a>
    2419 <a href="#" id="hideall" style="display:none;"><?php _e( 'Hide' ); ?></a>
    2420 </span>
    2421         <?php _e( 'Sort Order:' ); ?>
    2422 <a href="#" id="asc"><?php _e( 'Ascending' ); ?></a> |
    2423 <a href="#" id="desc"><?php _e( 'Descending' ); ?></a> |
    2424 <a href="#" id="clear"><?php _ex( 'Clear', 'verb' ); ?></a>
    2425 </div>
    2426 <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="gallery-form">
    2427         <?php wp_nonce_field( 'media-form' ); ?>
    2428         <?php //media_upload_form( $errors ); ?>
    2429 <table class="widefat">
    2430 <thead><tr>
    2431 <th><?php _e( 'Media' ); ?></th>
    2432 <th class="order-head"><?php _e( 'Order' ); ?></th>
    2433 <th class="actions-head"><?php _e( 'Actions' ); ?></th>
    2434 </tr></thead>
    2435 </table>
    2436 <div id="media-items">
    2437         <?php add_filter( 'attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2 ); ?>
    2438         <?php echo get_media_items( $post_id, $errors ); ?>
    2439 </div>
    2440 
    2441 <p class="ml-submit">
    2442         <?php
    2443         submit_button(
    2444                 __( 'Save all changes' ),
    2445                 'savebutton',
    2446                 'save',
    2447                 false,
    2448                 array(
    2449                         'id'    => 'save-all',
    2450                         'style' => 'display: none;',
    2451                 )
    2452         );
    2453         ?>
    2454 <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
    2455 <input type="hidden" name="type" value="<?php echo esc_attr( $GLOBALS['type'] ); ?>" />
    2456 <input type="hidden" name="tab" value="<?php echo esc_attr( $GLOBALS['tab'] ); ?>" />
    2457 </p>
    2458 
    2459 <div id="gallery-settings" style="display:none;">
    2460 <div class="title"><?php _e( 'Gallery Settings' ); ?></div>
    2461 <table id="basic" class="describe"><tbody>
    2462         <tr>
    2463         <th scope="row" class="label">
    2464                 <label>
    2465                 <span class="alignleft"><?php _e( 'Link thumbnails to:' ); ?></span>
    2466                 </label>
    2467         </th>
    2468         <td class="field">
    2469                 <input type="radio" name="linkto" id="linkto-file" value="file" />
    2470                 <label for="linkto-file" class="radio"><?php _e( 'Image File' ); ?></label>
    2471 
    2472                 <input type="radio" checked="checked" name="linkto" id="linkto-post" value="post" />
    2473                 <label for="linkto-post" class="radio"><?php _e( 'Attachment Page' ); ?></label>
    2474         </td>
    2475         </tr>
    2476 
    2477         <tr>
    2478         <th scope="row" class="label">
    2479                 <label>
    2480                 <span class="alignleft"><?php _e( 'Order images by:' ); ?></span>
    2481                 </label>
    2482         </th>
    2483         <td class="field">
    2484                 <select id="orderby" name="orderby">
    2485                         <option value="menu_order" selected="selected"><?php _e( 'Menu order' ); ?></option>
    2486                         <option value="title"><?php _e( 'Title' ); ?></option>
    2487                         <option value="post_date"><?php _e( 'Date/Time' ); ?></option>
    2488                         <option value="rand"><?php _e( 'Random' ); ?></option>
    2489                 </select>
    2490         </td>
    2491         </tr>
    2492 
    2493         <tr>
    2494         <th scope="row" class="label">
    2495                 <label>
    2496                 <span class="alignleft"><?php _e( 'Order:' ); ?></span>
    2497                 </label>
    2498         </th>
    2499         <td class="field">
    2500                 <input type="radio" checked="checked" name="order" id="order-asc" value="asc" />
    2501                 <label for="order-asc" class="radio"><?php _e( 'Ascending' ); ?></label>
    2502 
    2503                 <input type="radio" name="order" id="order-desc" value="desc" />
    2504                 <label for="order-desc" class="radio"><?php _e( 'Descending' ); ?></label>
    2505         </td>
    2506         </tr>
    2507 
    2508         <tr>
    2509         <th scope="row" class="label">
    2510                 <label>
    2511                 <span class="alignleft"><?php _e( 'Gallery columns:' ); ?></span>
    2512                 </label>
    2513         </th>
    2514         <td class="field">
    2515                 <select id="columns" name="columns">
    2516                         <option value="1">1</option>
    2517                         <option value="2">2</option>
    2518                         <option value="3" selected="selected">3</option>
    2519                         <option value="4">4</option>
    2520                         <option value="5">5</option>
    2521                         <option value="6">6</option>
    2522                         <option value="7">7</option>
    2523                         <option value="8">8</option>
    2524                         <option value="9">9</option>
    2525                 </select>
    2526         </td>
    2527         </tr>
    2528 </tbody></table>
    2529 
    2530 <p class="ml-submit">
    2531 <input type="button" class="button" style="display:none;" onMouseDown="wpgallery.update();" name="insert-gallery" id="insert-gallery" value="<?php esc_attr_e( 'Insert gallery' ); ?>" />
    2532 <input type="button" class="button" style="display:none;" onMouseDown="wpgallery.update();" name="update-gallery" id="update-gallery" value="<?php esc_attr_e( 'Update gallery settings' ); ?>" />
    2533 </p>
    2534 </div>
    2535 </form>
     2508        <script type="text/javascript">
     2509        jQuery(function($){
     2510                var preloaded = $(".media-item.preloaded");
     2511                if ( preloaded.length > 0 ) {
     2512                        preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
     2513                        updateMediaForm();
     2514                }
     2515        });
     2516        </script>
     2517        <div id="sort-buttons" class="hide-if-no-js">
     2518        <span>
     2519                <?php _e( 'All Tabs:' ); ?>
     2520        <a href="#" id="showall"><?php _e( 'Show' ); ?></a>
     2521        <a href="#" id="hideall" style="display:none;"><?php _e( 'Hide' ); ?></a>
     2522        </span>
     2523                <?php _e( 'Sort Order:' ); ?>
     2524        <a href="#" id="asc"><?php _e( 'Ascending' ); ?></a> |
     2525        <a href="#" id="desc"><?php _e( 'Descending' ); ?></a> |
     2526        <a href="#" id="clear"><?php _ex( 'Clear', 'verb' ); ?></a>
     2527        </div>
     2528        <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="gallery-form">
     2529                <?php wp_nonce_field( 'media-form' ); ?>
     2530                <?php //media_upload_form( $errors ); ?>
     2531        <table class="widefat">
     2532        <thead><tr>
     2533        <th><?php _e( 'Media' ); ?></th>
     2534        <th class="order-head"><?php _e( 'Order' ); ?></th>
     2535        <th class="actions-head"><?php _e( 'Actions' ); ?></th>
     2536        </tr></thead>
     2537        </table>
     2538        <div id="media-items">
     2539                <?php add_filter( 'attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2 ); ?>
     2540                <?php echo get_media_items( $post_id, $errors ); ?>
     2541        </div>
     2542
     2543        <p class="ml-submit">
     2544                <?php
     2545                submit_button(
     2546                        __( 'Save all changes' ),
     2547                        'savebutton',
     2548                        'save',
     2549                        false,
     2550                        array(
     2551                                'id'    => 'save-all',
     2552                                'style' => 'display: none;',
     2553                        )
     2554                );
     2555                ?>
     2556        <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
     2557        <input type="hidden" name="type" value="<?php echo esc_attr( $GLOBALS['type'] ); ?>" />
     2558        <input type="hidden" name="tab" value="<?php echo esc_attr( $GLOBALS['tab'] ); ?>" />
     2559        </p>
     2560
     2561        <div id="gallery-settings" style="display:none;">
     2562        <div class="title"><?php _e( 'Gallery Settings' ); ?></div>
     2563        <table id="basic" class="describe"><tbody>
     2564                <tr>
     2565                <th scope="row" class="label">
     2566                        <label>
     2567                        <span class="alignleft"><?php _e( 'Link thumbnails to:' ); ?></span>
     2568                        </label>
     2569                </th>
     2570                <td class="field">
     2571                        <input type="radio" name="linkto" id="linkto-file" value="file" />
     2572                        <label for="linkto-file" class="radio"><?php _e( 'Image File' ); ?></label>
     2573
     2574                        <input type="radio" checked="checked" name="linkto" id="linkto-post" value="post" />
     2575                        <label for="linkto-post" class="radio"><?php _e( 'Attachment Page' ); ?></label>
     2576                </td>
     2577                </tr>
     2578
     2579                <tr>
     2580                <th scope="row" class="label">
     2581                        <label>
     2582                        <span class="alignleft"><?php _e( 'Order images by:' ); ?></span>
     2583                        </label>
     2584                </th>
     2585                <td class="field">
     2586                        <select id="orderby" name="orderby">
     2587                                <option value="menu_order" selected="selected"><?php _e( 'Menu order' ); ?></option>
     2588                                <option value="title"><?php _e( 'Title' ); ?></option>
     2589                                <option value="post_date"><?php _e( 'Date/Time' ); ?></option>
     2590                                <option value="rand"><?php _e( 'Random' ); ?></option>
     2591                        </select>
     2592                </td>
     2593                </tr>
     2594
     2595                <tr>
     2596                <th scope="row" class="label">
     2597                        <label>
     2598                        <span class="alignleft"><?php _e( 'Order:' ); ?></span>
     2599                        </label>
     2600                </th>
     2601                <td class="field">
     2602                        <input type="radio" checked="checked" name="order" id="order-asc" value="asc" />
     2603                        <label for="order-asc" class="radio"><?php _e( 'Ascending' ); ?></label>
     2604
     2605                        <input type="radio" name="order" id="order-desc" value="desc" />
     2606                        <label for="order-desc" class="radio"><?php _e( 'Descending' ); ?></label>
     2607                </td>
     2608                </tr>
     2609
     2610                <tr>
     2611                <th scope="row" class="label">
     2612                        <label>
     2613                        <span class="alignleft"><?php _e( 'Gallery columns:' ); ?></span>
     2614                        </label>
     2615                </th>
     2616                <td class="field">
     2617                        <select id="columns" name="columns">
     2618                                <option value="1">1</option>
     2619                                <option value="2">2</option>
     2620                                <option value="3" selected="selected">3</option>
     2621                                <option value="4">4</option>
     2622                                <option value="5">5</option>
     2623                                <option value="6">6</option>
     2624                                <option value="7">7</option>
     2625                                <option value="8">8</option>
     2626                                <option value="9">9</option>
     2627                        </select>
     2628                </td>
     2629                </tr>
     2630        </tbody></table>
     2631
     2632        <p class="ml-submit">
     2633        <input type="button" class="button" style="display:none;" onMouseDown="wpgallery.update();" name="insert-gallery" id="insert-gallery" value="<?php esc_attr_e( 'Insert gallery' ); ?>" />
     2634        <input type="button" class="button" style="display:none;" onMouseDown="wpgallery.update();" name="update-gallery" id="update-gallery" value="<?php esc_attr_e( 'Update gallery settings' ); ?>" />
     2635        </p>
     2636        </div>
     2637        </form>
    25362638        <?php
    25372639}
     
    25812683
    25822684        ?>
    2583 
    2584 <form id="filter" method="get">
    2585 <input type="hidden" name="type" value="<?php echo esc_attr( $type ); ?>" />
    2586 <input type="hidden" name="tab" value="<?php echo esc_attr( $tab ); ?>" />
    2587 <input type="hidden" name="post_id" value="<?php echo (int) $post_id; ?>" />
    2588 <input type="hidden" name="post_mime_type" value="<?php echo isset( $_GET['post_mime_type'] ) ? esc_attr( $_GET['post_mime_type'] ) : ''; ?>" />
    2589 <input type="hidden" name="context" value="<?php echo isset( $_GET['context'] ) ? esc_attr( $_GET['context'] ) : ''; ?>" />
    2590 
    2591 <p id="media-search" class="search-box">
    2592         <label class="screen-reader-text" for="media-search-input"><?php _e( 'Search Media' ); ?>:</label>
    2593         <input type="search" id="media-search-input" name="s" value="<?php the_search_query(); ?>" />
    2594         <?php submit_button( __( 'Search Media' ), '', '', false ); ?>
    2595 </p>
    2596 
    2597 <ul class="subsubsub">
    2598         <?php
    2599         $type_links = array();
    2600         $_num_posts = (array) wp_count_attachments();
    2601         $matches    = wp_match_mime_types( array_keys( $post_mime_types ), array_keys( $_num_posts ) );
    2602         foreach ( $matches as $_type => $reals ) {
    2603                 foreach ( $reals as $real ) {
    2604                         if ( isset( $num_posts[ $_type ] ) ) {
    2605                                 $num_posts[ $_type ] += $_num_posts[ $real ];
    2606                         } else {
    2607                                 $num_posts[ $_type ] = $_num_posts[ $real ];
    2608                         }
    2609                 }
    2610         }
    2611         // If available type specified by media button clicked, filter by that type
    2612         if ( empty( $_GET['post_mime_type'] ) && ! empty( $num_posts[ $type ] ) ) {
    2613                 $_GET['post_mime_type']                        = $type;
    2614                 list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query();
    2615         }
    2616         if ( empty( $_GET['post_mime_type'] ) || $_GET['post_mime_type'] == 'all' ) {
    2617                 $class = ' class="current"';
    2618         } else {
    2619                 $class = '';
    2620         }
    2621         $type_links[] = '<li><a href="' . esc_url(
    2622                 add_query_arg(
    2623                         array(
    2624                                 'post_mime_type' => 'all',
    2625                                 'paged'          => false,
    2626                                 'm'              => false,
    2627                         )
    2628                 )
    2629         ) . '"' . $class . '>' . __( 'All Types' ) . '</a>';
    2630         foreach ( $post_mime_types as $mime_type => $label ) {
    2631                 $class = '';
    2632 
    2633                 if ( ! wp_match_mime_types( $mime_type, $avail_post_mime_types ) ) {
    2634                         continue;
    2635                 }
    2636 
    2637                 if ( isset( $_GET['post_mime_type'] ) && wp_match_mime_types( $mime_type, $_GET['post_mime_type'] ) ) {
     2685        <form id="filter" method="get">
     2686        <input type="hidden" name="type" value="<?php echo esc_attr( $type ); ?>" />
     2687        <input type="hidden" name="tab" value="<?php echo esc_attr( $tab ); ?>" />
     2688        <input type="hidden" name="post_id" value="<?php echo (int) $post_id; ?>" />
     2689        <input type="hidden" name="post_mime_type" value="<?php echo isset( $_GET['post_mime_type'] ) ? esc_attr( $_GET['post_mime_type'] ) : ''; ?>" />
     2690        <input type="hidden" name="context" value="<?php echo isset( $_GET['context'] ) ? esc_attr( $_GET['context'] ) : ''; ?>" />
     2691
     2692        <p id="media-search" class="search-box">
     2693                <label class="screen-reader-text" for="media-search-input"><?php _e( 'Search Media' ); ?>:</label>
     2694                <input type="search" id="media-search-input" name="s" value="<?php the_search_query(); ?>" />
     2695                <?php submit_button( __( 'Search Media' ), '', '', false ); ?>
     2696        </p>
     2697
     2698        <ul class="subsubsub">
     2699                <?php
     2700                $type_links = array();
     2701                $_num_posts = (array) wp_count_attachments();
     2702                $matches    = wp_match_mime_types( array_keys( $post_mime_types ), array_keys( $_num_posts ) );
     2703                foreach ( $matches as $_type => $reals ) {
     2704                        foreach ( $reals as $real ) {
     2705                                if ( isset( $num_posts[ $_type ] ) ) {
     2706                                        $num_posts[ $_type ] += $_num_posts[ $real ];
     2707                                } else {
     2708                                        $num_posts[ $_type ] = $_num_posts[ $real ];
     2709                                }
     2710                        }
     2711                }
     2712                // If available type specified by media button clicked, filter by that type
     2713                if ( empty( $_GET['post_mime_type'] ) && ! empty( $num_posts[ $type ] ) ) {
     2714                        $_GET['post_mime_type']                        = $type;
     2715                        list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query();
     2716                }
     2717                if ( empty( $_GET['post_mime_type'] ) || $_GET['post_mime_type'] == 'all' ) {
    26382718                        $class = ' class="current"';
    2639                 }
    2640 
     2719                } else {
     2720                        $class = '';
     2721                }
    26412722                $type_links[] = '<li><a href="' . esc_url(
    26422723                        add_query_arg(
    26432724                                array(
    2644                                         'post_mime_type' => $mime_type,
     2725                                        'post_mime_type' => 'all',
    26452726                                        'paged'          => false,
     2727                                        'm'              => false,
    26462728                                )
    26472729                        )
    2648                 ) . '"' . $class . '>' . sprintf( translate_nooped_plural( $label[2], $num_posts[ $mime_type ] ), '<span id="' . $mime_type . '-counter">' . number_format_i18n( $num_posts[ $mime_type ] ) . '</span>' ) . '</a>';
    2649         }
    2650         /**
    2651          * Filters the media upload mime type list items.
    2652          *
    2653          * Returned values should begin with an `<li>` tag.
    2654          *
    2655          * @since 3.1.0
    2656          *
    2657          * @param string[] $type_links An array of list items containing mime type link HTML.
    2658          */
    2659         echo implode( ' | </li>', apply_filters( 'media_upload_mime_type_links', $type_links ) ) . '</li>';
    2660         unset( $type_links );
    2661         ?>
    2662 </ul>
    2663 
    2664 <div class="tablenav">
    2665 
    2666         <?php
    2667         $page_links = paginate_links(
    2668                 array(
    2669                         'base'      => add_query_arg( 'paged', '%#%' ),
    2670                         'format'    => '',
    2671                         'prev_text' => __( '&laquo;' ),
    2672                         'next_text' => __( '&raquo;' ),
    2673                         'total'     => ceil( $wp_query->found_posts / 10 ),
    2674                         'current'   => $q['paged'],
    2675                 )
    2676         );
    2677 
    2678         if ( $page_links ) {
    2679                 echo "<div class='tablenav-pages'>$page_links</div>";
    2680         }
    2681         ?>
    2682 
    2683 <div class="alignleft actions">
    2684         <?php
    2685 
    2686         $arc_query = "SELECT DISTINCT YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM $wpdb->posts WHERE post_type = 'attachment' ORDER BY post_date DESC";
    2687 
    2688         $arc_result = $wpdb->get_results( $arc_query );
    2689 
    2690         $month_count    = count( $arc_result );
    2691         $selected_month = isset( $_GET['m'] ) ? $_GET['m'] : 0;
    2692 
    2693         if ( $month_count && ! ( 1 == $month_count && 0 == $arc_result[0]->mmonth ) ) {
     2730                ) . '"' . $class . '>' . __( 'All Types' ) . '</a>';
     2731                foreach ( $post_mime_types as $mime_type => $label ) {
     2732                        $class = '';
     2733
     2734                        if ( ! wp_match_mime_types( $mime_type, $avail_post_mime_types ) ) {
     2735                                continue;
     2736                        }
     2737
     2738                        if ( isset( $_GET['post_mime_type'] ) && wp_match_mime_types( $mime_type, $_GET['post_mime_type'] ) ) {
     2739                                $class = ' class="current"';
     2740                        }
     2741
     2742                        $type_links[] = '<li><a href="' . esc_url(
     2743                                add_query_arg(
     2744                                        array(
     2745                                                'post_mime_type' => $mime_type,
     2746                                                'paged'          => false,
     2747                                        )
     2748                                )
     2749                        ) . '"' . $class . '>' . sprintf( translate_nooped_plural( $label[2], $num_posts[ $mime_type ] ), '<span id="' . $mime_type . '-counter">' . number_format_i18n( $num_posts[ $mime_type ] ) . '</span>' ) . '</a>';
     2750                }
     2751                /**
     2752                 * Filters the media upload mime type list items.
     2753                 *
     2754                 * Returned values should begin with an `<li>` tag.
     2755                 *
     2756                 * @since 3.1.0
     2757                 *
     2758                 * @param string[] $type_links An array of list items containing mime type link HTML.
     2759                 */
     2760                echo implode( ' | </li>', apply_filters( 'media_upload_mime_type_links', $type_links ) ) . '</li>';
     2761                unset( $type_links );
    26942762                ?>
    2695 <select name='m'>
    2696 <option<?php selected( $selected_month, 0 ); ?> value='0'><?php _e( 'All dates' ); ?></option>
     2763        </ul>
     2764
     2765        <div class="tablenav">
     2766
    26972767                <?php
    2698                 foreach ( $arc_result as $arc_row ) {
    2699                         if ( $arc_row->yyear == 0 ) {
    2700                                 continue;
    2701                         }
    2702                         $arc_row->mmonth = zeroise( $arc_row->mmonth, 2 );
    2703 
    2704                         if ( $arc_row->yyear . $arc_row->mmonth == $selected_month ) {
    2705                                 $default = ' selected="selected"';
    2706                         } else {
    2707                                 $default = '';
    2708                         }
    2709 
    2710                         echo "<option$default value='" . esc_attr( $arc_row->yyear . $arc_row->mmonth ) . "'>";
    2711                         echo esc_html( $wp_locale->get_month( $arc_row->mmonth ) . " $arc_row->yyear" );
    2712                         echo "</option>\n";
     2768                $page_links = paginate_links(
     2769                        array(
     2770                                'base'      => add_query_arg( 'paged', '%#%' ),
     2771                                'format'    => '',
     2772                                'prev_text' => __( '&laquo;' ),
     2773                                'next_text' => __( '&raquo;' ),
     2774                                'total'     => ceil( $wp_query->found_posts / 10 ),
     2775                                'current'   => $q['paged'],
     2776                        )
     2777                );
     2778
     2779                if ( $page_links ) {
     2780                        echo "<div class='tablenav-pages'>$page_links</div>";
    27132781                }
    27142782                ?>
    2715 </select>
    2716         <?php } ?>
    2717 
    2718         <?php submit_button( __( 'Filter &#187;' ), '', 'post-query-submit', false ); ?>
    2719 
    2720 </div>
    2721 
    2722 <br class="clear" />
    2723 </div>
    2724 </form>
    2725 
    2726 <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="library-form">
    2727 
     2783
     2784        <div class="alignleft actions">
     2785                <?php
     2786
     2787                $arc_query = "SELECT DISTINCT YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM $wpdb->posts WHERE post_type = 'attachment' ORDER BY post_date DESC";
     2788
     2789                $arc_result = $wpdb->get_results( $arc_query );
     2790
     2791                $month_count    = count( $arc_result );
     2792                $selected_month = isset( $_GET['m'] ) ? $_GET['m'] : 0;
     2793
     2794                if ( $month_count && ! ( 1 == $month_count && 0 == $arc_result[0]->mmonth ) ) {
     2795                        ?>
     2796                        <select name='m'>
     2797                        <option<?php selected( $selected_month, 0 ); ?> value='0'><?php _e( 'All dates' ); ?></option>
     2798                        <?php
     2799
     2800                        foreach ( $arc_result as $arc_row ) {
     2801                                if ( $arc_row->yyear == 0 ) {
     2802                                        continue;
     2803                                }
     2804
     2805                                $arc_row->mmonth = zeroise( $arc_row->mmonth, 2 );
     2806
     2807                                if ( $arc_row->yyear . $arc_row->mmonth == $selected_month ) {
     2808                                        $default = ' selected="selected"';
     2809                                } else {
     2810                                        $default = '';
     2811                                }
     2812
     2813                                echo "<option$default value='" . esc_attr( $arc_row->yyear . $arc_row->mmonth ) . "'>";
     2814                                echo esc_html( $wp_locale->get_month( $arc_row->mmonth ) . " $arc_row->yyear" );
     2815                                echo "</option>\n";
     2816                        }
     2817
     2818                        ?>
     2819                        </select>
     2820                <?php } ?>
     2821
     2822                <?php submit_button( __( 'Filter &#187;' ), '', 'post-query-submit', false ); ?>
     2823
     2824        </div>
     2825
     2826        <br class="clear" />
     2827        </div>
     2828        </form>
     2829
     2830        <form enctype="multipart/form-data" method="post" action="<?php echo esc_url( $form_action_url ); ?>" class="<?php echo $form_class; ?>" id="library-form">
    27282831        <?php wp_nonce_field( 'media-form' ); ?>
    27292832        <?php //media_upload_form( $errors ); ?>
    27302833
    2731 <script type="text/javascript">
    2732 <!--
    2733 jQuery(function($){
    2734         var preloaded = $(".media-item.preloaded");
    2735         if ( preloaded.length > 0 ) {
    2736                 preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
    2737                 updateMediaForm();
    2738         }
    2739 });
    2740 -->
    2741 </script>
    2742 
    2743 <div id="media-items">
    2744         <?php add_filter( 'attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2 ); ?>
    2745         <?php echo get_media_items( null, $errors ); ?>
    2746 </div>
    2747 <p class="ml-submit">
    2748         <?php submit_button( __( 'Save all changes' ), 'savebutton', 'save', false ); ?>
    2749 <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
    2750 </p>
    2751 </form>
     2834        <script type="text/javascript">
     2835        jQuery(function($){
     2836                var preloaded = $(".media-item.preloaded");
     2837                if ( preloaded.length > 0 ) {
     2838                        preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
     2839                        updateMediaForm();
     2840                }
     2841        });
     2842        </script>
     2843
     2844        <div id="media-items">
     2845                <?php add_filter( 'attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2 ); ?>
     2846                <?php echo get_media_items( null, $errors ); ?>
     2847        </div>
     2848        <p class="ml-submit">
     2849                <?php submit_button( __( 'Save all changes' ), 'savebutton', 'save', false ); ?>
     2850        <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
     2851        </p>
     2852        </form>
    27522853        <?php
    27532854}
     
    27702871                        </th>
    27712872                        <td class="field"><textarea id="caption" name="caption"></textarea></td>
    2772                 </tr>
    2773 ';
     2873                </tr>';
    27742874        } else {
    27752875                $caption = '';
     
    27772877
    27782878        $default_align = get_option( 'image_default_align' );
     2879
    27792880        if ( empty( $default_align ) ) {
    27802881                $default_align = 'none';
     
    28572958                        </td>
    28582959                </tr>
    2859         </tbody></table>
    2860 ';
    2861 
     2960        </tbody></table>';
    28622961}
    28632962
     
    29273026                $end = '</a>';
    29283027        }
     3028
    29293029        ?>
    2930 <p class="hide-if-no-js"><label>
    2931 <input name="image_resize" type="checkbox" id="image_resize" value="true"<?php echo $checked; ?> />
     3030        <p class="hide-if-no-js"><label>
     3031        <input name="image_resize" type="checkbox" id="image_resize" value="true"<?php echo $checked; ?> />
    29323032        <?php
    29333033        /* translators: 1: Link start tag, 2: Link end tag, 3: Width, 4: Height. */
    29343034        printf( __( 'Scale images to match the large size selected in %1$simage options%2$s (%3$d &times; %4$d).' ), $a, $end, (int) get_option( 'large_size_w', '1024' ), (int) get_option( 'large_size_h', '1024' ) );
     3035
    29353036        ?>
    2936 </label></p>
     3037        </label></p>
    29373038        <?php
    29383039}
     
    29603061function edit_form_image_editor( $post ) {
    29613062        $open = isset( $_GET['image-editor'] );
     3063
    29623064        if ( $open ) {
    29633065                require_once ABSPATH . 'wp-admin/includes/image-edit.php';
     
    29663068        $thumb_url     = false;
    29673069        $attachment_id = intval( $post->ID );
     3070
    29683071        if ( $attachment_id ) {
    29693072                $thumb_url = wp_get_attachment_image_src( $attachment_id, array( 900, 450 ), true );
     
    29763079        <div class="wp_attachment_holder wp-clearfix">
    29773080        <?php
     3081
    29783082        if ( wp_attachment_is_image( $post->ID ) ) :
    29793083                $image_edit_button = '';
     
    29853089                $open_style     = '';
    29863090                $not_open_style = '';
     3091
    29873092                if ( $open ) {
    29883093                        $open_style = ' style="display:none"';
     
    29903095                        $not_open_style = ' style="display:none"';
    29913096                }
     3097
    29923098                ?>
    2993 
    29943099                <div class="imgedit-response" id="imgedit-response-<?php echo $attachment_id; ?>"></div>
    29953100
     
    29993104                </div>
    30003105                <div<?php echo $not_open_style; ?> class="image-editor" id="image-editor-<?php echo $attachment_id; ?>">
    3001                         <?php
    3002                         if ( $open ) {
    3003                                 wp_image_editor( $attachment_id );}
    3004                         ?>
     3106                <?php
     3107
     3108                if ( $open ) {
     3109                        wp_image_editor( $attachment_id );
     3110                }
     3111
     3112                ?>
    30053113                </div>
    30063114                <?php
     
    30183126                $w    = ! empty( $meta['width'] ) ? min( $meta['width'], 640 ) : 0;
    30193127                $h    = ! empty( $meta['height'] ) ? $meta['height'] : 0;
     3128
    30203129                if ( $h && $w < $meta['width'] ) {
    30213130                        $h = round( ( $meta['height'] * $w ) / $meta['width'] );
     
    30233132
    30243133                $attr = array( 'src' => $att_url );
     3134
    30253135                if ( ! empty( $w ) && ! empty( $h ) ) {
    30263136                        $attr['width']  = $w;
     
    30293139
    30303140                $thumb_id = get_post_thumbnail_id( $attachment_id );
     3141
    30313142                if ( ! empty( $thumb_id ) ) {
    30323143                        $attr['poster'] = wp_get_attachment_url( $thumb_id );
     
    30363147
    30373148        elseif ( isset( $thumb_url[0] ) ) :
    3038 
    30393149                ?>
    30403150                <div class="wp_attachment_image wp-clearfix" id="media-head-<?php echo $attachment_id; ?>">
     
    30573167
    30583168        endif;
     3169
    30593170        ?>
    30603171        </div>
     
    30663177                </p>
    30673178                <p class="attachment-alt-text-description" id="alt-text-description">
    3068                         <?php
    3069                         printf(
    3070                                 /* translators: 1: Link to tutorial, 2: Additional link attributes, 3: Accessibility text. */
    3071                                 __( '<a href="%1$s" %2$s>Describe the purpose of the image%3$s</a>. Leave empty if the image is purely decorative.' ),
    3072                                 esc_url( 'https://www.w3.org/WAI/tutorials/images/decision-tree' ),
    3073                                 'target="_blank" rel="noopener noreferrer"',
    3074                                 sprintf(
    3075                                         '<span class="screen-reader-text"> %s</span>',
    3076                                         /* translators: Accessibility text. */
    3077                                         __( '(opens in a new tab)' )
    3078                                 )
    3079                         );
    3080                         ?>
     3179                <?php
     3180
     3181                printf(
     3182                        /* translators: 1: Link to tutorial, 2: Additional link attributes, 3: Accessibility text. */
     3183                        __( '<a href="%1$s" %2$s>Describe the purpose of the image%3$s</a>. Leave empty if the image is purely decorative.' ),
     3184                        esc_url( 'https://www.w3.org/WAI/tutorials/images/decision-tree' ),
     3185                        'target="_blank" rel="noopener noreferrer"',
     3186                        sprintf(
     3187                                '<span class="screen-reader-text"> %s</span>',
     3188                                /* translators: Accessibility text. */
     3189                                __( '(opens in a new tab)' )
     3190                        )
     3191                );
     3192
     3193                ?>
    30813194                </p>
    30823195        <?php endif; ?>
     
    30883201
    30893202        <?php
    3090                 $quicktags_settings = array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,close' );
    3091                 $editor_args        = array(
    3092                         'textarea_name' => 'content',
    3093                         'textarea_rows' => 5,
    3094                         'media_buttons' => false,
    3095                         'tinymce'       => false,
    3096                         'quicktags'     => $quicktags_settings,
    3097                 );
     3203
     3204        $quicktags_settings = array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,close' );
     3205        $editor_args        = array(
     3206                'textarea_name' => 'content',
     3207                'textarea_rows' => 5,
     3208                'media_buttons' => false,
     3209                'tinymce'       => false,
     3210                'quicktags'     => $quicktags_settings,
     3211        );
     3212
    30983213        ?>
    30993214
    31003215        <label for="attachment_content"><strong><?php _e( 'Description' ); ?></strong>
    3101                 <?php
    3102                 if ( preg_match( '#^(audio|video)/#', $post->post_mime_type ) ) {
    3103                         echo ': ' . __( 'Displayed on attachment pages.' );
    3104                 }
    3105                 ?>
     3216        <?php
     3217
     3218        if ( preg_match( '#^(audio|video)/#', $post->post_mime_type ) ) {
     3219                echo ': ' . __( 'Displayed on attachment pages.' );
     3220        }
     3221
     3222        ?>
    31063223        </label>
    31073224        <?php wp_editor( $post->post_content, 'attachment_content', $editor_args ); ?>
     
    31093226        </div>
    31103227        <?php
     3228
    31113229        $extras = get_compat_media_markup( $post->ID );
    31123230        echo $extras['item'];
     
    31203238 */
    31213239function attachment_submitbox_metadata() {
    3122         $post = get_post();
    3123 
    3124         $file     = get_attached_file( $post->ID );
     3240        $post          = get_post();
     3241        $attachment_id = $post->ID;
     3242
     3243        $file     = get_attached_file( $attachment_id );
    31253244        $filename = esc_html( wp_basename( $file ) );
    31263245
    31273246        $media_dims = '';
    3128         $meta       = wp_get_attachment_metadata( $post->ID );
     3247        $meta       = wp_get_attachment_metadata( $attachment_id );
     3248
    31293249        if ( isset( $meta['width'], $meta['height'] ) ) {
    3130                 $media_dims .= "<span id='media-dims-$post->ID'>{$meta['width']}&nbsp;&times;&nbsp;{$meta['height']}</span> ";
     3250                $media_dims .= "<span id='media-dims-$attachment_id'>{$meta['width']}&nbsp;&times;&nbsp;{$meta['height']}</span> ";
    31313251        }
    31323252        /** This filter is documented in wp-admin/includes/media.php */
    31333253        $media_dims = apply_filters( 'media_meta', $media_dims, $post );
    31343254
    3135         $att_url = wp_get_attachment_url( $post->ID );
     3255        $att_url = wp_get_attachment_url( $attachment_id );
     3256
    31363257        ?>
    31373258        <div class="misc-pub-section misc-pub-attachment">
     
    31433264        </div>
    31443265        <div class="misc-pub-section misc-pub-filetype">
    3145                 <?php _e( 'File type:' ); ?> <strong>
    3146                                         <?php
    3147                                         if ( preg_match( '/^.*?\.(\w+)$/', get_attached_file( $post->ID ), $matches ) ) {
    3148                                                 echo esc_html( strtoupper( $matches[1] ) );
    3149                                                 list( $mime_type ) = explode( '/', $post->post_mime_type );
    3150                                                 if ( $mime_type !== 'image' && ! empty( $meta['mime_type'] ) ) {
    3151                                                         if ( $meta['mime_type'] !== "$mime_type/" . strtolower( $matches[1] ) ) {
    3152                                                                 echo ' (' . $meta['mime_type'] . ')';
    3153                                                         }
    3154                                                 }
    3155                                         } else {
    3156                                                 echo strtoupper( str_replace( 'image/', '', $post->post_mime_type ) );
    3157                                         }
    3158                                         ?>
     3266                <?php _e( 'File type:' ); ?>
     3267                <strong>
     3268                <?php
     3269
     3270                if ( preg_match( '/^.*?\.(\w+)$/', get_attached_file( $post->ID ), $matches ) ) {
     3271                        echo esc_html( strtoupper( $matches[1] ) );
     3272                        list( $mime_type ) = explode( '/', $post->post_mime_type );
     3273                        if ( $mime_type !== 'image' && ! empty( $meta['mime_type'] ) ) {
     3274                                if ( $meta['mime_type'] !== "$mime_type/" . strtolower( $matches[1] ) ) {
     3275                                        echo ' (' . $meta['mime_type'] . ')';
     3276                                }
     3277                        }
     3278                } else {
     3279                        echo strtoupper( str_replace( 'image/', '', $post->post_mime_type ) );
     3280                }
     3281
     3282                ?>
    31593283                </strong>
    31603284        </div>
    31613285
    31623286        <?php
    3163                 $file_size = false;
     3287
     3288        $file_size = false;
    31643289
    31653290        if ( isset( $meta['filesize'] ) ) {
     
    31693294        }
    31703295
    3171         if ( ! empty( $file_size ) ) :
     3296        if ( ! empty( $file_size ) ) {
    31723297                ?>
    3173                         <div class="misc-pub-section misc-pub-filesize">
    3174                                 <?php _e( 'File size:' ); ?> <strong><?php echo size_format( $file_size ); ?></strong>
    3175                         </div>
    3176                         <?php
    3177                 endif;
     3298                <div class="misc-pub-section misc-pub-filesize">
     3299                        <?php _e( 'File size:' ); ?> <strong><?php echo size_format( $file_size ); ?></strong>
     3300                </div>
     3301                <?php
     3302        }
    31783303
    31793304        if ( preg_match( '#^(audio|video)/#', $post->post_mime_type ) ) {
     
    32013326                                continue;
    32023327                        }
     3328
    32033329                        ?>
    3204                 <div class="misc-pub-section misc-pub-mime-meta misc-pub-<?php echo sanitize_html_class( $key ); ?>">
    3205                         <?php echo $label; ?> <strong>
    3206                                                 <?php
    3207                                                 switch ( $key ) {
    3208                                                         case 'bitrate':
    3209                                                                 echo round( $meta['bitrate'] / 1000 ) . 'kb/s';
    3210                                                                 if ( ! empty( $meta['bitrate_mode'] ) ) {
    3211                                                                         echo ' ' . strtoupper( esc_html( $meta['bitrate_mode'] ) );
    3212                                                                 }
    3213                                                                 break;
    3214                                                         default:
    3215                                                                 echo esc_html( $meta[ $key ] );
    3216                                                                 break;
     3330                        <div class="misc-pub-section misc-pub-mime-meta misc-pub-<?php echo sanitize_html_class( $key ); ?>">
     3331                                <?php echo $label; ?>
     3332                                <strong>
     3333                                <?php
     3334
     3335                                switch ( $key ) {
     3336                                        case 'bitrate':
     3337                                                echo round( $meta['bitrate'] / 1000 ) . 'kb/s';
     3338                                                if ( ! empty( $meta['bitrate_mode'] ) ) {
     3339                                                        echo ' ' . strtoupper( esc_html( $meta['bitrate_mode'] ) );
    32173340                                                }
    3218                                                 ?>
    3219                         </strong>
    3220                 </div>
     3341                                                break;
     3342                                        default:
     3343                                                echo esc_html( $meta[ $key ] );
     3344                                                break;
     3345                                }
     3346
     3347                                ?>
     3348                                </strong>
     3349                        </div>
    32213350                        <?php
    32223351                }
     
    32453374                                continue;
    32463375                        }
     3376
    32473377                        ?>
    3248                 <div class="misc-pub-section misc-pub-audio misc-pub-<?php echo sanitize_html_class( $key ); ?>">
    3249                         <?php echo $label; ?> <strong><?php echo esc_html( $meta['audio'][ $key ] ); ?></strong>
     3378                        <div class="misc-pub-section misc-pub-audio misc-pub-<?php echo sanitize_html_class( $key ); ?>">
     3379                                <?php echo $label; ?> <strong><?php echo esc_html( $meta['audio'][ $key ] ); ?></strong>
     3380                        </div>
     3381                        <?php
     3382                }
     3383        }
     3384
     3385        if ( $media_dims ) {
     3386                ?>
     3387                <div class="misc-pub-section misc-pub-dimensions">
     3388                        <?php _e( 'Dimensions:' ); ?> <strong><?php echo $media_dims; ?></strong>
    32503389                </div>
    3251                         <?php
    3252                 }
    3253         }
    3254 
    3255         if ( $media_dims ) :
    3256                 ?>
    3257         <div class="misc-pub-section misc-pub-dimensions">
    3258                 <?php _e( 'Dimensions:' ); ?> <strong><?php echo $media_dims; ?></strong>
    3259         </div>
    32603390                <?php
    3261         endif;
     3391        }
    32623392}
    32633393
     
    33293459                require( ABSPATH . WPINC . '/ID3/getid3.php' );
    33303460        }
     3461
    33313462        $id3  = new getID3();
    33323463        $data = $id3->analyze( $file );
     
    33353466                $metadata['lossless'] = $data['video']['lossless'];
    33363467        }
     3468
    33373469        if ( ! empty( $data['video']['bitrate'] ) ) {
    33383470                $metadata['bitrate'] = (int) $data['video']['bitrate'];
    33393471        }
     3472
    33403473        if ( ! empty( $data['video']['bitrate_mode'] ) ) {
    33413474                $metadata['bitrate_mode'] = $data['video']['bitrate_mode'];
    33423475        }
     3476
    33433477        if ( ! empty( $data['filesize'] ) ) {
    33443478                $metadata['filesize'] = (int) $data['filesize'];
    33453479        }
     3480
    33463481        if ( ! empty( $data['mime_type'] ) ) {
    33473482                $metadata['mime_type'] = $data['mime_type'];
    33483483        }
     3484
    33493485        if ( ! empty( $data['playtime_seconds'] ) ) {
    33503486                $metadata['length'] = (int) round( $data['playtime_seconds'] );
    33513487        }
     3488
    33523489        if ( ! empty( $data['playtime_string'] ) ) {
    33533490                $metadata['length_formatted'] = $data['playtime_string'];
    33543491        }
     3492
    33553493        if ( ! empty( $data['video']['resolution_x'] ) ) {
    33563494                $metadata['width'] = (int) $data['video']['resolution_x'];
    33573495        }
     3496
    33583497        if ( ! empty( $data['video']['resolution_y'] ) ) {
    33593498                $metadata['height'] = (int) $data['video']['resolution_y'];
    33603499        }
     3500
    33613501        if ( ! empty( $data['fileformat'] ) ) {
    33623502                $metadata['fileformat'] = $data['fileformat'];
    33633503        }
     3504
    33643505        if ( ! empty( $data['video']['dataformat'] ) ) {
    33653506                $metadata['dataformat'] = $data['video']['dataformat'];
    33663507        }
     3508
    33673509        if ( ! empty( $data['video']['encoder'] ) ) {
    33683510                $metadata['encoder'] = $data['video']['encoder'];
    33693511        }
     3512
    33703513        if ( ! empty( $data['video']['codec'] ) ) {
    33713514                $metadata['codec'] = $data['video']['codec'];
     
    34173560                return false;
    34183561        }
     3562
    34193563        $metadata = array();
    34203564
     
    34263570                require( ABSPATH . WPINC . '/ID3/getid3.php' );
    34273571        }
     3572
    34283573        $id3  = new getID3();
    34293574        $data = $id3->analyze( $file );
     
    34373582                $metadata['fileformat'] = $data['fileformat'];
    34383583        }
     3584
    34393585        if ( ! empty( $data['filesize'] ) ) {
    34403586                $metadata['filesize'] = (int) $data['filesize'];
    34413587        }
     3588
    34423589        if ( ! empty( $data['mime_type'] ) ) {
    34433590                $metadata['mime_type'] = $data['mime_type'];
    34443591        }
     3592
    34453593        if ( ! empty( $data['playtime_seconds'] ) ) {
    34463594                $metadata['length'] = (int) round( $data['playtime_seconds'] );
    34473595        }
     3596
    34483597        if ( ! empty( $data['playtime_string'] ) ) {
    34493598                $metadata['length_formatted'] = $data['playtime_string'];
     
    35323681                wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
    35333682        }
     3683
    35343684        $ids = array();
     3685
    35353686        foreach ( (array) $_REQUEST['media'] as $att_id ) {
    35363687                $att_id = (int) $att_id;
     
    35453696        if ( ! empty( $ids ) ) {
    35463697                $ids_string = implode( ',', $ids );
     3698
    35473699                if ( 'attach' === $action ) {
    35483700                        $result = $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ( $ids_string )", $parent_id ) );
     
    35593711                $location = 'upload.php';
    35603712                $referer  = wp_get_referer();
     3713
    35613714                if ( $referer ) {
    35623715                        if ( false !== strpos( $referer, 'upload.php' ) ) {
     
    35673720                $key      = 'attach' === $action ? 'attached' : 'detach';
    35683721                $location = add_query_arg( array( $key => $result ), $location );
     3722
    35693723                wp_redirect( $location );
    35703724                exit;
  • trunk/src/wp-includes/script-loader.php

    r45932 r45934  
    11261126                'missing_upload_url'        => __( 'There was a configuration error. Please contact the server administrator.' ),
    11271127                'upload_limit_exceeded'     => __( 'You may only upload 1 file.' ),
    1128                 'http_error'                => __( 'HTTP error.' ),
     1128                'http_error'                => __( 'Unexpected response from the server. The file may have been uploaded successfully. Check in the Media Library or reload the page.' ),
     1129                'http_error_image'          => __( 'Post-processing of the image failed. If this is a photo or a large image, please scale it down to 2500px and upload it again.' ),
    11291130                'upload_failed'             => __( 'Upload failed.' ),
    11301131                /* translators: 1: Opening link tag, 2: Closing link tag. */
Note: See TracChangeset for help on using the changeset viewer.