@@ -92,6 +92,7 @@ public function enqueue_scripts( $hook ) {
9292 'maxFileSize ' => $ max_file_size ,
9393 'attachmentId ' => $ id ,
9494 'mimeType ' => $ mime_type ,
95+ 'nonce ' => wp_create_nonce ( 'optml_replace_media_nonce ' ),
9596 'i18n ' => [
9697 'maxFileSizeError ' => $ max_file_size_error ,
9798 'replaceFileError ' => __ ( 'Error replacing file ' , 'optimole-wp ' ),
@@ -329,7 +330,17 @@ public function save_attachment_filename( $post_id ) {
329330 * Replace the file
330331 */
331332 public function replace_file () {
332- $ id = (int ) sanitize_text_field ( $ _POST ['attachment_id ' ] );
333+ check_ajax_referer ( 'optml_replace_media_nonce ' , 'optml_replace_nonce ' );
334+
335+ $ id = absint ( $ _POST ['attachment_id ' ] ?? 0 );
336+
337+ if ( ! $ id ) {
338+ wp_send_json_error ( __ ( 'Invalid attachment ID ' , 'optimole-wp ' ) );
339+ }
340+
341+ if ( get_post_type ( $ id ) !== 'attachment ' ) {
342+ wp_send_json_error ( __ ( 'Invalid attachment ID ' , 'optimole-wp ' ) );
343+ }
333344
334345 if ( ! current_user_can ( 'edit_post ' , $ id ) ) {
335346 wp_send_json_error ( __ ( 'You are not allowed to replace this file ' , 'optimole-wp ' ) );
@@ -339,6 +350,17 @@ public function replace_file() {
339350 wp_send_json_error ( __ ( 'No file uploaded ' , 'optimole-wp ' ) );
340351 }
341352
353+ $ file_info = wp_check_filetype_and_ext ( $ _FILES ['file ' ]['tmp_name ' ], $ _FILES ['file ' ]['name ' ] );
354+
355+ if ( empty ( $ file_info ['type ' ] ) ) {
356+ wp_send_json_error ( __ ( 'Could not determine uploaded file type ' , 'optimole-wp ' ) );
357+ }
358+
359+ $ original_mime = get_post_mime_type ( $ id );
360+ if ( $ file_info ['type ' ] !== $ original_mime ) {
361+ wp_send_json_error ( __ ( 'Uploaded file type does not match the original attachment ' , 'optimole-wp ' ) );
362+ }
363+
342364 $ replacer = new Optml_Attachment_Replace ( $ id , $ _FILES ['file ' ] );
343365
344366 $ replaced = $ replacer ->replace ();
0 commit comments