Index: wp-admin/includes/media.php
===================================================================
--- wp-admin/includes/media.php	(revision 25143)
+++ wp-admin/includes/media.php	(working copy)
@@ -312,13 +312,28 @@
  *
  * @since 2.6.0
  *
- * @param array $file_array Array similar to a {@link $_FILES} upload array
+ * @param string|array $file A URL as a string, or an array similar to a {@link $_FILES} upload array
  * @param int $post_id The post ID the media is associated with
  * @param string $desc Description of the sideloaded file
  * @param array $post_data allows you to overwrite some of the attachment
  * @return int|object The ID of the attachment or a WP_Error on failure
  */
-function media_handle_sideload($file_array, $post_id, $desc = null, $post_data = array()) {
+function media_handle_sideload( $file, $post_id, $desc = null, $post_data = array()) {
+	$downloading_url = is_string( $file );
+
+	if ( $downloading_url ) {
+		// Download file to temp location
+		$tmp = download_url( $file );
+
+		if ( is_wp_error( $tmp ) )
+			return $tmp;
+
+		$file_array = array(
+			'name' => preg_replace( '/\?.*/', '', $file ), // Strip query string (might need to be better)
+			'tmp_name' => $tmp,
+		);
+	}
+
 	$overrides = array('test_form'=>false);
 
 	$time = current_time( 'mysql' );
@@ -328,8 +343,11 @@
 	}
 
 	$file = wp_handle_sideload( $file_array, $overrides, $time );
-	if ( isset($file['error']) )
+	if ( isset( $file['error'] ) ) {
+		if ( $downloading_url )
+			@unlink( $tmp );
 		return new WP_Error( 'upload_error', $file['error'] );
+	}
 
 	$url = $file['url'];
 	$type = $file['type'];
@@ -660,35 +678,11 @@
  * @return string|WP_Error Populated HTML img tag on success
  */
 function media_sideload_image($file, $post_id, $desc = null) {
-	if ( ! empty($file) ) {
-		// Download file to temp location
-		$tmp = download_url( $file );
+	if ( ! $file )
+		return;
+	$id = media_handle_sideload( $file, $post_id, $desc );
 
-		// Set variables for storage
-		// fix file filename for query strings
-		preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
-		$file_array['name'] = basename($matches[0]);
-		$file_array['tmp_name'] = $tmp;
-
-		// If error storing temporarily, unlink
-		if ( is_wp_error( $tmp ) ) {
-			@unlink($file_array['tmp_name']);
-			$file_array['tmp_name'] = '';
-		}
-
-		// do the validation and storage stuff
-		$id = media_handle_sideload( $file_array, $post_id, $desc );
-		// If error storing permanently, unlink
-		if ( is_wp_error($id) ) {
-			@unlink($file_array['tmp_name']);
-			return $id;
-		}
-
-		$src = wp_get_attachment_url( $id );
-	}
-
-	// Finally check to make sure the file has been saved, then return the html
-	if ( ! empty($src) ) {
+	if ( $src = wp_get_attachment_url( $id ) ) {
 		$alt = isset($desc) ? esc_attr($desc) : '';
 		$html = "<img src='$src' alt='$alt' />";
 		return $html;
