Skip to content

Commit

Permalink
fix PDF thumbs, mime type comparisson and error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Hugo Solar committed Jul 9, 2024
1 parent 969872c commit a443bff
Show file tree
Hide file tree
Showing 4 changed files with 118 additions and 48 deletions.
108 changes: 61 additions & 47 deletions includes/class-windows-azure-replace-media.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,20 +64,20 @@ class Windows_Azure_Replace_Media {
*/

public function __construct() {
// Add fields to attachment editor
// Add fields to attachment editor.
add_filter( 'attachment_fields_to_edit', array( $this, 'register_azure_fields_attachment_editor' ), 10, 2 );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_replace_media_script' ) );

// ajax event to replace media
// ajax event to replace media.
add_action( 'wp_ajax_azure-storage-media-replace', array( $this, 'process_media_replacement' ) );

/**
* Set a list of mime types allowed to be replaced.
*
* azure_blob_storage_allowed_types_replace filters the default list of mime types allowed to be replaced, for now just common images and pdf files.
*
*
* Azure_blob_storage_allowed_types_replace filters the default list of mime types allowed to be replaced, for now just common images and pdf files.
*
* @since 4.2.3
*
*
* @param array $types array of allowed mime types
*/
$this->allowed_types = apply_filters(
Expand All @@ -97,8 +97,8 @@ public function __construct() {
/**
* Register replace media button
*
* @param array $form_fields Form fields
* @param WP_Post $post the post ID
* @param array $form_fields Form fields.
* @param WP_Post $post the post ID.
* @return array
*/
public function register_azure_fields_attachment_editor( $form_fields, $post ) {
Expand All @@ -117,7 +117,7 @@ public function register_azure_fields_attachment_editor( $form_fields, $post ) {
'html' => sprintf( '<button class="button-secondary" id="azure-media-replacement" onclick="replaceMedia(%d);"> %s </button>', $post->ID, esc_html__( 'Replace this media', 'windows-azure-storage' ) ),
);
}

return $form_fields;
}

Expand All @@ -129,7 +129,7 @@ public function register_azure_fields_attachment_editor( $form_fields, $post ) {
public function enqueue_replace_media_script() {
$js_ext = ( ! defined( 'SCRIPT_DEBUG' ) || false === SCRIPT_DEBUG ) ? '.min.js' : '.js';
wp_enqueue_script( 'windows-azure-storage-media-replace', MSFT_AZURE_PLUGIN_URL . 'js/windows-azure-storage-media-replace' . $js_ext, array( 'jquery', 'media-editor' ), MSFT_AZURE_PLUGIN_VERSION, true );

wp_localize_script(
'windows-azure-storage-media-replace',
'AzureMediaReplaceObject',
Expand All @@ -140,14 +140,14 @@ public function enqueue_replace_media_script() {
'title' => __( 'Replace this media', 'windows-azure-storage' ),
'replaceMediaButton' => __( 'Replace media', 'windows-azure-storage' ),
),
)
),
);
}

/**
* Ajax handler to process replace request
*
* @return void
* @return mixed
*/
public function process_media_replacement() {

Expand All @@ -161,44 +161,46 @@ public function process_media_replacement() {
$replace_attachment = filter_input( INPUT_POST, 'replace_attachment', FILTER_VALIDATE_INT );

$this->container_name = \Windows_Azure_Helper::get_default_container();
$response = $this->replace_media_with( $current_attachment, $replace_attachment );

wp_send_json( $this->replace_media_with( $current_attachment, $replace_attachment ) );
if ( ! is_wp_error( $response ) ) {
wp_send_json( $response );
} else {
wp_send_json_error( $response->get_error_message() );
}
}

/**
* Replace media id with another id
*
* @param int $source_attachment_id Source attachment ID
* @param int $media_to_replace_id Replacement file ID
* @return Mixed
* @return mixed
*/
private function replace_media_with( $source_attachment_id, $media_to_replace_id ) {
if ( empty( $source_attachment_id ) || empty( $media_to_replace_id ) ) {
return esc_html__( 'Cannot determine images IDs, aborting...', 'windows-azure-storage' );
return new WP_Error( 'missing_ids', __( 'Cannot determine images IDs, aborting...', 'windows-azure-storage' ) );
}

$source_file = get_post_meta( $source_attachment_id, '_wp_attached_file', true );
$replace_file = get_post_meta( $media_to_replace_id, '_wp_attached_file', true );

if ( empty( $source_file ) || empty( $replace_file ) ) {
return esc_html__( 'Path issues, aborting...', 'windows-azure-storage' );
return new WP_Error( 'path_issues', __( 'Path issues, aborting...', 'windows-azure-storage' ) );
}

$source_filetype = wp_check_filetype( $source_file );
$replace_filetype = wp_check_filetype( $replace_file );

if ( empty( $source_filetype['type'] ) && empty( $replace_filetype['type'] ) ) {
return esc_html__( 'Cannot determine file type, aborting...', 'windows-azure-storage' );
return new WP_Error( 'file_type_error', __( 'Cannot determine file type, aborting...', 'windows-azure-storage' ) );
}

$source_media_type = explode( '/', $source_filetype['type'] );
$replace_media_type = explode( '/', $replace_filetype['type'] );

if ( ( is_array( $source_media_type ) && is_array( $replace_filetype ) ) && ( $source_media_type[0] !== $replace_media_type[0] ) ) {
return esc_html__( 'File type mismatch', 'windows-azure-storage' );
if ( $source_filetype['type'] !== $replace_filetype['type'] ) {
return new WP_Error( 'file_type_mismatch', __( 'File type mismatch', 'windows-azure-storage' ) );
}

// only upload file if file exists locally
// only upload file if file exists locally.
try {
$full_blob_url = \Windows_Azure_Helper::get_full_blob_url( $replace_file );
if ( ! empty( $full_blob_url ) ) {
Expand All @@ -213,15 +215,16 @@ private function replace_media_with( $source_attachment_id, $media_to_replace_id
);
}
} catch ( Exception $e ) {
// translators: %s would be an error message
// translators: %s would be an error message.
printf( esc_html__( 'Error in uploading file. Error: %s', 'windows-azure-storage' ), esc_html( $e->getMessage() ) );
}

$replacement = array();


$replacement['success'] = true;
$replacement['is_image'] = $this->is_image( $source_filetype );
$replacement['file_name'] = basename( $replace_file );

$replacement = array_merge( $replacement, $this->media_meta_replacement_prepare( $source_attachment_id, $media_to_replace_id ) );

return $replacement;
Expand All @@ -230,18 +233,28 @@ private function replace_media_with( $source_attachment_id, $media_to_replace_id
/**
* If Attachment is an image
*
* @param string $filetype mime type
* @param array $filetype mime type.
* @return boolean
*/
private function is_image( $filetype ) {
return ( strpos( $filetype['type'], 'image' ) !== false );
}

/**
* If Attachment is a PDF
*
* @param string $filetype mime type.
* @return boolean
*/
private function is_pdf( $filetype ) {
return ( strpos( $filetype, 'pdf' ) !== false );
}

/**
* Media meta replacement and copy
*
* @param int $source_attachment_id Source attachment ID
* @param int $media_to_replace_id Replacement file ID
* @param int $source_attachment_id Source attachment ID.
* @param int $media_to_replace_id Replacement file ID.
* @return array
*/
private function media_meta_replacement_prepare( $source_attachment_id, $media_to_replace_id ) {
Expand Down Expand Up @@ -295,14 +308,15 @@ private function media_meta_replacement_prepare( $source_attachment_id, $media_t
/**
* Process media and replace
*
* @param array $source_data source data
* @param array $replace_data replacement file data
* @param array $source_data source data.
* @param array $replace_data replacement file data.
* @return array
*/
public function process_media_thumbnails( $source_data, $replace_data ) {

$sizes = $this->find_nearest_size( $source_data, $replace_data );


$sizes = $this->find_nearest_size( $source_data, $replace_data );
$mime_type = ( $this->is_pdf( $replace_data['mime_type'] ) ) ? 'image/jpg' : $replace_data['mime_type'];

if ( ! empty( $sizes ) ) {
foreach ( $sizes as $size_key => $size_data ) {
$source_data['meta_data']['sizes'][ $size_key ] = $size_data['source_data'];
Expand All @@ -313,40 +327,40 @@ public function process_media_thumbnails( $source_data, $replace_data ) {

if ( ! empty( $replace_data['meta_data']['sizes'] ) ) {

// Let's replace the file remotely
// Let's replace the file remotely.
foreach ( $sizes as $source_size => $sizes_source_data ) {
try {
\Windows_Azure_Helper::copy_media_to_blob_storage(
$this->container_name,
$sizes_source_data['replace_file'],
$sizes_source_data['source_file'],
$replace_data['mime_type'],
$mime_type,
'',
'',
30,
);
} catch ( Exception $e ) {
// translators: %s would be an error message
// translators: %s would be an error message.
printf( esc_html__( 'Error in uploading file. Error: %s', 'windows-azure-storage' ), esc_html( $e->getMessage() ) );
}
}
}

wp_delete_attachment( $replace_data['id'], true );

return $source_data;
}

/**
* Delete blobs from source
*
* @param array $data source or replacement data
* @param array $data source or replacement data.
* @return void
*/
public function delete_previous_thumbnails( $data ) {
$default_azure_storage_account_container_name = \Windows_Azure_Helper::get_default_container();

// delete remaining blobs from source
// delete remaining blobs from source.
if ( ! empty( $data['meta_azure']['thumbnails'] ) ) {
foreach ( $data['meta_azure']['thumbnails'] as $blob_location ) {
try {
Expand All @@ -358,7 +372,7 @@ public function delete_previous_thumbnails( $data ) {
);
}
} catch ( Exception $e ) {
// translators: %s would be an error message
// translators: %s would be an error message.
printf( esc_html__( 'Blob could not be removed. Error: %s', 'windows-azure-storage' ), esc_html( $e->getMessage() ) );
}
}
Expand All @@ -368,18 +382,18 @@ public function delete_previous_thumbnails( $data ) {
/**
* Get the nearest size from the replacement image
*
* @param array $source_sizes Source image data
* @param array $target_sizes Replacement image data
* @param array $source_sizes Source image data.
* @param array $target_sizes Replacement image data.
* @return array
*/
private function find_nearest_size( $source_sizes, $target_sizes ) {
// Bail early if no attachment meta field
// Bail early if no attachment meta field.
if ( empty( $source_sizes['meta_data'] ) || empty( $target_sizes['meta_data'] ) ) {
return;
return array();
}

if ( empty( $source_sizes['meta_data']['file'] ) || empty( $target_sizes['meta_data']['file'] ) ) {
return;
return array();
}

$convert_sizes = array();
Expand All @@ -390,7 +404,7 @@ private function find_nearest_size( $source_sizes, $target_sizes ) {
$target_file_path = dirname( $target_filename );

if ( empty( $source_sizes['meta_data']['sizes'] ) || empty( $target_sizes['meta_data']['sizes'] ) ) {
return;
return array();
}

foreach ( $source_sizes['meta_data']['sizes'] as $size => $size_data ) {
Expand Down
28 changes: 28 additions & 0 deletions js/src/windows-azure-storage-media-replace.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ function generateCacheVar(length) {
return result;
}

var alertMessage = function(message,status,fadeOutSeconds) {
var alert = '<div class="notice notice-' + status + ' is-dismissible"><p>' + message + '</p></div>';
var $alert = jQuery(alert).insertBefore('.attachment-info .settings-save-status');

// Fade out after 'fadeOutSeconds' seconds
setTimeout(function() {
$alert.fadeOut(function() {
$alert.remove(); // Remove the element from the DOM after fading out
});
}, fadeOutSeconds * 1000);
}

var replaceMedia = function(attachmentID) {
var mediaUploader;

Expand Down Expand Up @@ -42,6 +54,13 @@ var replaceMedia = function(attachmentID) {
jQuery('.edit-media-header').find('.media-modal-close').first().prop('disabled', true);
},
success: function(result) {
if ( ( 'success' in result ) && ( ! result.success ) ) {
jQuery('.settings-save-status').find('.spinner').removeClass('is-active');
jQuery('.edit-media-header').find('.media-modal-close').first().prop('disabled', false);
alertMessage(result.data, 'error', 5);
return;
}

jQuery('.settings-save-status').find('.spinner').removeClass('is-active');
jQuery('.edit-media-header').find('.media-modal-close').first().prop('disabled', false);

Expand All @@ -60,6 +79,15 @@ var replaceMedia = function(attachmentID) {
jQuery('.attachments-wrapper').find('li[data-id="'+ result.id +'"]').find('img').first().attr('src', medium_img + '?v=' + cacheVar );

jQuery('.attachments-wrapper').find('li[data-id="'+ result.old_ID +'"]').remove();
},
error: function(xhr, status, error) {
jQuery('.settings-save-status').find('.spinner').removeClass('is-active');
jQuery('.edit-media-header').find('.media-modal-close').first().prop('disabled', false);

var alertMessage = "Error: " + error + "\nStatus: " + status;
alertMessage(alertMessage, 'error', 5);

console.error("AJAX request failed: ", status, error);
}
});

Expand Down
28 changes: 28 additions & 0 deletions js/windows-azure-storage-media-replace.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ function generateCacheVar(length) {
return result;
}

var alertMessage = function(message,status,fadeOutSeconds) {
var alert = '<div class="notice notice-' + status + ' is-dismissible"><p>' + message + '</p></div>';
var $alert = jQuery(alert).insertBefore('.attachment-info .settings-save-status');

// Fade out after 'fadeOutSeconds' seconds
setTimeout(function() {
$alert.fadeOut(function() {
$alert.remove(); // Remove the element from the DOM after fading out
});
}, fadeOutSeconds * 1000);
}

var replaceMedia = function(attachmentID) {
var mediaUploader;

Expand Down Expand Up @@ -45,6 +57,13 @@ var replaceMedia = function(attachmentID) {
jQuery('.edit-media-header').find('.media-modal-close').first().prop('disabled', true);
},
success: function(result) {
if ( ( 'success' in result ) && ( ! result.success ) ) {
jQuery('.settings-save-status').find('.spinner').removeClass('is-active');
jQuery('.edit-media-header').find('.media-modal-close').first().prop('disabled', false);
alertMessage(result.data, 'error', 5);
return;
}

jQuery('.settings-save-status').find('.spinner').removeClass('is-active');
jQuery('.edit-media-header').find('.media-modal-close').first().prop('disabled', false);

Expand All @@ -63,6 +82,15 @@ var replaceMedia = function(attachmentID) {
jQuery('.attachments-wrapper').find('li[data-id="'+ result.id +'"]').find('img').first().attr('src', medium_img + '?v=' + cacheVar );

jQuery('.attachments-wrapper').find('li[data-id="'+ result.old_ID +'"]').remove();
},
error: function(xhr, status, error) {
jQuery('.settings-save-status').find('.spinner').removeClass('is-active');
jQuery('.edit-media-header').find('.media-modal-close').first().prop('disabled', false);

var alertMessage = "Error: " + error + "\nStatus: " + status;
alertMessage(alertMessage, 'error', 5);

console.error("AJAX request failed: ", status, error);
}
});

Expand Down
2 changes: 1 addition & 1 deletion js/windows-azure-storage-media-replace.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit a443bff

Please sign in to comment.