From cd784fd2c51f72a18cc81e53e8b72a79d6debe8d Mon Sep 17 00:00:00 2001 From: goldenapples Date: Fri, 26 Apr 2013 14:39:04 -0700 Subject: [PATCH] For local media imports, copy to tempfile before importing Apparently `wp_handle_sideload` performs a`rename()` operation on the file it's sideloading. In this case thats an unexpected side effect - you don't want the original image to go away when importing it to WordPress. --- php/commands/media.php | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/php/commands/media.php b/php/commands/media.php index 1e946f40..6fdf2b06 100644 --- a/php/commands/media.php +++ b/php/commands/media.php @@ -76,18 +76,30 @@ class Media_Command extends WP_CLI_Command { $is_file_remote = parse_url( $file, PHP_URL_SCHEME ); $orig_filename = $file; - if ( !empty( $is_file_remote ) ) { - $extension = pathinfo( $file, PATHINFO_EXTENSION ); + if ( empty( $is_file_remote ) ) { + // File appears to be a local file; make a copy first to work with + + $tempfile = wp_tempnam( $file ); + if ( ! $tempfile ) + WP_CLI::error( 'Could not create temporary file.' ); + + copy( $file, $tempfile ); + + } else { + // File appear to be a remote file; download as temp file + $tempfile = download_url( $file ); - // Necessary because temp filename will probably have an extension like - // .tmp, which is not in the list of permitted upload extensions - // and won't be recognized with the correct mime type - $tempfile_extension = pathinfo( $tempfile, PATHINFO_EXTENSION ); - $file = preg_replace( "/$tempfile_extension$/", $extension, $tempfile ); - rename( $tempfile, $file ); } + // Necessary because temp filename will probably have an extension like + // .tmp, which is not in the list of permitted upload extensions + // and won't be recognized with the correct mime type + $extension = pathinfo( $file, PATHINFO_EXTENSION ); + $tempfile_extension = pathinfo( $tempfile, PATHINFO_EXTENSION ); + $file = preg_replace( "/$tempfile_extension$/", $extension, $tempfile ); + rename( $tempfile, $file ); + $file_array = array( 'tmp_name' => $file, 'name' => basename( $file ) -- 2.11.0