Make WordPress Core

Opened 4 months ago

Closed 3 months ago

Last modified 3 months ago

#65686 closed defect (bug) (fixed)

Normalize non-integer filesize attachment metadata in the admin

Reported by: mukesh27 Owned by: westonruter
Priority: normal Milestone: 7.1
Component: Media Version: 7.0
Severity: normal Keywords: has-patch
Cc: Focuses:

Description

Follow-up to [62815] / #65670, which normalized the stored filesize attachment metadata in WP_REST_Attachments_Controller::get_attachment_filesize(). The same unguarded read still exists in two admin-facing places:

  • wp_prepare_attachment_for_js() in wp-includes/media.php
  • attachment_submitbox_metadata() in wp-admin/includes/media.php

Both do:

if ( isset( $meta['filesize'] ) ) {
        $bytes = $meta['filesize'];
} elseif ( file_exists( $attached_file ) ) {
        $bytes = wp_filesize( $attached_file );
}

Attachment metadata is untyped, and since [52837] the filesize key is commonly written by third-party code — offloading plugins (S3, GCS, CDNs) populate it from a remote storage API response, where it typically arrives as a string, and can be absent, empty, or non-numeric when the remote lookup fails.

Consequences today:

  • A numeric string ('123456') is passed through verbatim, so filesizeInBytes is a string in the JSON handed to the media modal, while the wp_filesize() branch of the very same conditional yields an int. After [62815] the REST response for the same attachment is now an int, so the two representations of one value disagree.
  • A non-numeric string ('unknown') is truthy, so the file_exists() fallback is skipped even when the real file is present and readable. size_format() then returns false, and filesizeHumanReadable is false / "File size:" renders empty — instead of the correct size that was one wp_filesize() call away.
  • Negative or zero-ish values (-1, '0', '') likewise suppress the fallback or produce a nonsensical size.

Proposed fix, mirroring [62815] exactly:

if ( isset( $meta['filesize'] ) && is_numeric( $meta['filesize'] ) && $meta['filesize'] > 0 ) {
        $bytes = (int) $meta['filesize'];
} elseif ( file_exists( $attached_file ) ) {
        $bytes = wp_filesize( $attached_file );
}

Numeric values are trusted and cast; anything else falls through to the real file size. This keeps filesizeInBytes a non-negative-int, consistent with wp_filesize() (see [62813]) and with the REST filesize field.

No back-compat break is expected: the only behavior change for existing valid metadata is '123456' becoming 123456, which is what every consumer already assumes.

Change History (10)

#1 @mukesh27
4 months ago

  • Owner set to mukesh27
  • Status new → assigned

This ticket was mentioned in ​PR #12632 on ​WordPress/wordpress-develop by ​@mukesh27.


4 months ago
#2

  • Keywords has-patch added; needs-patch removed

Trac ticket: https://core.trac.wordpress.org/ticket/65686

## Use of AI Tools

AI assistance: Yes
Tool(s): Claude
Model(s): GPT-5.1
Used for: For drafting PR details only.

This ticket was mentioned in ​Slack in #core-test by noruzzaman. ​View the logs.


3 months ago

​@wildworks commented on ​PR #12632:


3 months ago
#4

@mukeshpanchal27, Is this PR ready for review?

​@mukesh27 commented on ​PR #12632:


3 months ago
#5

Is this PR ready for review?

Yes @t-hamano

#6 @westonruter
3 months ago

  • Owner changed from mukesh27 to westonruter
  • Status assigned → reviewing

​@westonruter commented on ​PR #12632:


3 months ago
#7

I tried using a plugin to filter the attachment metadata to use 'unknown' as the filesize:

<details><summary>Details</summary>

<?php
/**
 * Plugin Name: Unknown Filesize Metadata
 * Plugin URI: https://core.trac.wordpress.org/ticket/65686
 * Description: Filters attachment metadata to supply the non-numeric string 'unknown' as the filesize, simulating an offloading plugin whose remote storage lookup failed. See Trac #65686.
 * Version: 0.1.0
 * Requires at least: 7.0
 * Requires PHP: 7.2
 * Author: Weston Ruter
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 *
 * @package UnknownFilesizeMetadata
 */

namespace UnknownFilesizeMetadata;

/**
 * Supplies a non-numeric filesize in attachment metadata.
 *
 * @param mixed $data Attachment metadata. Normally an array, but other plugins may return anything.
 * @return mixed Filtered attachment metadata.
 */
function filter_wp_get_attachment_metadata( $data ) {
        if ( is_array( $data ) ) {
                $data['filesize'] = 'unknown';
        }
        return $data;
}
add_filter( 'wp_get_attachment_metadata', __NAMESPACE__ . '\filter_wp_get_attachment_metadata' );

</details>

In the media modal, the file size correctly goes from false to the expected value as read from disk:

Before ❌ | After ✅

--

https://github.com/user-attachments/assets/0b8aeddc-c584-4801-9e84-261c862f75e2 | https://github.com/user-attachments/assets/653be628-fda7-46ea-8d1b-8cf376ef5752

​@westonruter commented on ​PR #12632:


3 months ago
#8

Same goes on the attachment detail page:

Before ❌ | After ✅

--

https://github.com/user-attachments/assets/e889c213-a7d5-4723-a473-96f856155791 | https://github.com/user-attachments/assets/c1c1bdde-4839-4311-906b-1771fad80696

#9 @westonruter
3 months ago

  • Resolution → fixed
  • Status reviewing → closed

In 62978:

Media: Normalize non-numeric attachment filesize metadata.

The stored filesize attachment metadata was read without validation in wp_prepare_attachment_for_js() and attachment_submitbox_metadata(). Attachment metadata is untyped, and the filesize key is commonly written by offloading plugins from a remote storage API response, so it can arrive as a numeric string, or be empty, non-numeric, or negative when the remote lookup fails. A numeric string was passed through verbatim, making filesizeInBytes a string in the media modal while the wp_filesize() branch of the very same conditional yielded an int; a non-numeric value such as 'unknown' was truthy and suppressed the fallback entirely, so size_format() returned false and the file size rendered empty even when the real file was readable.

Both call sites now only trust the stored value when it is numeric and casts to an integer greater than zero, and otherwise recompute the size with wp_filesize(). The fallback condition also replaces file_exists() with is_readable() guarded on a non-empty string, since get_attached_file() can be filtered to return a non-string. PHPUnit coverage is added for both functions.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/12632.
Follow-up to r34258, r52837, r62813, r62815.

Props mukesh27, westonruter.
See #65670.
Fixes #65686.

#10 @westonruter
3 months ago

In 63002:

Media: Normalize unusable sizes attachment metadata.

Attachment metadata is untyped, and the sizes key is not guaranteed to be present or to hold an array. Sub-size generation can leave it out entirely, and a plugin filtering wp_get_attachment_metadata can replace it with anything. wp_save_image() validated only that the metadata itself was an array before passing $meta['sizes'] to array_merge(), so an absent or scalar value raised a TypeError and the image editor returned an HTTP 500 mid-save. wp_restore_image() had the same gap at $meta['sizes'][ $default_size ] = $data, where a string raises "Cannot use a scalar value as an array" and false is deprecated as of PHP 8.1 and an error as of PHP 9.

wp_get_attachment_metadata() now returns false whenever the metadata is not an array, on the $unfiltered path as well as after the filter, matching the documented array|false return. A sizes key holding a non-array is replaced with an empty array, so every caller can rely on the key being an array whenever it is present. The key is not invented when it is absent: audio, video and document attachments legitimately store metadata without it, and callers such as wp-admin/post.php read the metadata unfiltered in order to modify it and write it back, so normalizing there would persist into the database.

The image editor entry points fill in the missing key themselves, and wp_prepare_attachment_for_js() now checks the dimensions of the full entry alongside its filename before reading them, removing the "Undefined array key" warnings raised for a sizes array that carries no usable full size. PHPUnit coverage is added for all three functions.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/12744.
Follow-up to r11965, r23873, r38949, r49084, r62978.

Props josephscott, westonruter, mukesh27, irozum, ugyensupport, nazmulasif.
See #65686, #64898.
Fixes #65748.

Note: See TracTickets for help on using tickets.