Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 66 additions & 2 deletions src/js/_enqueues/vendor/plupload/plupload.js
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,20 @@ plupload.addFileFilter('mime_types', function(filters, file, cb) {
});


plupload.addFileFilter('context_extensions', function(extensions, file, cb) {
if (plupload.inArray(o.Mime.getFileExtension(file.name), extensions) === -1) {
this.trigger('Error', {
code: plupload.FILE_EXTENSION_ERROR,
message: plupload.translate('File extension error.'),
file: file
});
cb(false);
} else {
cb(true);
}
});


plupload.addFileFilter('max_file_size', function(maxSize, file, cb) {
var undef;

Expand Down Expand Up @@ -730,6 +744,7 @@ plupload.addFileFilter('prevent_duplicates', function(value, file, cb) {
@param {String|DOMElement} [settings.container] id of the DOM element or DOM element itself that will be used to wrap uploader structures. Defaults to immediate parent of the `browse_button` element.
@param {String|DOMElement} [settings.drop_element] id of the DOM element or DOM element itself to use as a drop zone for Drag-n-Drop.
@param {String} [settings.file_data_name="file"] Name for the file field in Multipart formated message.
@param {Array|null} [settings.context_extensions=null] Additional allowed extensions for the current context. An empty array rejects all types.
@param {Object} [settings.filters={}] Set of file type filters.
@param {Array} [settings.filters.mime_types=[]] List of file types to accept, each one defined by title and list of extensions. `e.g. {title : "Image files", extensions : "jpg,jpeg,gif,png"}`. Dispatches `plupload.FILE_EXTENSION_ERROR`
@param {String|Number} [settings.filters.max_file_size=0] Maximum file size that the user can pick, in bytes. Optionally supports b, kb, mb, gb, tb suffixes. `e.g. "10mb" or "1gb"`. By default - not set. Dispatches `plupload.FILE_SIZE_ERROR`.
Expand Down Expand Up @@ -1041,6 +1056,41 @@ plupload.Uploader = function(options) {
}


// Native accept attributes must follow the current extension filters, even for custom MIME types.
function updateFileInputFilters() {
var types = settings.filters.mime_types || [],
context = settings.context_extensions,
extensions = [], unrestricted = false;

if (context) {
plupload.each(context, function(extension) {
if (!types.length || types.regexp.test('file.' + extension)) {
extensions.push('.' + extension);
}
});
} else {
plupload.each(types, function(filter) {
plupload.each(filter.extensions.split(/\s*,\s*/), function(extension) {
if (extension === '*') {
unrestricted = true;
} else if (extension) {
extensions.push('.' + extension);
}
});
});
}

plupload.each(fileInputs, function(fileInput) {
var container = plupload.get(fileInput.shimid);
if (container) {
plupload.each(container.getElementsByTagName('input'), function(input) {
input.setAttribute('accept', unrestricted ? '' : extensions.join(','));
});
}
});
}


function initControls(settings, cb) {
var self = this, inited = 0, queue = [];

Expand Down Expand Up @@ -1082,6 +1132,7 @@ plupload.Uploader = function(options) {

inited++;
fileInputs.push(this);
updateFileInputFilters();
cb();
};

Expand Down Expand Up @@ -1238,6 +1289,11 @@ plupload.Uploader = function(options) {
}
break;

case 'context_extensions':
settings.context_extensions = value;
updateFileInputFilters();
break;

case 'filters':
// for sake of backward compatibility
if (plupload.typeOf(value) === 'array') {
Expand Down Expand Up @@ -1270,6 +1326,7 @@ plupload.Uploader = function(options) {
return new RegExp('(' + extensionsRegExp.join('|') + ')$', 'i');
}(settings.filters.mime_types));
}
updateFileInputFilters();
break;

case 'resize':
Expand Down Expand Up @@ -1659,6 +1716,7 @@ plupload.Uploader = function(options) {
multipart: true,
multi_selection: true,
file_data_name: 'file',
context_extensions: null,
filters: {
mime_types: [],
prevent_duplicates: false,
Expand Down Expand Up @@ -1845,6 +1903,7 @@ plupload.Uploader = function(options) {
*/
refresh : function() {
if (fileInputs.length) {
updateFileInputFilters();
plupload.each(fileInputs, function(fileInput) {
fileInput.trigger('Refresh');
});
Expand Down Expand Up @@ -1932,8 +1991,13 @@ plupload.Uploader = function(options) {
;

function filterFile(file, cb) {
var queue = [];
o.each(self.settings.filters, function(rule, name) {
var queue = [], filters = plupload.extend({}, self.settings.filters);

// Keep context restrictions separate from plugin-owned filters.
if (self.settings.context_extensions) {
filters.context_extensions = self.settings.context_extensions;
}
o.each(filters, function(rule, name) {
if (fileFilters[name]) {
queue.push(function(cb) {
fileFilters[name].call(self, rule, file, function(res) {
Expand Down
46 changes: 46 additions & 0 deletions src/js/_enqueues/vendor/plupload/wp-plupload.js
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,31 @@ window.wp = window.wp || {};
} );
} );

/**
* Rechecks file types before upload handlers consume an accepted batch.
*
* A context can change after FileFiltered. Run before both the classic
* handler and the client-side media pipeline's priority-100 handler.
*
* @param {plupload.Uploader} up Uploader instance.
* @param {Array} files Files originally accepted by Plupload.
*/
this.uploader.bind( 'FilesAdded', function( up, files ) {
var index, file;

for ( index = files.length - 1; index >= 0; index-- ) {
file = files[ index ];
if ( ! self.isFileTypeSupported( file ) ) {
up.trigger( 'Error', {
code: plupload.FILE_EXTENSION_ERROR,
file: file
} );
files.splice( index, 1 );
up.removeFile( file );
}
}
}, this, 1000 );

/**
* After files were filtered and added to the queue, create a model for each.
*
Expand Down Expand Up @@ -458,6 +483,10 @@ window.wp = window.wp || {};
}
}

if ( pluploadError.code === plupload.FILE_EXTENSION_ERROR && up.getOption( 'context_extensions' ) ) {
message = pluploadL10n.unsupported_filetype;
}

error( message, pluploadError, pluploadError.file );
up.refresh();
});
Expand Down Expand Up @@ -494,6 +523,23 @@ window.wp = window.wp || {};
};

$.extend( Uploader.prototype, /** @lends wp.Uploader.prototype */{
/**
* Checks a file against the uploader's current extension filters.
*
* @since 7.2.0
*
* @param {plupload.File} file The file to check.
* @return {boolean} Whether the file type is allowed.
*/
isFileTypeSupported: function( file ) {
var types = this.uploader.getOption( 'filters' ).mime_types,
context = this.uploader.getOption( 'context_extensions' ),
extension = /\.([^.]+)$/.exec( file.name );

return ( ! types || ! types.length || types.regexp.test( file.name ) ) &&
( ! context || !! extension && _.contains( context, extension[1].toLowerCase() ) );
},

/**
* Acts as a shortcut to extending the uploader's multipart_params object.
*
Expand Down
8 changes: 7 additions & 1 deletion src/js/media/controllers/library.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,13 @@ Library = wp.media.controller.State.extend(/** @lends wp.media.controller.Librar
* @param {wp.media.model.Attachment} attachment The attachment that was uploaded.
*/
uploading: function( attachment ) {
var content = this.frame.content;
var content = this.frame.content,
uploader = this.frame.uploader && this.frame.uploader.uploader;

// The shared queue can contain uploads from a different media context.
if ( uploader && ! uploader.isFileTypeSupported( attachment.get( 'file' ) || { name: attachment.get( 'filename' ) } ) ) {
return;
}

if ( 'upload' === content.mode() ) {
this.frame.content.mode('browse');
Expand Down
17 changes: 17 additions & 0 deletions src/js/media/views/frame.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,23 @@ var Frame = wp.media.View.extend(/** @lends wp.media.view.Frame.prototype */{
this.states.invoke( 'trigger', 'reset' );
return this;
},

/**
* Deactivates the current state before removing the frame and its views.
*
* @since 7.2.0
*
* @return {wp.media.view.Frame} The removed frame.
*/
remove: function() {
var state = this.state();

if ( state && state.active ) {
state.trigger( 'deactivate' );
}

return wp.media.View.prototype.remove.apply( this, arguments );
},
/**
* Map activeMode collection events to the frame.
*
Expand Down
56 changes: 55 additions & 1 deletion src/js/media/views/uploader/window.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ UploaderWindow = wp.media.View.extend(/** @lends wp.media.view.UploaderWindow.pr
uploader.dropzone = $( uploader.dropzone );
}

this.controller.on( 'activate', this.refresh, this );
this.controller.on( 'activate change:library', this.refresh, this );

this.controller.on( 'detach', function() {
this.$browser.remove();
Expand All @@ -49,10 +49,63 @@ UploaderWindow = wp.media.View.extend(/** @lends wp.media.view.UploaderWindow.pr

refresh: function() {
if ( this.uploader ) {
this.updateUploadFilters();
this.uploader.refresh();
}
},

/**
* Restricts uploads to the active library's media types.
*
* @since 7.2.0
*/
updateUploadFilters: function() {
var uploader = this.uploader.uploader,
state = this.controller.state(),
library = state && state.get( 'library' ),
types = library && library.props.get( 'type' ),
extensions = null;

if ( this._uploadLibrary !== library ) {
if ( this._uploadLibrary ) {
this.stopListening( this._uploadLibrary.props );
}
this._uploadLibrary = library;
if ( library ) {
this.listenTo( library.props, 'change:type', this.refresh );
}
}

types = _.chain( _.isArray( types ) ? types : [ types ] )
.map( function( type ) { return type ? type.split( ',' ) : []; } )
.flatten()
.map( function( type ) { return type.trim().toLowerCase(); } )
.compact()
.value();

if ( types.length && ! _.contains( types, '*' ) && wp.Uploader.mimeTypes ) {
extensions = [];
_.each( wp.Uploader.mimeTypes, function( mime, pattern ) {
var matches;

mime = mime.toLowerCase();
matches = _.some( types, function( type ) {
return type === mime || type === mime.split( '/' )[0] || type === mime.split( '/' )[0] + '/*';
} );

if ( matches ) {
extensions = extensions.concat( pattern.toLowerCase().split( '|' ) );
}
} );
extensions = _.uniq( extensions );
}

// Context is independent of plugin-owned filters, including identical MIME lists.
if ( ! _.isEqual( extensions, uploader.getOption( 'context_extensions' ) ) ) {
uploader.setOption( 'context_extensions', extensions );
}
},

ready: function() {
var postId = wp.media.view.settings.post.id,
dropzone;
Expand All @@ -66,6 +119,7 @@ UploaderWindow = wp.media.View.extend(/** @lends wp.media.view.UploaderWindow.pr
this.options.uploader.params.post_id = postId;
}
this.uploader = new wp.Uploader( this.options.uploader );
this.refresh();

dropzone = this.uploader.dropzone;
dropzone.on( 'dropzone:enter', _.bind( this.show, this ) );
Expand Down
4 changes: 3 additions & 1 deletion src/wp-includes/media.php
Original file line number Diff line number Diff line change
Expand Up @@ -4511,7 +4511,8 @@ function wp_plupload_default_settings() {
}

$max_upload_size = wp_max_upload_size();
$allowed_extensions = array_keys( get_allowed_mime_types() );
$allowed_mime_types = get_allowed_mime_types();
$allowed_extensions = array_keys( $allowed_mime_types );
$extensions = array();
foreach ( $allowed_extensions as $extension ) {
$extensions = array_merge( $extensions, explode( '|', $extension ) );
Expand Down Expand Up @@ -4585,6 +4586,7 @@ function wp_plupload_default_settings() {

$settings = array(
'defaults' => $defaults,
'mimeTypes' => $allowed_mime_types,
'browser' => array(
'mobile' => wp_is_mobile(),
'supported' => _device_can_upload(),
Expand Down
1 change: 1 addition & 0 deletions src/wp-includes/script-loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -995,6 +995,7 @@ function wp_default_scripts( $scripts ) {
'file_exceeds_size_limit' => __( '%s exceeds the maximum upload size for this site.' ),
'zero_byte_file' => __( 'This file is empty. Please try another.' ),
'invalid_filetype' => __( 'This file cannot be processed by the web server.' ),
'unsupported_filetype' => __( 'This file type is not supported here.' ),
'not_an_image' => __( 'This file is not an image. Please try another.' ),
'image_memory_exceeded' => __( 'Memory exceeded. Please try another smaller file.' ),
'image_dimensions_exceeded' => __( 'This is larger than the maximum size. Please try another.' ),
Expand Down
33 changes: 33 additions & 0 deletions tests/phpunit/tests/media.php
Original file line number Diff line number Diff line change
Expand Up @@ -8011,6 +8011,39 @@ public function test_wp_show_heic_upload_error_omits_flag_when_supported() {
$this->assertArrayHasKey( 'existing', $result, 'Existing array keys are expected to be preserved.' );
$this->assertSame( 'value', $result['existing'], 'Existing array values are expected to remain unmodified.' );
}

/**
* The uploader needs the filtered MIME mapping to restrict uploads by context.
*
* @ticket 48710
* @covers ::wp_plupload_default_settings
*/
public function test_wp_plupload_default_settings_exposes_filtered_mime_types() {
$scripts = wp_scripts();
$previous_data = $scripts->registered['wp-plupload']->extra;
$custom_mime = static function ( $mimes ) {
$mimes['example'] = 'image/x-example';
unset( $mimes['pdf'] );
return $mimes;
};

add_filter( 'upload_mimes', $custom_mime );
$scripts->add_data( 'wp-plupload', 'data', '' );

try {
wp_plupload_default_settings();
$data = $scripts->get_data( 'wp-plupload', 'data' );
$settings = json_decode( substr( $data, strlen( 'var _wpPluploadSettings = ' ), -1 ), true );

$this->assertArrayHasKey( 'mimeTypes', $settings );
$this->assertSame( get_allowed_mime_types(), $settings['mimeTypes'] );
$this->assertSame( 'image/x-example', $settings['mimeTypes']['example'] );
$this->assertArrayNotHasKey( 'pdf', $settings['mimeTypes'] );
} finally {
remove_filter( 'upload_mimes', $custom_mime );
$scripts->registered['wp-plupload']->extra = $previous_data;
}
}
}

/**
Expand Down
5 changes: 5 additions & 0 deletions tests/qunit/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@
window.pluploadL10n = {"queue_limit_exceeded":"You have attempted to queue too many files.","file_exceeds_size_limit":"%s exceeds the maximum upload size for this site.","zero_byte_file":"This file is empty. Please try another.","invalid_filetype":"Sorry, you are not allowed to upload this file type.","not_an_image":"This file is not an image. Please try another.","image_memory_exceeded":"Memory exceeded. Please try another smaller file.","image_dimensions_exceeded":"This is larger than the maximum size. Please try another.","default_error":"An error occurred in the upload. Please try again later.","missing_upload_url":"There was a configuration error. Please contact the server administrator.","upload_limit_exceeded":"You may only upload 1 file.","http_error":"HTTP error.","upload_failed":"Upload failed.","big_upload_failed":"Please try uploading this file with the %1$sbrowser uploader%2$s.","big_upload_queued":"%s exceeds the maximum upload size for the multi-file uploader when used in your browser.","io_error":"IO error.","security_error":"Security error.","file_cancelled":"File canceled.","upload_stopped":"Upload stopped.","dismiss":"Dismiss","crunching":"Crunching\u2026","deleted":"moved to the Trash.","error_uploading":"\u201c%s\u201d has failed to upload."};
window._wpPluploadSettings = {"defaults":{"runtimes":"html5,flash,silverlight,html4","file_data_name":"async-upload","url":"\/wp-admin\/async-upload.php","flash_swf_url":"http:\/\/src.wordpress-develop.dev\/wp-includes\/js\/plupload\/plupload.flash.swf","silverlight_xap_url":"http:\/\/src.wordpress-develop.dev\/wp-includes\/js\/plupload\/plupload.silverlight.xap","filters":{"max_file_size":"2097152b","mime_types":[{"extensions":"jpg,jpeg,jpe,gif,png,bmp,tiff,tif,ico,asf,asx,wmv,wmx,wm,avi,divx,flv,mov,qt,mpeg,mpg,mpe,mp4,m4v,ogv,webm,mkv,3gp,3gpp,3g2,3gp2,txt,asc,c,cc,h,srt,csv,tsv,ics,rtx,css,vtt,dfxp,mp3,m4a,m4b,ra,ram,wav,ogg,oga,mid,midi,wma,wax,mka,rtf,js,pdf,class,tar,zip,gz,gzip,rar,7z,psd,xcf,doc,pot,pps,ppt,wri,xla,xls,xlt,xlw,mdb,mpp,docx,docm,dotx,dotm,xlsx,xlsm,xlsb,xltx,xltm,xlam,pptx,pptm,ppsx,ppsm,potx,potm,ppam,sldx,sldm,onetoc,onetoc2,onetmp,onepkg,oxps,xps,odt,odp,ods,odg,odc,odb,odf,wp,wpd,key,numbers,pages"}]},"multipart_params":{"action":"upload-attachment","_wpnonce":"87fa5740b8"}},"browser":{"mobile":false,"supported":true},"limitExceeded":false};
</script>
<script>
window.pluploadL10n.unsupported_filetype = 'This file type is not supported here.';
</script>
<script src="../../build/wp-includes/js/plupload/moxie.js"></script>
<script src="../../build/wp-includes/js/plupload/plupload.js"></script>
<script src="../../build/wp-includes/js/plupload/wp-plupload.js"></script>
<script>
window.mejsL10n = {"language":"en-US","strings":{"Close":"Close","Fullscreen":"Fullscreen","Turn off Fullscreen":"Turn off Fullscreen","Go Fullscreen":"Go Fullscreen","Download File":"Download File","Download Video":"Download Video","Play":"Play","Pause":"Pause","Captions\/Subtitles":"Captions\/Subtitles","None":"None","Time Slider":"Time Slider","Skip back %1 seconds":"Skip back %1 seconds","Video Player":"Video Player","Audio Player":"Audio Player","Volume Slider":"Volume Slider","Mute Toggle":"Mute Toggle","Unmute":"Unmute","Mute":"Mute","Use Up\/Down Arrow keys to increase or decrease volume.":"Use Up\/Down Arrow keys to increase or decrease volume.","Use Left\/Right Arrow keys to advance one second, Up\/Down arrows to advance ten seconds.":"Use Left\/Right Arrow keys to advance one second, Up\/Down arrows to advance ten seconds."}};
Expand Down
Loading
Loading