Skip to content
Merged
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
10 changes: 7 additions & 3 deletions inc/media_offload.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* @author Optimole <friends@optimole.com>
*/

use OptimoleWP\Media\UploadsPath;
use OptimoleWP\Offload\Loader;
use Optimole\Sdk\Exception\InvalidArgumentException;
use Optimole\Sdk\Exception\InvalidUploadApiResponseException;
Expand Down Expand Up @@ -1463,7 +1464,8 @@ public function generate_image_meta( $meta, $attachment_id ) {
do_action( 'optml_log', 'file after replace' );
do_action( 'optml_log', $local_file );
}
if ( ! file_exists( $local_file ) ) {
// The path comes from attachment metadata, so a file outside the uploads directory is treated as missing.
if ( ! file_exists( $local_file ) || ! UploadsPath::contains( $local_file ) ) {
update_post_meta( $attachment_id, self::META_KEYS['offload_error'], 'true' );
do_action( 'optml_log', 'missing file' );
do_action( 'optml_log', $local_file );
Expand Down Expand Up @@ -1616,7 +1618,8 @@ public function generate_image_meta( $meta, $attachment_id ) {
if ( isset( $meta['sizes'] ) ) {
foreach ( $meta['sizes'] as $key => $value ) {
$generated_image_size_path = str_replace( $original_name, $meta['sizes'][ $key ]['file'], $local_file );
file_exists( $generated_image_size_path ) && unlink( $generated_image_size_path );
// Size files come from attachment metadata too, so only those inside the uploads directory are deleted.
file_exists( $generated_image_size_path ) && UploadsPath::contains( $generated_image_size_path ) && unlink( $generated_image_size_path );
$meta['sizes'][ $key ]['file'] = $file_name;
}
}
Expand All @@ -1626,7 +1629,8 @@ public function generate_image_meta( $meta, $attachment_id ) {
if ( isset( $meta['original_image'] ) ) {
$ext = $this->get_ext( $local_file );
$scaled_path = str_replace( '.' . $ext, '-scaled.' . $ext, $local_file );
file_exists( $scaled_path ) && unlink( $scaled_path );
// The extension is replaced in the whole path, so folder names change too.
file_exists( $scaled_path ) && UploadsPath::contains( $scaled_path ) && unlink( $scaled_path );
}

$duplicated_images = apply_filters( 'optml_offload_duplicated_images', [], $attachment_id );
Expand Down
19 changes: 18 additions & 1 deletion inc/media_rename/attachment_db_renamer.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ class Optml_Attachment_Db_Renamer {
*/
private $skip_columns = [ 'user_pass' ];

/**
* Size suffixes, such as `150x150`, whose URLs are renamed, as keys; null renames every size
*
* @var array<string, int>|null
*/
private $renamed_size_suffixes = null;

/**
* Handle image size variations
*
Expand All @@ -35,9 +42,13 @@ class Optml_Attachment_Db_Renamer {

/**
* Constructor
*
* @param bool $skip_sizes Whether size and scaled variations are left unchanged.
* @param string[]|null $renamed_size_suffixes Size suffixes, such as `150x150`, whose URLs are renamed; null renames every size.
*/
public function __construct( $skip_sizes = false ) {
public function __construct( $skip_sizes = false, ?array $renamed_size_suffixes = null ) {
$this->handle_image_sizes = ! $skip_sizes;
$this->renamed_size_suffixes = null === $renamed_size_suffixes ? null : array_flip( $renamed_size_suffixes );
}

/**
Expand Down Expand Up @@ -479,6 +490,9 @@ private function replace_image_urls( $content, $old_url, $new_url ) {
function ( $matches ) use ( $old_base, $new_base, $old_domain, $new_domain, $old_dir, $new_dir, $old_ext, $new_ext ) {
// Extract the size part (e.g., -300x200)
$size_part = substr( $matches[0], strlen( $old_domain . $old_dir . '/' . $old_base ), -strlen( '.' . $old_ext ) );
if ( null !== $this->renamed_size_suffixes && ! isset( $this->renamed_size_suffixes[ ltrim( $size_part, '-' ) ] ) ) {
return $matches[0];
}

// Build the new URL with the same size
return $new_domain . $new_dir . '/' . $new_base . $size_part . '.' . $new_ext;
Expand All @@ -505,6 +519,9 @@ function ( $matches ) use ( $new_base, $new_domain, $new_dir, $new_ext ) {
function ( $matches ) use ( $old_base, $new_base, $old_domain, $new_domain, $old_dir, $new_dir, $old_ext, $new_ext ) {
// Extract the size part (e.g., -300x200)
$size_part = substr( $matches[0], strlen( str_replace( '/', '\/', $old_domain . $old_dir . '/' . $old_base ) ), -strlen( '.' . $old_ext ) );
if ( null !== $this->renamed_size_suffixes && ! isset( $this->renamed_size_suffixes[ ltrim( $size_part, '-' ) ] ) ) {
return $matches[0];
}

// Build the new URL with the same size
return str_replace( '/', '\/', $new_domain . $new_dir . '/' . $new_base . $size_part . '.' . $new_ext );
Expand Down
28 changes: 26 additions & 2 deletions inc/media_rename/attachment_rename.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

use OptimoleWP\Media\UploadsPath;

/**
* Attachment rename class.
*/
Expand All @@ -25,6 +27,13 @@ class Optml_Attachment_Rename {
*/
private $attachment;

/**
* Size suffixes, such as `150x150`, of the size files moved to the new name.
*
* @var list<string>
*/
private $moved_size_suffixes = [];

/**
* Constructor.
*
Expand Down Expand Up @@ -65,6 +74,11 @@ public function rename() {

global $wp_filesystem;

// Paths come from attachment metadata, so only files inside the uploads directory are moved.
if ( ! UploadsPath::contains( $file_path ) || ! UploadsPath::contains( $new_file_path ) ) {
return new WP_Error( 'optml_attachment_path_outside_uploads', __( 'Error renaming file.', 'optimole-wp' ) );
}

// Bail if original file doesn't exist.
if ( ! $wp_filesystem->exists( $file_path ) ) {
return new WP_Error( 'optml_attachment_file_not_found', __( 'Error renaming file.', 'optimole-wp' ) );
Expand All @@ -87,7 +101,9 @@ public function rename() {

$new_scaled_file_path = $base_dir . $scaled_new_file_with_ext;
// Move the scaled image. We also override any leftover scaled files.
$wp_filesystem->move( $scaled_old_file_path, $new_scaled_file_path, true );
if ( UploadsPath::contains( $scaled_old_file_path ) && UploadsPath::contains( $new_scaled_file_path ) ) {
$wp_filesystem->move( $scaled_old_file_path, $new_scaled_file_path, true );
}
}

// Update attachment metadata
Expand All @@ -100,7 +116,7 @@ public function rename() {
try {
$skip_sizes = ! $this->attachment->is_image();

$replacer = new Optml_Attachment_Db_Renamer( $skip_sizes );
$replacer = new Optml_Attachment_Db_Renamer( $skip_sizes, $this->moved_size_suffixes );
$old_url = $this->attachment->get_main_url();
$new_url = $this->get_new_url( $new_unique_filename );

Expand Down Expand Up @@ -186,6 +202,9 @@ private function update_attachment_metadata( $new_path ) {

$old_size_file_path = sprintf( '%s/%s', $this->attachment->get_dir_path(), $size_data['file'] );
$new_size_file_path = sprintf( '%s/%s', $this->attachment->get_dir_path(), $new_size_file );
if ( ! UploadsPath::contains( $old_size_file_path ) || ! UploadsPath::contains( $new_size_file_path ) ) {
continue;
}
Comment thread
pirate-bot marked this conversation as resolved.
Resolved

$move = $wp_filesystem->move( $old_size_file_path, $new_size_file_path );

Expand All @@ -194,6 +213,11 @@ private function update_attachment_metadata( $new_path ) {
$metadata['sizes'][ $size ]['file'] = $new_size_file;
$already_moved_paths = array_unique( $already_moved_paths );
}
// Links are renamed only for size files this rename created, so other links keep working. A path
// moved for an earlier size creates no file with this suffix.
if ( $move ) {
$this->moved_size_suffixes[] = $size_suffix;
}
}
}

Expand Down
12 changes: 10 additions & 2 deletions inc/media_rename/attachment_replace.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

use OptimoleWP\Media\UploadsPath;

/**
* Optml_Attachment_Replace
*
Expand Down Expand Up @@ -70,6 +72,11 @@ public function replace() {
return new WP_Error( 'file_error', __( 'Original file does not exist.', 'optimole-wp' ) );
}

// The path comes from attachment metadata, so only a file inside the uploads directory is overwritten.
if ( ! UploadsPath::contains( $original_file ) ) {
return new WP_Error( 'optml_attachment_path_outside_uploads', __( 'Error uploading file.', 'optimole-wp' ) );
}

$original_filetype = wp_check_filetype( $original_file );
$uploaded_filetype = wp_check_filetype( $this->file['name'] );

Expand Down Expand Up @@ -186,7 +193,8 @@ private function remove_all_image_sizes() {
global $wp_filesystem;

foreach ( $all_image_sizes_paths as $path ) {
if ( file_exists( $path ) ) {
// Paths come from attachment metadata, so only files inside the uploads directory are deleted.
if ( file_exists( $path ) && UploadsPath::contains( $path ) ) {
$wp_filesystem->delete( $path );
}
}
Expand Down Expand Up @@ -223,7 +231,7 @@ private function handle_scaled_images() {

// replace the old year/month/item-scaled.ext with the new year/month/item.ext
$scaled_path = str_replace( $unscaled_file, $old_scaled_file, $this->attachment->get_source_file_path() );
if ( file_exists( $scaled_path ) ) {
if ( file_exists( $scaled_path ) && UploadsPath::contains( $scaled_path ) ) {
Comment thread
pirate-bot marked this conversation as resolved.
Resolved
$wp_filesystem->delete( $scaled_path );
}

Expand Down
43 changes: 43 additions & 0 deletions inc/v2/Media/UploadsPath.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace OptimoleWP\Media;

/**
* Checks that attachment file paths stay inside the uploads directory.
*
* Paths built from attachment metadata are moved and deleted, so a `../` in that metadata
* must not reach files elsewhere on the server.
*
* @package OptimoleWP\Media
*/
class UploadsPath {
/**
* Check whether a file path, existing or not, is inside the uploads directory.
*
* The folder holding the file must exist; `..` and symlinks in that folder are resolved before the check.
* A symlink at the file itself is not followed: creating one needs write access to the server files.
*
* @param string $path Absolute file path.
*
* @return bool True when the file is inside the uploads directory.
*/
public static function contains( string $path ): bool {
$name = basename( $path );
if ( '' === $name || '.' === $name || '..' === $name ) {
return false;
}
Comment thread
pirate-bot marked this conversation as resolved.
Resolved

$uploads = realpath( wp_get_upload_dir()['basedir'] );
$dir = realpath( dirname( $path ) );
if ( false === $uploads || false === $dir ) {
return false;
}

// realpath() returns backslashes on Windows. Elsewhere a backslash is a filename character, so only the
// separator of this system is normalized.
$dir = str_replace( DIRECTORY_SEPARATOR, '/', $dir );
$uploads = str_replace( DIRECTORY_SEPARATOR, '/', $uploads );

return 0 === strpos( trailingslashit( $dir ), trailingslashit( $uploads ) );
}
}
6 changes: 0 additions & 6 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -2400,12 +2400,6 @@ parameters:
count: 2
path: inc/media_offload.php

-
message: '#^Method Optml_Attachment_Db_Renamer\:\:__construct\(\) has parameter \$skip_sizes with no type specified\.$#'
identifier: missingType.parameter
count: 1
path: inc/media_rename/attachment_db_renamer.php

-
message: '#^Method Optml_Attachment_Db_Renamer\:\:get_columns\(\) return type has no value type specified in iterable type array\.$#'
identifier: missingType.iterableValue
Expand Down
Loading
Loading