WordPress.org

Make WordPress Core

Opened 6 years ago

Closed 6 years ago

Last modified 6 years ago

#30209 closed defect (bug) (duplicate)

Media upload in multisite while switched to blog sets wrong url to uploaded media.

Reported by: yo-l1982 Owned by:
Milestone: Priority: normal
Severity: normal Version: 4.0
Component: Media Keywords:
Focuses: multisite Cc:

Description

To reproduce.
Setup a WP multisite network and run this pseudo code from a blog that is NOT blog_id = 1.

$post_id = 1234; //A post id to an existing post in blog 1
$image_url = 'http://example.com/image.jpg'; // Existing image.
switch_to_blog(1);
$url = media_sideload_image($image_url, $post_id);
restore_current_blog();
var_dump($url);

The url will now point at the correct filepath but wrong domain, the domain in blog 2 is used.

My current workaround:

function fix_url_bug($upload_info) {
        global $blog_id;
        $correctDomain = parse_url(get_site_url($blog_id));
        $faultyUrl = parse_url($upload_info['url']);

        $scheme   = isset($faultyUrl['scheme']) ? $faultyUrl['scheme'] . '://' : '';
        $host     = isset($correctDomain['host']) ? $correctDomain['host'] : '';
        $port     = isset($faultyUrl['port']) ? ':' . $faultyUrl['port'] : '';
        $path     = isset($faultyUrl['path']) ? $faultyUrl['path'] : '';
        $query    = isset($faultyUrl['query']) ? '?' . $faultyUrl['query'] : '';
        $fragment = isset($faultyUrl['fragment']) ? '#' . $faultyUrl['fragment'] : '';

        $upload_info['url'] = "$scheme$host$port$path$query$fragment";
        return $upload_info;
}


$post_id = 1234; //A post id to an existing post in blog 1
$image_url = 'http://example.com/image.jpg'; // Existing image.
switch_to_blog(1);
add_filter('wp_handle_upload', 'fix_url_bug');
$url = media_sideload_image($image_url, $post_id);
remove_filter('wp_handle_upload', 'fix_url_bug');
restore_current_blog();

var_dump($url);

If needed:
Watch out for the "reject_unsafe_urls" setting when uploading file from locally when reproducing.
Workaround for that:

add_filter('http_request_args', 'allow_unsafe_url');
funtion allow_unsafe_url($args)
{
      $args['reject_unsafe_urls'] = false;
      return $args;
}

Bye bye.

Change History (3)

#2 @yo-l1982
6 years ago

  • Resolution set to duplicate
  • Status changed from new to closed

Duplicate of #25650.

Yeah it is related.
wp_upload_dir() is used to fetch the url in media_sideload_image().
That ticket is closer to the actual bug in this ticket.

#3 @SergeyBiryukov
6 years ago

  • Milestone Awaiting Review deleted
Note: See TracTickets for help on using tickets.