Skip to content

Commit

Permalink
Upload Requests: add server-side restrictions
Browse files Browse the repository at this point in the history
Fixes #456
  • Loading branch information
swissspidy committed Jun 21, 2024
1 parent b7ea974 commit 8a7cb5d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
29 changes: 29 additions & 0 deletions inc/class-rest-attachments-controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -300,8 +300,37 @@ static function () use ( &$before_metadata ) {
}
// @codeCoverageIgnoreEnd

$filter_upload_mimes = null;

if ( $upload_request ) {
$allowed_types = get_post_meta( $upload_request->ID, 'mexp_allowed_types', true );

/**
* Filters list of mime types based on upload request restrictions.
*
* @param array $types Mime types keyed by the file extension regex corresponding to those types.
*
* @return array Filtered list of mime types.
*/
$filter_upload_mimes = static function ( array $types ) use ( $allowed_types ) {
return array_filter(
$types,
static function ( $mime_type ) use ( $allowed_types ) {
$file_type = explode( '/', $mime_type )[0];
return in_array( $file_type, $allowed_types, true );
}
);
};

add_filter( 'upload_mimes', $filter_upload_mimes );
}

$response = parent::create_item( $request );

if ( $upload_request ) {
remove_filter( 'upload_mimes', $filter_upload_mimes );
}

// @codeCoverageIgnoreStart
if ( function_exists( 'perflab_server_timing_register_metric' ) && ! empty( $before_metadata ) ) {
perflab_server_timing_register_metric(
Expand Down
22 changes: 21 additions & 1 deletion inc/templates/upload-request.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,27 @@
$allowed_types = get_post_meta( $post->ID, 'mexp_allowed_types', true );
$accept = get_post_meta( $post->ID, 'mexp_accept', true );
$multiple = (bool) get_post_meta( $post->ID, 'mexp_multiple', true );

add_filter(
'upload_mimes',
/**
* Filters list of mime types based on upload request restrictions.
*
* @param array $types Mime types keyed by the file extension regex corresponding to those types.
*
* @return array Filtered list of mime types.
*/
static function ( array $types ) use ( $allowed_types ) {
return array_filter(
$types,
static function ( $mime_type ) use ( $allowed_types ) {
$file_type = explode( '/', $mime_type )[0];
return in_array( $file_type, $allowed_types, true );
}
);
}
);

// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals

wp_add_inline_script(
Expand All @@ -51,7 +72,6 @@
window.mediaExperiments.allowedTypes = %3$s;
window.mediaExperiments.accept = %4$s;
window.mediaExperiments.multiple = %5$s;',
// TODO: Only provide mime types allowed for this upload request.
wp_json_encode( get_allowed_mime_types() ),
wp_json_encode( $post->post_name ),
wp_json_encode( $allowed_types ? (array) $allowed_types : null ),
Expand Down

0 comments on commit 8a7cb5d

Please sign in to comment.