WP_REST_Attachments_Controller::get_sideloaded_file_names( int $attachment_id, bool $include_provenance = true ): string[]

Returns the file names which a finalize request may store for an attachment.

Description

The set is the file names the sideload endpoint recorded as it produced them (ref. WP_REST_Attachments_Controller::META_KEY_SIDELOAD_FILE_NAME), plus the attachment’s own attached file – accepted in both its uploads-relative and basename form so a scaled main-file pointer validates regardless of which the client echoes – plus the names already stored in the attachment’s own metadata.

Parameters

$attachment_idintrequired
The attachment being finalized.
$include_provenancebooloptional
Whether to include the sideload provenance rows.
Pass false to get only the names recoverable from the attached file and stored metadata, e.g. to decide whether a provenance row is still needed.

Default:true

Return

string[] File names that may appear in the finalize submission.

Source

protected function get_sideloaded_file_names( int $attachment_id, bool $include_provenance = true ): array {
	$allowed = array();

	if ( $include_provenance ) {
		foreach ( (array) get_post_meta( $attachment_id, self::META_KEY_SIDELOAD_FILE_NAME ) as $name ) {
			if ( is_string( $name ) && '' !== $name ) {
				$allowed[] = $name;
			}
		}
	}

	$attached_file = get_post_meta( $attachment_id, '_wp_attached_file', true );
	if ( is_string( $attached_file ) && strlen( $attached_file ) > 0 ) {
		$allowed[] = $attached_file;
		$allowed[] = wp_basename( $attached_file );
	}

	/*
	 * Names already stored in this attachment's metadata passed this same
	 * check when they were written, so accepting them again introduces
	 * nothing new.
	 */
	$metadata = wp_get_attachment_metadata( $attachment_id, true );
	if ( is_array( $metadata ) ) {
		$stored = array(
			$metadata['file'] ?? null,
			$metadata['original_image'] ?? null,
			$metadata[ self::META_KEY_SOURCE_IMAGE ] ?? null,
			$metadata['animated_video'] ?? null,
			$metadata['animated_video_poster'] ?? null,
		);

		if ( ! empty( $metadata['sizes'] ) && is_array( $metadata['sizes'] ) ) {
			foreach ( $metadata['sizes'] as $size ) {
				$stored[] = is_array( $size ) ? ( $size['file'] ?? null ) : null;
			}
		}

		foreach ( $stored as $name ) {
			if ( is_string( $name ) && '' !== $name ) {
				$allowed[] = $name;
				$allowed[] = wp_basename( $name );
			}
		}
	}

	return array_values( array_unique( $allowed ) );
}

Changelog

VersionDescription
7.1.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.