Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/wp-admin/includes/media.php
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,8 @@ function media_handle_sideload( $file_array, $post_id = 0, $desc = null, $post_d
if ( isset( $post_data['post_date'] ) && substr( $post_data['post_date'], 0, 4 ) > 0 ) {
$time = $post_data['post_date'];
} else {
$post = get_post( $post_id );
// Avoid get_post() falling back to the global post when no post ID is passed.
$post = $post_id ? get_post( $post_id ) : null;
if ( $post && substr( $post->post_date, 0, 4 ) > 0 ) {
$time = $post->post_date;
} else {
Expand Down
82 changes: 82 additions & 0 deletions tests/phpunit/tests/media/mediaHandleSideload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

/**
* Tests for the `media_handle_sideload()` function.
*
* @group media
* @covers ::media_handle_sideload
*/
class Tests_Media_mediaHandleSideload extends WP_UnitTestCase {

public static function set_up_before_class() {
parent::set_up_before_class();

require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
}

public function tear_down() {
$this->remove_added_uploads();

parent::tear_down();
}

/**
* Sideloads a copy of a test image.
*
* @param int $post_id The post ID passed to `media_handle_sideload()`.
* @return string The path of the sideloaded file.
*/
private function sideload( $post_id ) {
$tmp_name = wp_tempnam( 'canola.jpg' );
copy( DIR_TESTDATA . '/images/canola.jpg', $tmp_name );

$attachment_id = media_handle_sideload(
array(
'name' => 'canola.jpg',
'tmp_name' => $tmp_name,
),
$post_id
);

$this->assertIsInt( $attachment_id );

return get_attached_file( $attachment_id );
}

/**
* @ticket 43119
*
* @dataProvider data_empty_post_id
*
* @param mixed $post_id An empty post ID.
*/
public function test_empty_post_id_ignores_global_post( $post_id ) {
$GLOBALS['post'] = self::factory()->post->create_and_get( array( 'post_date' => '2018-01-01 00:00:00' ) );

$this->assertStringContainsString( current_time( '/Y/m/' ), $this->sideload( $post_id ) );
}

/**
* Data provider for test_empty_post_id_ignores_global_post().
*
* @return array[]
*/
public function data_empty_post_id() {
return array(
'zero' => array( 0 ),
'null' => array( null ),
'false' => array( false ),
);
}

/**
* @ticket 43119
*/
public function test_post_id_uses_post_date() {
$post_id = self::factory()->post->create( array( 'post_date' => '2018-01-01 00:00:00' ) );

$this->assertStringContainsString( '/2018/01/', $this->sideload( $post_id ) );
}
}
Loading