Skip to content

Commit

Permalink
Fix some path renaming issues
Browse files Browse the repository at this point in the history
- Fixes wrong paths saved
- Also handles paths correctly now when using a WebP extension
  • Loading branch information
fabianfabian committed Oct 26, 2023
1 parent 54a2c7b commit b5dd47c
Showing 1 changed file with 63 additions and 61 deletions.
124 changes: 63 additions & 61 deletions nostr-media.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ function msp_disable_default_image_sizes($sizes) {
}

function handle_image_upload() {
$base_directory = WP_CONTENT_DIR . '/uploads';
$base_url = content_url('/uploads');

$isValid = validate_authorization_header();

if($isValid["valid"]) {
Expand All @@ -142,12 +145,13 @@ function handle_image_upload() {


// WP saves an image and then creates scaled version of it with suffix.
// We need <scaled hash>.jpg to return to nostr client.
// But WP generates <whatever>-scaled.jpg or <whatever>-150x150.jpg etc.
// So we need to save the original as <original hash>.jpg, then WP can
// generate <original hash>-scaled.jpg etc, then we can rename <original hash>-scaled.jpg to <scaled hash>.jpg
// This way the nostr client gets the scaled version as <scaled hash>.jpg and WP media backend
// will list: <scaled hash>.jpg and in the detail it have a link to <original hash>.jpg
// We need <scaled hash>.ext to return to nostr client.
// But WP generates <whatever>-scaled.ext or <whatever>-150x150.ext etc.
// Or with a WebP plug-in it generates <whatever>-jpg.webp
// So we need to save the original as <original hash>.ext, then WP can
// generate <original hash>-scaled.ext etc, then we can rename <original hash>-scaled.ext to <scaled hash>.ext
// This way the nostr client gets the scaled version as <scaled hash>.ext and WP media backend
// will list: <scaled hash>.ext and in the detail it have a link to <original hash>.ext

if ($movefile && !isset($movefile['error'])) {
add_filter('intermediate_image_sizes_advanced', 'msp_disable_default_image_sizes');
Expand All @@ -156,7 +160,7 @@ function handle_image_upload() {
require_once(ABSPATH . 'wp-admin/includes/image.php');

$filetype = wp_check_filetype(basename($movefile['file']), null);

// Save uploaded file to <hash>.ext
$pathinfo = pathinfo($movefile['file']);
$new_original_path = $pathinfo['dirname'] . '/' . $original_hash . '.' . $pathinfo['extension'];
Expand All @@ -172,71 +176,68 @@ function handle_image_upload() {

$attach_id = wp_insert_attachment($attachment, $new_original_path);
$attach_data = wp_generate_attachment_metadata($attach_id, $new_original_path);
wp_update_attachment_metadata($attach_id, $attach_data);

// Get the path of the automatically scaled image generated by WP
$scaled_image_path = str_replace('.', '-scaled.', $new_original_path);
$new_scaled_image_path = $scaled_image_path; // We'll rename this later, else it falls back to this default path

if (!file_exists($scaled_image_path)) {
// If there is no scaled image, use the original
$scaled_image_path = $new_original_path;
$scaled_image_hash = $original_hash;
$attach_data['scaled_file_hash'] = $original_hash;
$new_scaled_image_path = $new_original_path;
}
else {
// take hash from scaled image
$scaled_image_hash = hash_file('sha256', $scaled_image_path);

unset($attach_data["image_meta"]);

// If there is no scaled version, the scaled path and hash will default back to the original path and hash:
$scaled_image_path = $new_original_path;
$scaled_image_hash = hash_file('sha256', $base_directory . '/' . $attach_data["file"]);
$isScaled = $scaled_image_hash !== $original_hash;

$scaled_image_filepath = $base_directory . '/' . $attach_data["file"];

if ($isScaled) {
// Move file to new path nostr/s/c/<scaled hash>.ext
$extension = pathinfo($attach_data["file"], PATHINFO_EXTENSION);
$scaled_path_prefix = substr($scaled_image_hash, 0, 1) . '/' . substr($scaled_image_hash, 1, 1);
$new_path = 'nostr/' . $scaled_path_prefix . '/' . $scaled_image_hash . '.' .$extension;

// Rename <hash>-scaled.ext to <scaled hash>.ext
$new_scaled_image_path = str_replace($original_hash, $scaled_image_hash, $scaled_image_path);
$new_scaled_image_path = str_replace("-scaled.", ".", $new_scaled_image_path);
// Save the scaled hash to the attachment metadata
$attach_data['scaled_file_hash'] = $scaled_image_hash;

// replace path prefix of original hash with path prefix of scaled hash
$original_path_prefix = '/' . substr($original_hash, 0, 1) . '/' . substr($original_hash, 1, 1);
$scaled_path_prefix = '/' . substr($scaled_image_hash, 0, 1) . '/' . substr($scaled_image_hash, 1, 1);
// New path for the scaled image
// From: d/0/d0c0db5b65104add337d851725c451ccd8b618bdfc017946b78cca82599a3be6-jpg.webp (original hash)
// To: 5/6/56ef04e3a9d61edbc8bfe0314d945bb3dc7a054d53d46b09cd7bbe188809cd36.webp (scaled hash and -scaled or other suffixes removed)

$new_scaled_image_path = str_replace($original_path_prefix, $scaled_path_prefix, $new_scaled_image_path);
$new_scaled_image_filepath = $base_directory . '/' . $new_path;

if (!file_exists($new_scaled_image_path)) {
$new_scaled_image_dir = dirname($new_scaled_image_path);
// If the file doesn't exist check, check if directory exists, and if not, create it
if (!file_exists($new_scaled_image_filepath)) {
$new_scaled_image_dir = dirname($new_scaled_image_filepath);
if (!file_exists($new_scaled_image_dir)) { // create prefix paths if they don't exist
wp_mkdir_p($new_scaled_image_dir);
}
// Rename /a/b/<hash>-scaled.ext to /c/d/<scaled hash>.ext
rename($scaled_image_path, $new_scaled_image_path);

// Save the scaled hash to the attachment metadata
$attach_data['scaled_file_hash'] = $scaled_image_hash;
}
else {
// already exists
$scaled_image_hash = hash_file('sha256', $new_scaled_image_path);
$attach_data['scaled_file_hash'] = $scaled_image_hash;
}

// Make sure WP backend links to the new scaled image path /c/d/<scaled hash>.ext instread of <hash>-scaled.ext
update_attached_file( $attach_id, $new_scaled_image_path);
// Rename the file on the disk
if (rename($scaled_image_filepath, $new_scaled_image_filepath)) {
// Update the 'file' key in the $attach_data array
$attach_data['file'] = $new_path;

// Update the 'sources' key for all types
if (isset($attach_data['sources'])) {
foreach ($attach_data['sources'] as $type => $source) {
$attach_data['sources'][$type]['file'] = $attach_data['file'];
}
}
$scaled_image_path = $new_path;
$scaled_image_filepath = $base_directory . '/' . $attach_data['file'];
// Update the '_wp_attached_file' meta key
update_post_meta($attach_id, '_wp_attached_file', $scaled_image_path);
}
}

// Save the original to the attachment metadata
$attach_data['original_file_hash'] = $original_hash;

// Save size and dimensions of the scaled image to the attachment metadata
$attach_data['dim'] = getimagesize($new_scaled_image_path);
$attach_data['size'] = filesize($new_scaled_image_path);
$attach_data['dim'] = getimagesize($scaled_image_filepath);
$attach_data['size'] = filesize($scaled_image_filepath);

wp_update_attachment_metadata($attach_id, $attach_data);

// Get the URL of the newly named scaled image (https://your-domain.com/wp-content/uploads/nostr/a/b/<scaled hash>.ext)
$scaled_image_url = wp_upload_dir()['url'] . '/' . $scaled_image_hash . '.' . $pathinfo['extension'];

// $scaled_image_url prefix is still from the original upload hash, so need to replace that with the scaled hash prefix
$wrong_prefix_and_scaled_hash = '/' . substr($original_hash, 0, 1) . '/' . substr($original_hash, 1, 1) . '/' .$scaled_image_hash;
$correct_prefix_and_scaled_hash = '/' . substr($scaled_image_hash, 0, 1) . '/' . substr($scaled_image_hash, 1, 1) . '/' .$scaled_image_hash;

$scaled_image_url = str_replace($wrong_prefix_and_scaled_hash, $correct_prefix_and_scaled_hash, $scaled_image_url);
// Get the URL of the newly named scaled image (https://your-domain.com/wp-content/uploads/nostr/s/c/<scaled hash>.ext)
$scaled_image_url = $base_url . '/' . $attach_data['file'];

$response = array(
"status" => "success",
Expand All @@ -252,7 +253,7 @@ function handle_image_upload() {
array("url", $scaled_image_url),
array("m", $movefile['type']),
array("ox", $original_hash),
array("x", $attach_data['scaled_file_hash']),
array("x", $scaled_image_hash),
array("size", "" . $attach_data['size']), // Added file size of the scaled image
array("dim", $attach_data['dim'][0] . 'x' . $attach_data['dim'][1]) // Added dimensions of the scaled image
)
Expand All @@ -272,7 +273,8 @@ function handle_image_upload() {

// show file hashes (ox and x) in the Media tab
function msp_add_file_hash_to_media_library($form_fields, $post) {
$original_file_hash = get_post_meta($post->ID, '_wp_attachment_metadata', true)['original_file_hash'];
$meta = get_post_meta($post->ID, '_wp_attachment_metadata', true);
$original_file_hash = $meta['original_file_hash'];

if ($original_file_hash) {
$form_fields['original_file_hash'] = array(
Expand All @@ -284,7 +286,7 @@ function msp_add_file_hash_to_media_library($form_fields, $post) {
);
}

$scaled_image_hash = get_post_meta($post->ID, '_wp_attachment_metadata', true)['scaled_file_hash'];
$scaled_image_hash = isset($meta['scaled_file_hash']) ? $meta['scaled_file_hash'] : null;

if ($scaled_image_hash) {
$form_fields['scaled_image_hash'] = array(
Expand Down Expand Up @@ -401,11 +403,11 @@ function custom_upload_dir($uploads) {
// Assuming $original_hash is accessible here (otherwise, you'll need to calculate it again)
global $original_hash; // We'll set this in the file handling code later

$base_directory = WP_CONTENT_DIR . '/uploads/nostr';
$base_url = content_url('/uploads/nostr');
$base_directory = WP_CONTENT_DIR . '/uploads';
$base_url = content_url('/uploads');

$custom_directory = '/' . substr($original_hash, 0, 1) . '/' . substr($original_hash, 1, 1);
$custom_url = '/' . substr($original_hash, 0, 1) . '/' . substr($original_hash, 1, 1);
$custom_directory = '/nostr/' . substr($original_hash, 0, 1) . '/' . substr($original_hash, 1, 1);
$custom_url = '/nostr/' . substr($original_hash, 0, 1) . '/' . substr($original_hash, 1, 1);

$uploads['path'] = $base_directory . $custom_directory;
if (!file_exists($uploads['path'])) {
Expand Down

0 comments on commit b5dd47c

Please sign in to comment.