From 3eb2bd9f5b7b049af9f09aebcf0b896e062f41a0 Mon Sep 17 00:00:00 2001 From: Sergey Biryukov Date: Tue, 7 Jul 2020 10:18:25 +0000 Subject: [PATCH] Upload: Introduce `pre_wp_unique_filename_file_list` filter to allow for short-circuiting the `scandir()` call in `wp_unique_filename()`. This allows plugins to override the file fetching behavior to provide performance improvements for large directories. Props joehoyle. Fixes #50587. git-svn-id: https://develop.svn.wordpress.org/trunk@48369 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/functions.php | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index ec2229be50..225ad31f21 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -2533,8 +2533,25 @@ function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) // The (resized) image files would have name and extension, and will be in the uploads dir. if ( $name && $ext && @is_dir( $dir ) && false !== strpos( $dir, $upload_dir['basedir'] ) ) { - // List of all files and directories contained in $dir. - $files = @scandir( $dir ); + /** + * Filters the file list used for calculating a unique filename for a newly added file. + * + * Returning an array from the filter will effectively short-circuit retrieval + * from the filesystem and return the passed value instead. + * + * @since 5.5.0 + * + * @param array|null $files The list of files to use for filename comparisons. + * Default null (to retrieve the list from the filesystem). + * @param string $dir The directory for the new file. + * @param string $filename The proposed filename for the new file. + */ + $files = apply_filters( 'pre_wp_unique_filename_file_list', null, $dir, $filename ); + + if ( null === $files ) { + // List of all files and directories contained in $dir. + $files = @scandir( $dir ); + } if ( ! empty( $files ) ) { // Remove "dot" dirs.