Move into nested docroot
This commit is contained in:
parent
83a0d3a149
commit
c8b70abde9
13405 changed files with 0 additions and 0 deletions
172
web/core/modules/file/src/Tests/DownloadTest.php
Normal file
172
web/core/modules/file/src/Tests/DownloadTest.php
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
/**
|
||||
* Tests for download/file transfer functions.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class DownloadTest extends FileManagedTestBase {
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
// Clear out any hook calls.
|
||||
file_test_reset();
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the public file transfer system.
|
||||
*/
|
||||
function testPublicFileTransfer() {
|
||||
// Test generating a URL to a created file.
|
||||
$file = $this->createFile();
|
||||
$url = file_create_url($file->getFileUri());
|
||||
// URLs can't contain characters outside the ASCII set so $filename has to be
|
||||
// encoded.
|
||||
$filename = $GLOBALS['base_url'] . '/' . \Drupal::service('stream_wrapper_manager')->getViaScheme('public')->getDirectoryPath() . '/' . rawurlencode($file->getFilename());
|
||||
$this->assertEqual($filename, $url, 'Correctly generated a URL for a created file.');
|
||||
$this->drupalHead($url);
|
||||
$this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the created file.');
|
||||
|
||||
// Test generating a URL to a shipped file (i.e. a file that is part of
|
||||
// Drupal core, a module or a theme, for example a JavaScript file).
|
||||
$filepath = 'core/assets/vendor/jquery/jquery.min.js';
|
||||
$url = file_create_url($filepath);
|
||||
$this->assertEqual($GLOBALS['base_url'] . '/' . $filepath, $url, 'Correctly generated a URL for a shipped file.');
|
||||
$this->drupalHead($url);
|
||||
$this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the private file transfer system.
|
||||
*/
|
||||
public function testPrivateFileTransferWithoutPageCache() {
|
||||
$this->doPrivateFileTransferTest();
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the private file transfer system.
|
||||
*/
|
||||
protected function doPrivateFileTransferTest() {
|
||||
// Set file downloads to private so handler functions get called.
|
||||
|
||||
// Create a file.
|
||||
$contents = $this->randomMachineName(8);
|
||||
$file = $this->createFile(NULL, $contents, 'private');
|
||||
// Created private files without usage are by default not accessible
|
||||
// for a user different from the owner, but createFile always uses uid 1
|
||||
// as the owner of the files. Therefore make it permanent to allow access
|
||||
// if a module allows it.
|
||||
$file->setPermanent();
|
||||
$file->save();
|
||||
|
||||
$url = file_create_url($file->getFileUri());
|
||||
|
||||
// Set file_test access header to allow the download.
|
||||
file_test_set_return('download', array('x-foo' => 'Bar'));
|
||||
$this->drupalGet($url);
|
||||
$this->assertEqual($this->drupalGetHeader('x-foo'), 'Bar', 'Found header set by file_test module on private download.');
|
||||
$this->assertFalse($this->drupalGetHeader('x-drupal-cache'), 'Page cache is disabled on private file download.');
|
||||
$this->assertResponse(200, 'Correctly allowed access to a file when file_test provides headers.');
|
||||
|
||||
// Test that the file transferred correctly.
|
||||
$this->assertEqual($contents, $this->content, 'Contents of the file are correct.');
|
||||
|
||||
// Deny access to all downloads via a -1 header.
|
||||
file_test_set_return('download', -1);
|
||||
$this->drupalHead($url);
|
||||
$this->assertResponse(403, 'Correctly denied access to a file when file_test sets the header to -1.');
|
||||
|
||||
// Try non-existent file.
|
||||
$url = file_create_url('private://' . $this->randomMachineName());
|
||||
$this->drupalHead($url);
|
||||
$this->assertResponse(404, 'Correctly returned 404 response for a non-existent file.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test file_create_url().
|
||||
*/
|
||||
function testFileCreateUrl() {
|
||||
|
||||
// Tilde (~) is excluded from this test because it is encoded by
|
||||
// rawurlencode() in PHP 5.2 but not in PHP 5.3, as per RFC 3986.
|
||||
// @see http://php.net/manual/function.rawurlencode.php#86506
|
||||
$basename = " -._!$'\"()*@[]?&+%#,;=:\n\x00" . // "Special" ASCII characters.
|
||||
"%23%25%26%2B%2F%3F" . // Characters that look like a percent-escaped string.
|
||||
"éøïвβ中國書۞"; // Characters from various non-ASCII alphabets.
|
||||
$basename_encoded = '%20-._%21%24%27%22%28%29%2A%40%5B%5D%3F%26%2B%25%23%2C%3B%3D%3A__' .
|
||||
'%2523%2525%2526%252B%252F%253F' .
|
||||
'%C3%A9%C3%B8%C3%AF%D0%B2%CE%B2%E4%B8%AD%E5%9C%8B%E6%9B%B8%DB%9E';
|
||||
|
||||
// Public files should not be served by Drupal, so their URLs should not be
|
||||
// routed through Drupal, whereas private files should be served by Drupal,
|
||||
// so they need to be. The difference is most apparent when $script_path
|
||||
// is not empty (i.e., when not using clean URLs).
|
||||
$clean_url_settings = array(
|
||||
'clean' => '',
|
||||
'unclean' => 'index.php/',
|
||||
);
|
||||
$public_directory_path = \Drupal::service('stream_wrapper_manager')->getViaScheme('public')->getDirectoryPath();
|
||||
foreach ($clean_url_settings as $clean_url_setting => $script_path) {
|
||||
$clean_urls = $clean_url_setting == 'clean';
|
||||
$request = $this->prepareRequestForGenerator($clean_urls);
|
||||
$base_path = $request->getSchemeAndHttpHost() . $request->getBasePath();
|
||||
$this->checkUrl('public', '', $basename, $base_path . '/' . $public_directory_path . '/' . $basename_encoded);
|
||||
$this->checkUrl('private', '', $basename, $base_path . '/' . $script_path . 'system/files/' . $basename_encoded);
|
||||
}
|
||||
$this->assertEqual(file_create_url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='), 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', t('Generated URL matches expected URL.'));
|
||||
// Test public files with a different host name from settings.
|
||||
$test_base_url = 'http://www.example.com/cdn';
|
||||
$this->settingsSet('file_public_base_url', $test_base_url);
|
||||
$filepath = file_create_filename('test.txt', '');
|
||||
$directory_uri = 'public://' . dirname($filepath);
|
||||
file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY);
|
||||
$file = $this->createFile($filepath, NULL, 'public');
|
||||
$url = file_create_url($file->getFileUri());
|
||||
$expected_url = $test_base_url . '/' . basename($filepath);
|
||||
$this->assertEqual($url, $expected_url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a file from the URL generated by file_create_url().
|
||||
*
|
||||
* Create a file with the specified scheme, directory and filename; check that
|
||||
* the URL generated by file_create_url() for the specified file equals the
|
||||
* specified URL; fetch the URL and then compare the contents to the file.
|
||||
*
|
||||
* @param string $scheme
|
||||
* A scheme, e.g. "public".
|
||||
* @param string $directory
|
||||
* A directory, possibly "".
|
||||
* @param string $filename
|
||||
* A filename.
|
||||
* @param string $expected_url
|
||||
* The expected URL.
|
||||
*/
|
||||
private function checkUrl($scheme, $directory, $filename, $expected_url) {
|
||||
// Convert $filename to a valid filename, i.e. strip characters not
|
||||
// supported by the filesystem, and create the file in the specified
|
||||
// directory.
|
||||
$filepath = file_create_filename($filename, $directory);
|
||||
$directory_uri = $scheme . '://' . dirname($filepath);
|
||||
file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY);
|
||||
$file = $this->createFile($filepath, NULL, $scheme);
|
||||
|
||||
$url = file_create_url($file->getFileUri());
|
||||
$this->assertEqual($url, $expected_url);
|
||||
|
||||
if ($scheme == 'private') {
|
||||
// Tell the implementation of hook_file_download() in file_test.module
|
||||
// that this file may be downloaded.
|
||||
file_test_set_return('download', array('x-foo' => 'Bar'));
|
||||
}
|
||||
|
||||
$this->drupalGet($url);
|
||||
if ($this->assertResponse(200) == 'pass') {
|
||||
$this->assertRaw(file_get_contents($file->getFileUri()), 'Contents of the file are correct.');
|
||||
}
|
||||
|
||||
$file->delete();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,169 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\node\Entity\Node;
|
||||
use Drupal\user\RoleInterface;
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Confirm that file field submissions work correctly for anonymous visitors.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FileFieldAnonymousSubmissionTest extends FileFieldTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
// Set up permissions for anonymous attacker user.
|
||||
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array(
|
||||
'create article content' => TRUE,
|
||||
'access content' => TRUE,
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the basic node submission for an anonymous visitor.
|
||||
*/
|
||||
public function testAnonymousNode() {
|
||||
$bundle_label = 'Article';
|
||||
$node_title = 'test page';
|
||||
|
||||
// Load the node form.
|
||||
$this->drupalLogout();
|
||||
$this->drupalGet('node/add/article');
|
||||
$this->assertResponse(200, 'Loaded the article node form.');
|
||||
$this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));
|
||||
|
||||
$edit = array(
|
||||
'title[0][value]' => $node_title,
|
||||
'body[0][value]' => 'Test article',
|
||||
);
|
||||
$this->drupalPostForm(NULL, $edit, 'Save');
|
||||
$this->assertResponse(200);
|
||||
$t_args = array('@type' => $bundle_label, '%title' => $node_title);
|
||||
$this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
|
||||
$matches = array();
|
||||
if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) {
|
||||
$nid = end($matches);
|
||||
$this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.');
|
||||
$node = Node::load($nid);
|
||||
$this->assertNotEqual($node, NULL, 'The node was loaded successfully.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests file submission for an anonymous visitor.
|
||||
*/
|
||||
public function testAnonymousNodeWithFile() {
|
||||
$bundle_label = 'Article';
|
||||
$node_title = 'Test page';
|
||||
$this->createFileField('field_image', 'node', 'article', array(), array('file_extensions' => 'txt png'));
|
||||
|
||||
// Load the node form.
|
||||
$this->drupalLogout();
|
||||
$this->drupalGet('node/add/article');
|
||||
$this->assertResponse(200, 'Loaded the article node form.');
|
||||
$this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));
|
||||
|
||||
// Generate an image file.
|
||||
$image = $this->getTestFile('image');
|
||||
|
||||
// Submit the form.
|
||||
$edit = array(
|
||||
'title[0][value]' => $node_title,
|
||||
'body[0][value]' => 'Test article',
|
||||
'files[field_image_0]' => $this->container->get('file_system')->realpath($image->getFileUri()),
|
||||
);
|
||||
$this->drupalPostForm(NULL, $edit, 'Save');
|
||||
$this->assertResponse(200);
|
||||
$t_args = array('@type' => $bundle_label, '%title' => $node_title);
|
||||
$this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
|
||||
$matches = array();
|
||||
if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) {
|
||||
$nid = end($matches);
|
||||
$this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.');
|
||||
$node = Node::load($nid);
|
||||
$this->assertNotEqual($node, NULL, 'The node was loaded successfully.');
|
||||
$this->assertFileExists(File::load($node->field_image->target_id), 'The image was uploaded successfully.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests file submission for an anonymous visitor with a missing node title.
|
||||
*/
|
||||
public function testAnonymousNodeWithFileWithoutTitle() {
|
||||
$this->drupalLogout();
|
||||
$this->doTestNodeWithFileWithoutTitle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests file submission for an authenticated user with a missing node title.
|
||||
*/
|
||||
public function testAuthenticatedNodeWithFileWithoutTitle() {
|
||||
$admin_user = $this->drupalCreateUser(array(
|
||||
'bypass node access',
|
||||
'access content overview',
|
||||
'administer nodes',
|
||||
));
|
||||
$this->drupalLogin($admin_user);
|
||||
$this->doTestNodeWithFileWithoutTitle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to test file submissions with missing node titles.
|
||||
*/
|
||||
protected function doTestNodeWithFileWithoutTitle() {
|
||||
$bundle_label = 'Article';
|
||||
$node_title = 'Test page';
|
||||
$this->createFileField('field_image', 'node', 'article', array(), array('file_extensions' => 'txt png'));
|
||||
|
||||
// Load the node form.
|
||||
$this->drupalGet('node/add/article');
|
||||
$this->assertResponse(200, 'Loaded the article node form.');
|
||||
$this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));
|
||||
|
||||
// Generate an image file.
|
||||
$image = $this->getTestFile('image');
|
||||
|
||||
// Submit the form but exclude the title field.
|
||||
$edit = array(
|
||||
'body[0][value]' => 'Test article',
|
||||
'files[field_image_0]' => $this->container->get('file_system')->realpath($image->getFileUri()),
|
||||
);
|
||||
if (!$this->loggedInUser) {
|
||||
$label = 'Save';
|
||||
}
|
||||
else {
|
||||
$label = 'Save and publish';
|
||||
}
|
||||
$this->drupalPostForm(NULL, $edit, $label);
|
||||
$this->assertResponse(200);
|
||||
$t_args = array('@type' => $bundle_label, '%title' => $node_title);
|
||||
$this->assertNoText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
|
||||
$this->assertText('Title field is required.');
|
||||
|
||||
// Submit the form again but this time with the missing title field. This
|
||||
// should still work.
|
||||
$edit = array(
|
||||
'title[0][value]' => $node_title,
|
||||
);
|
||||
$this->drupalPostForm(NULL, $edit, $label);
|
||||
|
||||
// Confirm the final submission actually worked.
|
||||
$t_args = array('@type' => $bundle_label, '%title' => $node_title);
|
||||
$this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
|
||||
$matches = array();
|
||||
if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) {
|
||||
$nid = end($matches);
|
||||
$this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.');
|
||||
$node = Node::load($nid);
|
||||
$this->assertNotEqual($node, NULL, 'The node was loaded successfully.');
|
||||
$this->assertFileExists(File::load($node->field_image->target_id), 'The image was uploaded successfully.');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
168
web/core/modules/file/src/Tests/FileFieldDisplayTest.php
Normal file
168
web/core/modules/file/src/Tests/FileFieldDisplayTest.php
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\Core\Field\FieldStorageDefinitionInterface;
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests the display of file fields in node and views.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FileFieldDisplayTest extends FileFieldTestBase {
|
||||
|
||||
/**
|
||||
* Tests normal formatter display on node display.
|
||||
*/
|
||||
function testNodeDisplay() {
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$type_name = 'article';
|
||||
$field_storage_settings = array(
|
||||
'display_field' => '1',
|
||||
'display_default' => '1',
|
||||
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
|
||||
);
|
||||
$field_settings = array(
|
||||
'description_field' => '1',
|
||||
);
|
||||
$widget_settings = array();
|
||||
$this->createFileField($field_name, 'node', $type_name, $field_storage_settings, $field_settings, $widget_settings);
|
||||
|
||||
// Create a new node *without* the file field set, and check that the field
|
||||
// is not shown for each node display.
|
||||
$node = $this->drupalCreateNode(array('type' => $type_name));
|
||||
// Check file_default last as the assertions below assume that this is the
|
||||
// case.
|
||||
$file_formatters = array('file_table', 'file_url_plain', 'hidden', 'file_default');
|
||||
foreach ($file_formatters as $formatter) {
|
||||
$edit = array(
|
||||
"fields[$field_name][type]" => $formatter,
|
||||
);
|
||||
$this->drupalPostForm("admin/structure/types/manage/$type_name/display", $edit, t('Save'));
|
||||
$this->drupalGet('node/' . $node->id());
|
||||
$this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter)));
|
||||
}
|
||||
|
||||
$test_file = $this->getTestFile('text');
|
||||
simpletest_generate_file('escaped-&-text', 64, 10, 'text');
|
||||
$test_file = File::create([
|
||||
'uri' => 'public://escaped-&-text.txt',
|
||||
'name' => 'escaped-&-text',
|
||||
'filesize' => filesize('public://escaped-&-text.txt'),
|
||||
]);
|
||||
|
||||
// Create a new node with the uploaded file.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
|
||||
// Check that the default formatter is displaying with the file name.
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
$file_link = array(
|
||||
'#theme' => 'file_link',
|
||||
'#file' => $node_file,
|
||||
);
|
||||
$default_output = \Drupal::service('renderer')->renderRoot($file_link);
|
||||
$this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
|
||||
|
||||
// Turn the "display" option off and check that the file is no longer displayed.
|
||||
$edit = array($field_name . '[0][display]' => FALSE);
|
||||
$this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published'));
|
||||
|
||||
$this->assertNoRaw($default_output, 'Field is hidden when "display" option is unchecked.');
|
||||
|
||||
// Add a description and make sure that it is displayed.
|
||||
$description = $this->randomMachineName();
|
||||
$edit = array(
|
||||
$field_name . '[0][description]' => $description,
|
||||
$field_name . '[0][display]' => TRUE,
|
||||
);
|
||||
$this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published'));
|
||||
$this->assertText($description);
|
||||
|
||||
// Ensure the filename in the link's title attribute is escaped.
|
||||
$this->assertRaw('title="escaped-&-text.txt"');
|
||||
|
||||
// Test that fields appear as expected after during the preview.
|
||||
// Add a second file.
|
||||
$name = 'files[' . $field_name . '_1][]';
|
||||
$edit[$name] = drupal_realpath($test_file->getFileUri());
|
||||
|
||||
// Uncheck the display checkboxes and go to the preview.
|
||||
$edit[$field_name . '[0][display]'] = FALSE;
|
||||
$edit[$field_name . '[1][display]'] = FALSE;
|
||||
$this->drupalPostForm("node/$nid/edit", $edit, t('Preview'));
|
||||
$this->clickLink(t('Back to content editing'));
|
||||
$this->assertRaw($field_name . '[0][display]', 'First file appears as expected.');
|
||||
$this->assertRaw($field_name . '[1][display]', 'Second file appears as expected.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests default display of File Field.
|
||||
*/
|
||||
function testDefaultFileFieldDisplay() {
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$type_name = 'article';
|
||||
$field_storage_settings = array(
|
||||
'display_field' => '1',
|
||||
'display_default' => '0',
|
||||
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
|
||||
);
|
||||
$field_settings = array(
|
||||
'description_field' => '1',
|
||||
);
|
||||
$widget_settings = array();
|
||||
$this->createFileField($field_name, 'node', $type_name, $field_storage_settings, $field_settings, $widget_settings);
|
||||
|
||||
$test_file = $this->getTestFile('text');
|
||||
|
||||
// Create a new node with the uploaded file.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
|
||||
$this->drupalGet('node/' . $nid . '/edit');
|
||||
$this->assertFieldByXPath('//input[@type="checkbox" and @name="' . $field_name . '[0][display]"]', NULL, 'Default file display checkbox field exists.');
|
||||
$this->assertFieldByXPath('//input[@type="checkbox" and @name="' . $field_name . '[0][display]" and not(@checked)]', NULL, 'Default file display is off.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests description toggle for field instance configuration.
|
||||
*/
|
||||
function testDescToggle() {
|
||||
$type_name = 'test';
|
||||
$field_type = 'file';
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
// Use the UI to add a new content type that also contains a file field.
|
||||
$edit = array(
|
||||
'name' => $type_name,
|
||||
'type' => $type_name,
|
||||
);
|
||||
$this->drupalPostForm('admin/structure/types/add', $edit, t('Save and manage fields'));
|
||||
$edit = array(
|
||||
'new_storage_type' => $field_type,
|
||||
'field_name' => $field_name,
|
||||
'label' => $this->randomString(),
|
||||
);
|
||||
$this->drupalPostForm('/admin/structure/types/manage/' . $type_name . '/fields/add-field', $edit, t('Save and continue'));
|
||||
$this->drupalPostForm(NULL, array(), t('Save field settings'));
|
||||
// Ensure the description field is selected on the field instance settings
|
||||
// form. That's what this test is all about.
|
||||
$edit = array(
|
||||
'settings[description_field]' => TRUE,
|
||||
);
|
||||
$this->drupalPostForm(NULL, $edit, t('Save settings'));
|
||||
// Add a node of our new type and upload a file to it.
|
||||
$file = current($this->drupalGetTestFiles('text'));
|
||||
$title = $this->randomString();
|
||||
$edit = array(
|
||||
'title[0][value]' => $title,
|
||||
'files[field_' . $field_name . '_0]' => drupal_realpath($file->uri),
|
||||
);
|
||||
$this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish'));
|
||||
$node = $this->drupalGetNodeByTitle($title);
|
||||
$this->drupalGet('node/' . $node->id() . '/edit');
|
||||
$this->assertText(t('The description may be used as the label of the link to the file.'));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
|
||||
/**
|
||||
* Tests file formatter access.
|
||||
* @group file
|
||||
*/
|
||||
class FileFieldFormatterAccessTest extends FileFieldTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['node', 'file', 'field_ui', 'file_test'];
|
||||
|
||||
/**
|
||||
* Tests the custom access handler is invoked.
|
||||
*/
|
||||
public function testFileAccessHandler() {
|
||||
$type_name = 'article';
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$this->createFileField($field_name, 'node', $type_name);
|
||||
\Drupal::state()->set('file_test_alternate_access_handler', TRUE);
|
||||
\Drupal::entityManager()->clearCachedDefinitions();
|
||||
$test_file = $this->getTestFile('text');
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
$this->drupalGet('node/' . $nid);
|
||||
$this->assertTrue(\Drupal::state()->get('file_access_formatter_check', FALSE));
|
||||
}
|
||||
|
||||
}
|
||||
93
web/core/modules/file/src/Tests/FileFieldPathTest.php
Normal file
93
web/core/modules/file/src/Tests/FileFieldPathTest.php
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests that files are uploaded to proper locations.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FileFieldPathTest extends FileFieldTestBase {
|
||||
/**
|
||||
* Tests the normal formatter display on node display.
|
||||
*/
|
||||
function testUploadPath() {
|
||||
/** @var \Drupal\node\NodeStorageInterface $node_storage */
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$type_name = 'article';
|
||||
$this->createFileField($field_name, 'node', $type_name);
|
||||
/** @var \Drupal\file\FileInterface $test_file */
|
||||
$test_file = $this->getTestFile('text');
|
||||
|
||||
// Create a new node.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
|
||||
// Check that the file was uploaded to the correct location.
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
/** @var \Drupal\file\FileInterface $node_file */
|
||||
$node_file = $node->{$field_name}->entity;
|
||||
$date_formatter = $this->container->get('date.formatter');
|
||||
$expected_filename =
|
||||
'public://' .
|
||||
$date_formatter->format(REQUEST_TIME, 'custom', 'Y') . '-' .
|
||||
$date_formatter->format(REQUEST_TIME, 'custom', 'm') . '/' .
|
||||
$test_file->getFilename();
|
||||
$this->assertPathMatch($expected_filename, $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->getFileUri())));
|
||||
|
||||
// Change the path to contain multiple subdirectories.
|
||||
$this->updateFileField($field_name, $type_name, array('file_directory' => 'foo/bar/baz'));
|
||||
|
||||
// Upload a new file into the subdirectories.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
|
||||
// Check that the file was uploaded into the subdirectory.
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
$this->assertPathMatch('public://foo/bar/baz/' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->getFileUri())));
|
||||
|
||||
// Check the path when used with tokens.
|
||||
// Change the path to contain multiple token directories.
|
||||
$this->updateFileField($field_name, $type_name, array('file_directory' => '[current-user:uid]/[current-user:name]'));
|
||||
|
||||
// Upload a new file into the token subdirectories.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
|
||||
// Check that the file was uploaded into the subdirectory.
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
// Do token replacement using the same user which uploaded the file, not
|
||||
// the user running the test case.
|
||||
$data = array('user' => $this->adminUser);
|
||||
$subdirectory = \Drupal::token()->replace('[user:uid]/[user:name]', $data);
|
||||
$this->assertPathMatch('public://' . $subdirectory . '/' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path with token replacements.', array('%file' => $node_file->getFileUri())));
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that a file is uploaded to the right location.
|
||||
*
|
||||
* @param string $expected_path
|
||||
* The location where the file is expected to be uploaded. Duplicate file
|
||||
* names to not need to be taken into account.
|
||||
* @param string $actual_path
|
||||
* Where the file was actually uploaded.
|
||||
* @param string $message
|
||||
* The message to display with this assertion.
|
||||
*/
|
||||
function assertPathMatch($expected_path, $actual_path, $message) {
|
||||
// Strip off the extension of the expected path to allow for _0, _1, etc.
|
||||
// suffixes when the file hits a duplicate name.
|
||||
$pos = strrpos($expected_path, '.');
|
||||
$base_path = substr($expected_path, 0, $pos);
|
||||
$extension = substr($expected_path, $pos + 1);
|
||||
|
||||
$result = preg_match('/' . preg_quote($base_path, '/') . '(_[0-9]+)?\.' . preg_quote($extension, '/') . '/', $actual_path);
|
||||
$this->assertTrue($result, $message);
|
||||
}
|
||||
|
||||
}
|
||||
68
web/core/modules/file/src/Tests/FileFieldRSSContentTest.php
Normal file
68
web/core/modules/file/src/Tests/FileFieldRSSContentTest.php
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Ensure that files added to nodes appear correctly in RSS feeds.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FileFieldRSSContentTest extends FileFieldTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('node', 'views');
|
||||
|
||||
/**
|
||||
* Tests RSS enclosure formatter display for RSS feeds.
|
||||
*/
|
||||
function testFileFieldRSSContent() {
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$type_name = 'article';
|
||||
|
||||
$this->createFileField($field_name, 'node', $type_name);
|
||||
|
||||
// RSS display must be added manually.
|
||||
$this->drupalGet("admin/structure/types/manage/$type_name/display");
|
||||
$edit = array(
|
||||
"display_modes_custom[rss]" => '1',
|
||||
);
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
|
||||
// Change the format to 'RSS enclosure'.
|
||||
$this->drupalGet("admin/structure/types/manage/$type_name/display/rss");
|
||||
$edit = array("fields[$field_name][type]" => 'file_rss_enclosure');
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
|
||||
// Create a new node with a file field set. Promote to frontpage
|
||||
// needs to be set so this node will appear in the RSS feed.
|
||||
$node = $this->drupalCreateNode(array('type' => $type_name, 'promote' => 1));
|
||||
$test_file = $this->getTestFile('text');
|
||||
|
||||
// Create a new node with the uploaded file.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $node->id());
|
||||
|
||||
// Get the uploaded file from the node.
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
|
||||
// Check that the RSS enclosure appears in the RSS feed.
|
||||
$this->drupalGet('rss.xml');
|
||||
$uploaded_filename = str_replace('public://', '', $node_file->getFileUri());
|
||||
$selector = sprintf(
|
||||
'enclosure[url="%s"][length="%s"][type="%s"]',
|
||||
file_create_url("public://$uploaded_filename", array('absolute' => TRUE)),
|
||||
$node_file->getSize(),
|
||||
$node_file->getMimeType()
|
||||
);
|
||||
$this->assertTrue(!empty($this->cssSelect($selector)), 'File field RSS enclosure is displayed when viewing the RSS feed.');
|
||||
}
|
||||
|
||||
}
|
||||
142
web/core/modules/file/src/Tests/FileFieldRevisionTest.php
Normal file
142
web/core/modules/file/src/Tests/FileFieldRevisionTest.php
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests creating and deleting revisions with files attached.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FileFieldRevisionTest extends FileFieldTestBase {
|
||||
/**
|
||||
* Tests creating multiple revisions of a node and managing attached files.
|
||||
*
|
||||
* Expected behaviors:
|
||||
* - Adding a new revision will make another entry in the field table, but
|
||||
* the original file will not be duplicated.
|
||||
* - Deleting a revision should not delete the original file if the file
|
||||
* is in use by another revision.
|
||||
* - When the last revision that uses a file is deleted, the original file
|
||||
* should be deleted also.
|
||||
*/
|
||||
function testRevisions() {
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
$type_name = 'article';
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$this->createFileField($field_name, 'node', $type_name);
|
||||
// Create the same fields for users.
|
||||
$this->createFileField($field_name, 'user', 'user');
|
||||
|
||||
$test_file = $this->getTestFile('text');
|
||||
|
||||
// Create a new node with the uploaded file.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
|
||||
// Check that the file exists on disk and in the database.
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file_r1 = File::load($node->{$field_name}->target_id);
|
||||
$node_vid_r1 = $node->getRevisionId();
|
||||
$this->assertFileExists($node_file_r1, 'New file saved to disk on node creation.');
|
||||
$this->assertFileEntryExists($node_file_r1, 'File entry exists in database on node creation.');
|
||||
$this->assertFileIsPermanent($node_file_r1, 'File is permanent.');
|
||||
|
||||
// Upload another file to the same node in a new revision.
|
||||
$this->replaceNodeFile($test_file, $field_name, $nid);
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file_r2 = File::load($node->{$field_name}->target_id);
|
||||
$node_vid_r2 = $node->getRevisionId();
|
||||
$this->assertFileExists($node_file_r2, 'Replacement file exists on disk after creating new revision.');
|
||||
$this->assertFileEntryExists($node_file_r2, 'Replacement file entry exists in database after creating new revision.');
|
||||
$this->assertFileIsPermanent($node_file_r2, 'Replacement file is permanent.');
|
||||
|
||||
// Check that the original file is still in place on the first revision.
|
||||
$node = node_revision_load($node_vid_r1);
|
||||
$current_file = File::load($node->{$field_name}->target_id);
|
||||
$this->assertEqual($node_file_r1->id(), $current_file->id(), 'Original file still in place after replacing file in new revision.');
|
||||
$this->assertFileExists($node_file_r1, 'Original file still in place after replacing file in new revision.');
|
||||
$this->assertFileEntryExists($node_file_r1, 'Original file entry still in place after replacing file in new revision');
|
||||
$this->assertFileIsPermanent($node_file_r1, 'Original file is still permanent.');
|
||||
|
||||
// Save a new version of the node without any changes.
|
||||
// Check that the file is still the same as the previous revision.
|
||||
$this->drupalPostForm('node/' . $nid . '/edit', array('revision' => '1'), t('Save and keep published'));
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file_r3 = File::load($node->{$field_name}->target_id);
|
||||
$node_vid_r3 = $node->getRevisionId();
|
||||
$this->assertEqual($node_file_r2->id(), $node_file_r3->id(), 'Previous revision file still in place after creating a new revision without a new file.');
|
||||
$this->assertFileIsPermanent($node_file_r3, 'New revision file is permanent.');
|
||||
|
||||
// Revert to the first revision and check that the original file is active.
|
||||
$this->drupalPostForm('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert'));
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file_r4 = File::load($node->{$field_name}->target_id);
|
||||
$this->assertEqual($node_file_r1->id(), $node_file_r4->id(), 'Original revision file still in place after reverting to the original revision.');
|
||||
$this->assertFileIsPermanent($node_file_r4, 'Original revision file still permanent after reverting to the original revision.');
|
||||
|
||||
// Delete the second revision and check that the file is kept (since it is
|
||||
// still being used by the third revision).
|
||||
$this->drupalPostForm('node/' . $nid . '/revisions/' . $node_vid_r2 . '/delete', array(), t('Delete'));
|
||||
$this->assertFileExists($node_file_r3, 'Second file is still available after deleting second revision, since it is being used by the third revision.');
|
||||
$this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting second revision, since it is being used by the third revision.');
|
||||
$this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting second revision, since it is being used by the third revision.');
|
||||
|
||||
// Attach the second file to a user.
|
||||
$user = $this->drupalCreateUser();
|
||||
$user->$field_name->target_id = $node_file_r3->id();
|
||||
$user->$field_name->display = 1;
|
||||
$user->save();
|
||||
$this->drupalGet('user/' . $user->id() . '/edit');
|
||||
|
||||
// Delete the third revision and check that the file is not deleted yet.
|
||||
$this->drupalPostForm('node/' . $nid . '/revisions/' . $node_vid_r3 . '/delete', array(), t('Delete'));
|
||||
$this->assertFileExists($node_file_r3, 'Second file is still available after deleting third revision, since it is being used by the user.');
|
||||
$this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting third revision, since it is being used by the user.');
|
||||
$this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting third revision, since it is being used by the user.');
|
||||
|
||||
// Delete the user and check that the file is also deleted.
|
||||
$user->delete();
|
||||
// TODO: This seems like a bug in File API. Clearing the stat cache should
|
||||
// not be necessary here. The file really is deleted, but stream wrappers
|
||||
// doesn't seem to think so unless we clear the PHP file stat() cache.
|
||||
clearstatcache($node_file_r1->getFileUri());
|
||||
clearstatcache($node_file_r2->getFileUri());
|
||||
clearstatcache($node_file_r3->getFileUri());
|
||||
clearstatcache($node_file_r4->getFileUri());
|
||||
|
||||
// Call file_cron() to clean up the file. Make sure the changed timestamp
|
||||
// of the file is older than the system.file.temporary_maximum_age
|
||||
// configuration value.
|
||||
db_update('file_managed')
|
||||
->fields(array(
|
||||
'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1),
|
||||
))
|
||||
->condition('fid', $node_file_r3->id())
|
||||
->execute();
|
||||
\Drupal::service('cron')->run();
|
||||
|
||||
$this->assertFileNotExists($node_file_r3, 'Second file is now deleted after deleting third revision, since it is no longer being used by any other nodes.');
|
||||
$this->assertFileEntryNotExists($node_file_r3, 'Second file entry is now deleted after deleting third revision, since it is no longer being used by any other nodes.');
|
||||
|
||||
// Delete the entire node and check that the original file is deleted.
|
||||
$this->drupalPostForm('node/' . $nid . '/delete', array(), t('Delete'));
|
||||
// Call file_cron() to clean up the file. Make sure the changed timestamp
|
||||
// of the file is older than the system.file.temporary_maximum_age
|
||||
// configuration value.
|
||||
db_update('file_managed')
|
||||
->fields(array(
|
||||
'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1),
|
||||
))
|
||||
->condition('fid', $node_file_r1->id())
|
||||
->execute();
|
||||
\Drupal::service('cron')->run();
|
||||
$this->assertFileNotExists($node_file_r1, 'Original file is deleted after deleting the entire node with two revisions remaining.');
|
||||
$this->assertFileEntryNotExists($node_file_r1, 'Original file entry is deleted after deleting the entire node with two revisions remaining.');
|
||||
}
|
||||
|
||||
}
|
||||
302
web/core/modules/file/src/Tests/FileFieldTestBase.php
Normal file
302
web/core/modules/file/src/Tests/FileFieldTestBase.php
Normal file
|
|
@ -0,0 +1,302 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\file\FileInterface;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Provides methods specifically for testing File module's field handling.
|
||||
*/
|
||||
abstract class FileFieldTestBase extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('node', 'file', 'file_module_test', 'field_ui');
|
||||
|
||||
/**
|
||||
* An user with administration permissions.
|
||||
*
|
||||
* @var \Drupal\user\UserInterface
|
||||
*/
|
||||
protected $adminUser;
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->adminUser = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer users', 'administer permissions', 'administer content types', 'administer node fields', 'administer node display', 'administer nodes', 'bypass node access'));
|
||||
$this->drupalLogin($this->adminUser);
|
||||
$this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a sample file of the specified type.
|
||||
*
|
||||
* @return \Drupal\file\FileInterface
|
||||
*/
|
||||
function getTestFile($type_name, $size = NULL) {
|
||||
// Get a file to upload.
|
||||
$file = current($this->drupalGetTestFiles($type_name, $size));
|
||||
|
||||
// Add a filesize property to files as would be read by
|
||||
// \Drupal\file\Entity\File::load().
|
||||
$file->filesize = filesize($file->uri);
|
||||
|
||||
return File::create((array) $file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the fid of the last inserted file.
|
||||
*/
|
||||
function getLastFileId() {
|
||||
return (int) db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new file field.
|
||||
*
|
||||
* @param string $name
|
||||
* The name of the new field (all lowercase), exclude the "field_" prefix.
|
||||
* @param string $entity_type
|
||||
* The entity type.
|
||||
* @param string $bundle
|
||||
* The bundle that this field will be added to.
|
||||
* @param array $storage_settings
|
||||
* A list of field storage settings that will be added to the defaults.
|
||||
* @param array $field_settings
|
||||
* A list of instance settings that will be added to the instance defaults.
|
||||
* @param array $widget_settings
|
||||
* A list of widget settings that will be added to the widget defaults.
|
||||
*/
|
||||
function createFileField($name, $entity_type, $bundle, $storage_settings = array(), $field_settings = array(), $widget_settings = array()) {
|
||||
$field_storage = FieldStorageConfig::create(array(
|
||||
'entity_type' => $entity_type,
|
||||
'field_name' => $name,
|
||||
'type' => 'file',
|
||||
'settings' => $storage_settings,
|
||||
'cardinality' => !empty($storage_settings['cardinality']) ? $storage_settings['cardinality'] : 1,
|
||||
));
|
||||
$field_storage->save();
|
||||
|
||||
$this->attachFileField($name, $entity_type, $bundle, $field_settings, $widget_settings);
|
||||
return $field_storage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches a file field to an entity.
|
||||
*
|
||||
* @param string $name
|
||||
* The name of the new field (all lowercase), exclude the "field_" prefix.
|
||||
* @param string $entity_type
|
||||
* The entity type this field will be added to.
|
||||
* @param string $bundle
|
||||
* The bundle this field will be added to.
|
||||
* @param array $field_settings
|
||||
* A list of field settings that will be added to the defaults.
|
||||
* @param array $widget_settings
|
||||
* A list of widget settings that will be added to the widget defaults.
|
||||
*/
|
||||
function attachFileField($name, $entity_type, $bundle, $field_settings = array(), $widget_settings = array()) {
|
||||
$field = array(
|
||||
'field_name' => $name,
|
||||
'label' => $name,
|
||||
'entity_type' => $entity_type,
|
||||
'bundle' => $bundle,
|
||||
'required' => !empty($field_settings['required']),
|
||||
'settings' => $field_settings,
|
||||
);
|
||||
FieldConfig::create($field)->save();
|
||||
|
||||
entity_get_form_display($entity_type, $bundle, 'default')
|
||||
->setComponent($name, array(
|
||||
'type' => 'file_generic',
|
||||
'settings' => $widget_settings,
|
||||
))
|
||||
->save();
|
||||
// Assign display settings.
|
||||
entity_get_display($entity_type, $bundle, 'default')
|
||||
->setComponent($name, array(
|
||||
'label' => 'hidden',
|
||||
'type' => 'file_default',
|
||||
))
|
||||
->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates an existing file field with new settings.
|
||||
*/
|
||||
function updateFileField($name, $type_name, $field_settings = array(), $widget_settings = array()) {
|
||||
$field = FieldConfig::loadByName('node', $type_name, $name);
|
||||
$field->setSettings(array_merge($field->getSettings(), $field_settings));
|
||||
$field->save();
|
||||
|
||||
entity_get_form_display('node', $type_name, 'default')
|
||||
->setComponent($name, array(
|
||||
'settings' => $widget_settings,
|
||||
))
|
||||
->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads a file to a node.
|
||||
*
|
||||
* @param \Drupal\file\FileInterface $file
|
||||
* The File to be uploaded.
|
||||
* @param string $field_name
|
||||
* The name of the field on which the files should be saved.
|
||||
* @param $nid_or_type
|
||||
* A numeric node id to upload files to an existing node, or a string
|
||||
* indicating the desired bundle for a new node.
|
||||
* @param bool $new_revision
|
||||
* The revision number.
|
||||
* @param array $extras
|
||||
* Additional values when a new node is created.
|
||||
*
|
||||
* @return int
|
||||
* The node id.
|
||||
*/
|
||||
function uploadNodeFile(FileInterface $file, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = array()) {
|
||||
return $this->uploadNodeFiles([$file], $field_name, $nid_or_type, $new_revision, $extras);
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads multiple files to a node.
|
||||
*
|
||||
* @param \Drupal\file\FileInterface[] $files
|
||||
* The files to be uploaded.
|
||||
* @param string $field_name
|
||||
* The name of the field on which the files should be saved.
|
||||
* @param $nid_or_type
|
||||
* A numeric node id to upload files to an existing node, or a string
|
||||
* indicating the desired bundle for a new node.
|
||||
* @param bool $new_revision
|
||||
* The revision number.
|
||||
* @param array $extras
|
||||
* Additional values when a new node is created.
|
||||
*
|
||||
* @return int
|
||||
* The node id.
|
||||
*/
|
||||
function uploadNodeFiles(array $files, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = array()) {
|
||||
$edit = array(
|
||||
'title[0][value]' => $this->randomMachineName(),
|
||||
'revision' => (string) (int) $new_revision,
|
||||
);
|
||||
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
if (is_numeric($nid_or_type)) {
|
||||
$nid = $nid_or_type;
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
}
|
||||
else {
|
||||
// Add a new node.
|
||||
$extras['type'] = $nid_or_type;
|
||||
$node = $this->drupalCreateNode($extras);
|
||||
$nid = $node->id();
|
||||
// Save at least one revision to better simulate a real site.
|
||||
$node->setNewRevision();
|
||||
$node->save();
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$this->assertNotEqual($nid, $node->getRevisionId(), 'Node revision exists.');
|
||||
}
|
||||
|
||||
// Attach files to the node.
|
||||
$field_storage = FieldStorageConfig::loadByName('node', $field_name);
|
||||
// File input name depends on number of files already uploaded.
|
||||
$field_num = count($node->{$field_name});
|
||||
$name = 'files[' . $field_name . "_$field_num]";
|
||||
if ($field_storage->getCardinality() != 1) {
|
||||
$name .= '[]';
|
||||
}
|
||||
foreach ($files as $file) {
|
||||
$file_path = $this->container->get('file_system')->realpath($file->getFileUri());
|
||||
if (count($files) == 1) {
|
||||
$edit[$name] = $file_path;
|
||||
}
|
||||
else {
|
||||
$edit[$name][] = $file_path;
|
||||
}
|
||||
}
|
||||
$this->drupalPostForm("node/$nid/edit", $edit, t('Save and keep published'));
|
||||
|
||||
return $nid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a file from a node.
|
||||
*
|
||||
* Note that if replacing a file, it must first be removed then added again.
|
||||
*/
|
||||
function removeNodeFile($nid, $new_revision = TRUE) {
|
||||
$edit = array(
|
||||
'revision' => (string) (int) $new_revision,
|
||||
);
|
||||
|
||||
$this->drupalPostForm('node/' . $nid . '/edit', array(), t('Remove'));
|
||||
$this->drupalPostForm(NULL, $edit, t('Save and keep published'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces a file within a node.
|
||||
*/
|
||||
function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
|
||||
$edit = array(
|
||||
'files[' . $field_name . '_0]' => drupal_realpath($file->getFileUri()),
|
||||
'revision' => (string) (int) $new_revision,
|
||||
);
|
||||
|
||||
$this->drupalPostForm('node/' . $nid . '/edit', array(), t('Remove'));
|
||||
$this->drupalPostForm(NULL, $edit, t('Save and keep published'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that a file exists physically on disk.
|
||||
*/
|
||||
function assertFileExists($file, $message = NULL) {
|
||||
$message = isset($message) ? $message : format_string('File %file exists on the disk.', array('%file' => $file->getFileUri()));
|
||||
$this->assertTrue(is_file($file->getFileUri()), $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that a file exists in the database.
|
||||
*/
|
||||
function assertFileEntryExists($file, $message = NULL) {
|
||||
$this->container->get('entity.manager')->getStorage('file')->resetCache();
|
||||
$db_file = File::load($file->id());
|
||||
$message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', array('%file' => $file->getFileUri()));
|
||||
$this->assertEqual($db_file->getFileUri(), $file->getFileUri(), $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that a file does not exist on disk.
|
||||
*/
|
||||
function assertFileNotExists($file, $message = NULL) {
|
||||
$message = isset($message) ? $message : format_string('File %file exists on the disk.', array('%file' => $file->getFileUri()));
|
||||
$this->assertFalse(is_file($file->getFileUri()), $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that a file does not exist in the database.
|
||||
*/
|
||||
function assertFileEntryNotExists($file, $message) {
|
||||
$this->container->get('entity.manager')->getStorage('file')->resetCache();
|
||||
$message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', array('%file' => $file->getFileUri()));
|
||||
$this->assertFalse(File::load($file->id()), $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that a file's status is set to permanent in the database.
|
||||
*/
|
||||
function assertFileIsPermanent(FileInterface $file, $message = NULL) {
|
||||
$message = isset($message) ? $message : format_string('File %file is permanent.', array('%file' => $file->getFileUri()));
|
||||
$this->assertTrue($file->isPermanent(), $message);
|
||||
}
|
||||
|
||||
}
|
||||
188
web/core/modules/file/src/Tests/FileFieldValidateTest.php
Normal file
188
web/core/modules/file/src/Tests/FileFieldValidateTest.php
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\Core\Field\FieldStorageDefinitionInterface;
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests validation functions such as file type, max file size, max size per
|
||||
* node, and required.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FileFieldValidateTest extends FileFieldTestBase {
|
||||
|
||||
/**
|
||||
* Tests the required property on file fields.
|
||||
*/
|
||||
function testRequired() {
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
$type_name = 'article';
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$storage = $this->createFileField($field_name, 'node', $type_name, array(), array('required' => '1'));
|
||||
$field = FieldConfig::loadByName('node', $type_name, $field_name);
|
||||
|
||||
$test_file = $this->getTestFile('text');
|
||||
|
||||
// Try to post a new node without uploading a file.
|
||||
$edit = array();
|
||||
$edit['title[0][value]'] = $this->randomMachineName();
|
||||
$this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish'));
|
||||
$this->assertRaw(t('@title field is required.', array('@title' => $field->getLabel())), 'Node save failed when required file field was empty.');
|
||||
|
||||
// Create a new node with the uploaded file.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
$this->assertTrue($nid !== FALSE, format_string('uploadNodeFile(@test_file, @field_name, @type_name) succeeded', array('@test_file' => $test_file->getFileUri(), '@field_name' => $field_name, '@type_name' => $type_name)));
|
||||
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
$this->assertFileExists($node_file, 'File exists after uploading to the required field.');
|
||||
$this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required field.');
|
||||
|
||||
// Try again with a multiple value field.
|
||||
$storage->delete();
|
||||
$this->createFileField($field_name, 'node', $type_name, array('cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED), array('required' => '1'));
|
||||
|
||||
// Try to post a new node without uploading a file in the multivalue field.
|
||||
$edit = array();
|
||||
$edit['title[0][value]'] = $this->randomMachineName();
|
||||
$this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish'));
|
||||
$this->assertRaw(t('@title field is required.', array('@title' => $field->getLabel())), 'Node save failed when required multiple value file field was empty.');
|
||||
|
||||
// Create a new node with the uploaded file into the multivalue field.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
$this->assertFileExists($node_file, 'File exists after uploading to the required multiple value field.');
|
||||
$this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required multiple value field.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the max file size validator.
|
||||
*/
|
||||
function testFileMaxSize() {
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
$type_name = 'article';
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$this->createFileField($field_name, 'node', $type_name, array(), array('required' => '1'));
|
||||
|
||||
$small_file = $this->getTestFile('text', 131072); // 128KB.
|
||||
$large_file = $this->getTestFile('text', 1310720); // 1.2MB
|
||||
|
||||
// Test uploading both a large and small file with different increments.
|
||||
$sizes = array(
|
||||
'1M' => 1048576,
|
||||
'1024K' => 1048576,
|
||||
'1048576' => 1048576,
|
||||
);
|
||||
|
||||
foreach ($sizes as $max_filesize => $file_limit) {
|
||||
// Set the max file upload size.
|
||||
$this->updateFileField($field_name, $type_name, array('max_filesize' => $max_filesize));
|
||||
|
||||
// Create a new node with the small file, which should pass.
|
||||
$nid = $this->uploadNodeFile($small_file, $field_name, $type_name);
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
$this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) under the max limit (%maxsize).', array('%filesize' => format_size($small_file->getSize()), '%maxsize' => $max_filesize)));
|
||||
$this->assertFileEntryExists($node_file, format_string('File entry exists after uploading a file (%filesize) under the max limit (%maxsize).', array('%filesize' => format_size($small_file->getSize()), '%maxsize' => $max_filesize)));
|
||||
|
||||
// Check that uploading the large file fails (1M limit).
|
||||
$this->uploadNodeFile($large_file, $field_name, $type_name);
|
||||
$error_message = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($large_file->getSize()), '%maxsize' => format_size($file_limit)));
|
||||
$this->assertRaw($error_message, format_string('Node save failed when file (%filesize) exceeded the max upload size (%maxsize).', array('%filesize' => format_size($large_file->getSize()), '%maxsize' => $max_filesize)));
|
||||
}
|
||||
|
||||
// Turn off the max filesize.
|
||||
$this->updateFileField($field_name, $type_name, array('max_filesize' => ''));
|
||||
|
||||
// Upload the big file successfully.
|
||||
$nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
$this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->getSize()))));
|
||||
$this->assertFileEntryExists($node_file, format_string('File entry exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->getSize()))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests file extension checking.
|
||||
*/
|
||||
function testFileExtension() {
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
$type_name = 'article';
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$this->createFileField($field_name, 'node', $type_name);
|
||||
|
||||
$test_file = $this->getTestFile('image');
|
||||
list(, $test_file_extension) = explode('.', $test_file->getFilename());
|
||||
|
||||
// Disable extension checking.
|
||||
$this->updateFileField($field_name, $type_name, array('file_extensions' => ''));
|
||||
|
||||
// Check that the file can be uploaded with no extension checking.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
$this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.');
|
||||
$this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.');
|
||||
|
||||
// Enable extension checking for text files.
|
||||
$this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt'));
|
||||
|
||||
// Check that the file with the wrong extension cannot be uploaded.
|
||||
$this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
$error_message = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => 'txt'));
|
||||
$this->assertRaw($error_message, 'Node save failed when file uploaded with the wrong extension.');
|
||||
|
||||
// Enable extension checking for text and image files.
|
||||
$this->updateFileField($field_name, $type_name, array('file_extensions' => "txt $test_file_extension"));
|
||||
|
||||
// Check that the file can be uploaded with extension checking.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
$this->assertFileExists($node_file, 'File exists after uploading a file with extension checking.');
|
||||
$this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with extension checking.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that a file can always be removed if it does not pass validation.
|
||||
*/
|
||||
public function testFileRemoval() {
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
$type_name = 'article';
|
||||
$field_name = 'file_test';
|
||||
$this->createFileField($field_name, 'node', $type_name);
|
||||
|
||||
$test_file = $this->getTestFile('image');
|
||||
|
||||
// Disable extension checking.
|
||||
$this->updateFileField($field_name, $type_name, array('file_extensions' => ''));
|
||||
|
||||
// Check that the file can be uploaded with no extension checking.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
$this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.');
|
||||
$this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.');
|
||||
|
||||
// Enable extension checking for text files.
|
||||
$this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt'));
|
||||
|
||||
// Check that the file can still be removed.
|
||||
$this->removeNodeFile($nid);
|
||||
$this->assertNoText('Only files with the following extensions are allowed: txt.');
|
||||
$this->assertText('Article ' . $node->getTitle() . ' has been updated.');
|
||||
}
|
||||
|
||||
}
|
||||
602
web/core/modules/file/src/Tests/FileFieldWidgetTest.php
Normal file
602
web/core/modules/file/src/Tests/FileFieldWidgetTest.php
Normal file
|
|
@ -0,0 +1,602 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\comment\Entity\Comment;
|
||||
use Drupal\comment\Tests\CommentTestTrait;
|
||||
use Drupal\Component\Utility\Unicode;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\field_ui\Tests\FieldUiTestTrait;
|
||||
use Drupal\user\RoleInterface;
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\user\Entity\User;
|
||||
use Drupal\user\UserInterface;
|
||||
|
||||
/**
|
||||
* Tests the file field widget, single and multi-valued, with and without AJAX,
|
||||
* with public and private files.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FileFieldWidgetTest extends FileFieldTestBase {
|
||||
|
||||
use CommentTestTrait;
|
||||
use FieldUiTestTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->drupalPlaceBlock('system_breadcrumb_block');
|
||||
}
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('comment', 'block');
|
||||
|
||||
/**
|
||||
* Creates a temporary file, for a specific user.
|
||||
*
|
||||
* @param string $data
|
||||
* A string containing the contents of the file.
|
||||
* @param \Drupal\user\UserInterface $user
|
||||
* The user of the file owner.
|
||||
*
|
||||
* @return \Drupal\file\FileInterface
|
||||
* A file object, or FALSE on error.
|
||||
*/
|
||||
protected function createTemporaryFile($data, UserInterface $user = NULL) {
|
||||
$file = file_save_data($data, NULL, NULL);
|
||||
|
||||
if ($file) {
|
||||
if ($user) {
|
||||
$file->setOwner($user);
|
||||
}
|
||||
else {
|
||||
$file->setOwner($this->adminUser);
|
||||
}
|
||||
// Change the file status to be temporary.
|
||||
$file->setTemporary();
|
||||
// Save the changes.
|
||||
$file->save();
|
||||
}
|
||||
|
||||
return $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests upload and remove buttons for a single-valued File field.
|
||||
*/
|
||||
function testSingleValuedWidget() {
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
$type_name = 'article';
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$this->createFileField($field_name, 'node', $type_name);
|
||||
|
||||
$test_file = $this->getTestFile('text');
|
||||
|
||||
foreach (array('nojs', 'js') as $type) {
|
||||
// Create a new node with the uploaded file and ensure it got uploaded
|
||||
// successfully.
|
||||
// @todo This only tests a 'nojs' submission, because drupalPostAjaxForm()
|
||||
// does not yet support file uploads.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
$this->assertFileExists($node_file, 'New file saved to disk on node creation.');
|
||||
|
||||
// Ensure the file can be downloaded.
|
||||
$this->drupalGet(file_create_url($node_file->getFileUri()));
|
||||
$this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
|
||||
|
||||
// Ensure the edit page has a remove button instead of an upload button.
|
||||
$this->drupalGet("node/$nid/edit");
|
||||
$this->assertNoFieldByXPath('//input[@type="submit"]', t('Upload'), 'Node with file does not display the "Upload" button.');
|
||||
$this->assertFieldByXpath('//input[@type="submit"]', t('Remove'), 'Node with file displays the "Remove" button.');
|
||||
|
||||
// "Click" the remove button (emulating either a nojs or js submission).
|
||||
switch ($type) {
|
||||
case 'nojs':
|
||||
$this->drupalPostForm(NULL, array(), t('Remove'));
|
||||
break;
|
||||
case 'js':
|
||||
$button = $this->xpath('//input[@type="submit" and @value="' . t('Remove') . '"]');
|
||||
$this->drupalPostAjaxForm(NULL, array(), array((string) $button[0]['name'] => (string) $button[0]['value']));
|
||||
break;
|
||||
}
|
||||
|
||||
// Ensure the page now has an upload button instead of a remove button.
|
||||
$this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), 'After clicking the "Remove" button, it is no longer displayed.');
|
||||
$this->assertFieldByXpath('//input[@type="submit"]', t('Upload'), 'After clicking the "Remove" button, the "Upload" button is displayed.');
|
||||
// Test label has correct 'for' attribute.
|
||||
$input = $this->xpath('//input[@name="files[' . $field_name . '_0]"]');
|
||||
$label = $this->xpath('//label[@for="' . (string) $input[0]['id'] . '"]');
|
||||
$this->assertTrue(isset($label[0]), 'Label for upload found.');
|
||||
|
||||
// Save the node and ensure it does not have the file.
|
||||
$this->drupalPostForm(NULL, array(), t('Save and keep published'));
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$this->assertTrue(empty($node->{$field_name}->target_id), 'File was successfully removed from the node.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests upload and remove buttons for multiple multi-valued File fields.
|
||||
*/
|
||||
function testMultiValuedWidget() {
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
$type_name = 'article';
|
||||
// Use explicit names instead of random names for those fields, because of a
|
||||
// bug in drupalPostForm() with multiple file uploads in one form, where the
|
||||
// order of uploads depends on the order in which the upload elements are
|
||||
// added to the $form (which, in the current implementation of
|
||||
// FileStorage::listAll(), comes down to the alphabetical order on field
|
||||
// names).
|
||||
$field_name = 'test_file_field_1';
|
||||
$field_name2 = 'test_file_field_2';
|
||||
$cardinality = 3;
|
||||
$this->createFileField($field_name, 'node', $type_name, array('cardinality' => $cardinality));
|
||||
$this->createFileField($field_name2, 'node', $type_name, array('cardinality' => $cardinality));
|
||||
|
||||
$test_file = $this->getTestFile('text');
|
||||
|
||||
foreach (array('nojs', 'js') as $type) {
|
||||
// Visit the node creation form, and upload 3 files for each field. Since
|
||||
// the field has cardinality of 3, ensure the "Upload" button is displayed
|
||||
// until after the 3rd file, and after that, isn't displayed. Because
|
||||
// SimpleTest triggers the last button with a given name, so upload to the
|
||||
// second field first.
|
||||
// @todo This is only testing a non-Ajax upload, because drupalPostAjaxForm()
|
||||
// does not yet emulate jQuery's file upload.
|
||||
//
|
||||
$this->drupalGet("node/add/$type_name");
|
||||
foreach (array($field_name2, $field_name) as $each_field_name) {
|
||||
for ($delta = 0; $delta < 3; $delta++) {
|
||||
$edit = array('files[' . $each_field_name . '_' . $delta . '][]' => drupal_realpath($test_file->getFileUri()));
|
||||
// If the Upload button doesn't exist, drupalPostForm() will automatically
|
||||
// fail with an assertion message.
|
||||
$this->drupalPostForm(NULL, $edit, t('Upload'));
|
||||
}
|
||||
}
|
||||
$this->assertNoFieldByXpath('//input[@type="submit"]', t('Upload'), 'After uploading 3 files for each field, the "Upload" button is no longer displayed.');
|
||||
|
||||
$num_expected_remove_buttons = 6;
|
||||
|
||||
foreach (array($field_name, $field_name2) as $current_field_name) {
|
||||
// How many uploaded files for the current field are remaining.
|
||||
$remaining = 3;
|
||||
// Test clicking each "Remove" button. For extra robustness, test them out
|
||||
// of sequential order. They are 0-indexed, and get renumbered after each
|
||||
// iteration, so array(1, 1, 0) means:
|
||||
// - First remove the 2nd file.
|
||||
// - Then remove what is then the 2nd file (was originally the 3rd file).
|
||||
// - Then remove the first file.
|
||||
foreach (array(1, 1, 0) as $delta) {
|
||||
// Ensure we have the expected number of Remove buttons, and that they
|
||||
// are numbered sequentially.
|
||||
$buttons = $this->xpath('//input[@type="submit" and @value="Remove"]');
|
||||
$this->assertTrue(is_array($buttons) && count($buttons) === $num_expected_remove_buttons, format_string('There are %n "Remove" buttons displayed (JSMode=%type).', array('%n' => $num_expected_remove_buttons, '%type' => $type)));
|
||||
foreach ($buttons as $i => $button) {
|
||||
$key = $i >= $remaining ? $i - $remaining : $i;
|
||||
$check_field_name = $field_name2;
|
||||
if ($current_field_name == $field_name && $i < $remaining) {
|
||||
$check_field_name = $field_name;
|
||||
}
|
||||
|
||||
$this->assertIdentical((string) $button['name'], $check_field_name . '_' . $key . '_remove_button');
|
||||
}
|
||||
|
||||
// "Click" the remove button (emulating either a nojs or js submission).
|
||||
$button_name = $current_field_name . '_' . $delta . '_remove_button';
|
||||
switch ($type) {
|
||||
case 'nojs':
|
||||
// drupalPostForm() takes a $submit parameter that is the value of the
|
||||
// button whose click we want to emulate. Since we have multiple
|
||||
// buttons with the value "Remove", and want to control which one we
|
||||
// use, we change the value of the other ones to something else.
|
||||
// Since non-clicked buttons aren't included in the submitted POST
|
||||
// data, and since drupalPostForm() will result in $this being updated
|
||||
// with a newly rebuilt form, this doesn't cause problems.
|
||||
foreach ($buttons as $button) {
|
||||
if ($button['name'] != $button_name) {
|
||||
$button['value'] = 'DUMMY';
|
||||
}
|
||||
}
|
||||
$this->drupalPostForm(NULL, array(), t('Remove'));
|
||||
break;
|
||||
case 'js':
|
||||
// drupalPostAjaxForm() lets us target the button precisely, so we don't
|
||||
// require the workaround used above for nojs.
|
||||
$this->drupalPostAjaxForm(NULL, array(), array($button_name => t('Remove')));
|
||||
break;
|
||||
}
|
||||
$num_expected_remove_buttons--;
|
||||
$remaining--;
|
||||
|
||||
// Ensure an "Upload" button for the current field is displayed with the
|
||||
// correct name.
|
||||
$upload_button_name = $current_field_name . '_' . $remaining . '_upload_button';
|
||||
$buttons = $this->xpath('//input[@type="submit" and @value="Upload" and @name=:name]', array(':name' => $upload_button_name));
|
||||
$this->assertTrue(is_array($buttons) && count($buttons) == 1, format_string('The upload button is displayed with the correct name (JSMode=%type).', array('%type' => $type)));
|
||||
|
||||
// Ensure only at most one button per field is displayed.
|
||||
$buttons = $this->xpath('//input[@type="submit" and @value="Upload"]');
|
||||
$expected = $current_field_name == $field_name ? 1 : 2;
|
||||
$this->assertTrue(is_array($buttons) && count($buttons) == $expected, format_string('After removing a file, only one "Upload" button for each possible field is displayed (JSMode=%type).', array('%type' => $type)));
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure the page now has no Remove buttons.
|
||||
$this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), format_string('After removing all files, there is no "Remove" button displayed (JSMode=%type).', array('%type' => $type)));
|
||||
|
||||
// Save the node and ensure it does not have any files.
|
||||
$this->drupalPostForm(NULL, array('title[0][value]' => $this->randomMachineName()), t('Save and publish'));
|
||||
$matches = array();
|
||||
preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
|
||||
$nid = $matches[1];
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$this->assertTrue(empty($node->{$field_name}->target_id), 'Node was successfully saved without any files.');
|
||||
}
|
||||
|
||||
$upload_files_node_creation = array($test_file, $test_file);
|
||||
// Try to upload multiple files, but fewer than the maximum.
|
||||
$nid = $this->uploadNodeFiles($upload_files_node_creation, $field_name, $type_name);
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$this->assertEqual(count($node->{$field_name}), count($upload_files_node_creation), 'Node was successfully saved with mulitple files.');
|
||||
|
||||
// Try to upload more files than allowed on revision.
|
||||
$upload_files_node_revision = array($test_file, $test_file, $test_file, $test_file);
|
||||
$this->uploadNodeFiles($upload_files_node_revision, $field_name, $nid, 1);
|
||||
$args = [
|
||||
'%field' => $field_name,
|
||||
'@max' => $cardinality,
|
||||
'@count' => count($upload_files_node_creation) + count($upload_files_node_revision),
|
||||
'%list' => implode(', ', array_fill(0, 3, $test_file->getFilename())),
|
||||
];
|
||||
$this->assertRaw(t('Field %field can only hold @max values but there were @count uploaded. The following files have been omitted as a result: %list.', $args));
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$this->assertEqual(count($node->{$field_name}), $cardinality, 'More files than allowed could not be saved to node.');
|
||||
|
||||
// Try to upload exactly the allowed number of files on revision. Create an
|
||||
// empty node first, to fill it in its first revision.
|
||||
$node = $this->drupalCreateNode([
|
||||
'type' => $type_name
|
||||
]);
|
||||
$this->uploadNodeFile($test_file, $field_name, $node->id(), 1);
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$this->assertEqual(count($node->{$field_name}), $cardinality, 'Node was successfully revised to maximum number of files.');
|
||||
|
||||
// Try to upload exactly the allowed number of files, new node.
|
||||
$upload_files = array_fill(0, $cardinality, $test_file);
|
||||
$nid = $this->uploadNodeFiles($upload_files, $field_name, $type_name);
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$this->assertEqual(count($node->{$field_name}), $cardinality, 'Node was successfully saved with maximum number of files.');
|
||||
|
||||
// Try to upload more files than allowed, new node.
|
||||
$upload_files[] = $test_file;
|
||||
$this->uploadNodeFiles($upload_files, $field_name, $type_name);
|
||||
|
||||
$args = [
|
||||
'%field' => $field_name,
|
||||
'@max' => $cardinality,
|
||||
'@count' => count($upload_files),
|
||||
'%list' => $test_file->getFileName(),
|
||||
];
|
||||
$this->assertRaw(t('Field %field can only hold @max values but there were @count uploaded. The following files have been omitted as a result: %list.', $args));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests a file field with a "Private files" upload destination setting.
|
||||
*/
|
||||
function testPrivateFileSetting() {
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
// Grant the admin user required permissions.
|
||||
user_role_grant_permissions($this->adminUser->roles[0]->target_id, array('administer node fields'));
|
||||
|
||||
$type_name = 'article';
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$this->createFileField($field_name, 'node', $type_name);
|
||||
$field = FieldConfig::loadByName('node', $type_name, $field_name);
|
||||
$field_id = $field->id();
|
||||
|
||||
$test_file = $this->getTestFile('text');
|
||||
|
||||
// Change the field setting to make its files private, and upload a file.
|
||||
$edit = array('settings[uri_scheme]' => 'private');
|
||||
$this->drupalPostForm("admin/structure/types/manage/$type_name/fields/$field_id/storage", $edit, t('Save field settings'));
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
$this->assertFileExists($node_file, 'New file saved to disk on node creation.');
|
||||
|
||||
// Ensure the private file is available to the user who uploaded it.
|
||||
$this->drupalGet(file_create_url($node_file->getFileUri()));
|
||||
$this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
|
||||
|
||||
// Ensure we can't change 'uri_scheme' field settings while there are some
|
||||
// entities with uploaded files.
|
||||
$this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_id/storage");
|
||||
$this->assertFieldByXpath('//input[@id="edit-settings-uri-scheme-public" and @disabled="disabled"]', 'public', 'Upload destination setting disabled.');
|
||||
|
||||
// Delete node and confirm that setting could be changed.
|
||||
$node->delete();
|
||||
$this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_id/storage");
|
||||
$this->assertFieldByXpath('//input[@id="edit-settings-uri-scheme-public" and not(@disabled)]', 'public', 'Upload destination setting enabled.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that download restrictions on private files work on comments.
|
||||
*/
|
||||
function testPrivateFileComment() {
|
||||
$user = $this->drupalCreateUser(array('access comments'));
|
||||
|
||||
// Grant the admin user required comment permissions.
|
||||
$roles = $this->adminUser->getRoles();
|
||||
user_role_grant_permissions($roles[1], array('administer comment fields', 'administer comments'));
|
||||
|
||||
// Revoke access comments permission from anon user, grant post to
|
||||
// authenticated.
|
||||
user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, array('access comments'));
|
||||
user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, array('post comments', 'skip comment approval'));
|
||||
|
||||
// Create a new field.
|
||||
$this->addDefaultCommentField('node', 'article');
|
||||
|
||||
$name = strtolower($this->randomMachineName());
|
||||
$label = $this->randomMachineName();
|
||||
$storage_edit = array('settings[uri_scheme]' => 'private');
|
||||
$this->fieldUIAddNewField('admin/structure/comment/manage/comment', $name, $label, 'file', $storage_edit);
|
||||
|
||||
// Manually clear cache on the tester side.
|
||||
\Drupal::entityManager()->clearCachedFieldDefinitions();
|
||||
|
||||
// Create node.
|
||||
$edit = array(
|
||||
'title[0][value]' => $this->randomMachineName(),
|
||||
);
|
||||
$this->drupalPostForm('node/add/article', $edit, t('Save and publish'));
|
||||
$node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
|
||||
|
||||
// Add a comment with a file.
|
||||
$text_file = $this->getTestFile('text');
|
||||
$edit = array(
|
||||
'files[field_' . $name . '_' . 0 . ']' => drupal_realpath($text_file->getFileUri()),
|
||||
'comment_body[0][value]' => $comment_body = $this->randomMachineName(),
|
||||
);
|
||||
$this->drupalPostForm('node/' . $node->id(), $edit, t('Save'));
|
||||
|
||||
// Get the comment ID.
|
||||
preg_match('/comment-([0-9]+)/', $this->getUrl(), $matches);
|
||||
$cid = $matches[1];
|
||||
|
||||
// Log in as normal user.
|
||||
$this->drupalLogin($user);
|
||||
|
||||
$comment = Comment::load($cid);
|
||||
$comment_file = $comment->{'field_' . $name}->entity;
|
||||
$this->assertFileExists($comment_file, 'New file saved to disk on node creation.');
|
||||
// Test authenticated file download.
|
||||
$url = file_create_url($comment_file->getFileUri());
|
||||
$this->assertNotEqual($url, NULL, 'Confirmed that the URL is valid');
|
||||
$this->drupalGet(file_create_url($comment_file->getFileUri()));
|
||||
$this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
|
||||
|
||||
// Test anonymous file download.
|
||||
$this->drupalLogout();
|
||||
$this->drupalGet(file_create_url($comment_file->getFileUri()));
|
||||
$this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
|
||||
|
||||
// Unpublishes node.
|
||||
$this->drupalLogin($this->adminUser);
|
||||
$this->drupalPostForm('node/' . $node->id() . '/edit', array(), t('Save and unpublish'));
|
||||
|
||||
// Ensures normal user can no longer download the file.
|
||||
$this->drupalLogin($user);
|
||||
$this->drupalGet(file_create_url($comment_file->getFileUri()));
|
||||
$this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests validation with the Upload button.
|
||||
*/
|
||||
function testWidgetValidation() {
|
||||
$type_name = 'article';
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$this->createFileField($field_name, 'node', $type_name);
|
||||
$this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt'));
|
||||
|
||||
foreach (array('nojs', 'js') as $type) {
|
||||
// Create node and prepare files for upload.
|
||||
$node = $this->drupalCreateNode(array('type' => 'article'));
|
||||
$nid = $node->id();
|
||||
$this->drupalGet("node/$nid/edit");
|
||||
$test_file_text = $this->getTestFile('text');
|
||||
$test_file_image = $this->getTestFile('image');
|
||||
$name = 'files[' . $field_name . '_0]';
|
||||
|
||||
// Upload file with incorrect extension, check for validation error.
|
||||
$edit[$name] = drupal_realpath($test_file_image->getFileUri());
|
||||
switch ($type) {
|
||||
case 'nojs':
|
||||
$this->drupalPostForm(NULL, $edit, t('Upload'));
|
||||
break;
|
||||
case 'js':
|
||||
$button = $this->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]');
|
||||
$this->drupalPostAjaxForm(NULL, $edit, array((string) $button[0]['name'] => (string) $button[0]['value']));
|
||||
break;
|
||||
}
|
||||
$error_message = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => 'txt'));
|
||||
$this->assertRaw($error_message, t('Validation error when file with wrong extension uploaded (JSMode=%type).', array('%type' => $type)));
|
||||
|
||||
// Upload file with correct extension, check that error message is removed.
|
||||
$edit[$name] = drupal_realpath($test_file_text->getFileUri());
|
||||
switch ($type) {
|
||||
case 'nojs':
|
||||
$this->drupalPostForm(NULL, $edit, t('Upload'));
|
||||
break;
|
||||
case 'js':
|
||||
$button = $this->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]');
|
||||
$this->drupalPostAjaxForm(NULL, $edit, array((string) $button[0]['name'] => (string) $button[0]['value']));
|
||||
break;
|
||||
}
|
||||
$this->assertNoRaw($error_message, t('Validation error removed when file with correct extension uploaded (JSMode=%type).', array('%type' => $type)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests file widget element.
|
||||
*/
|
||||
public function testWidgetElement() {
|
||||
$field_name = Unicode::strtolower($this->randomMachineName());
|
||||
$html_name = str_replace('_', '-', $field_name);
|
||||
$this->createFileField($field_name, 'node', 'article', ['cardinality' => FieldStorageConfig::CARDINALITY_UNLIMITED]);
|
||||
$file = $this->getTestFile('text');
|
||||
$xpath = "//details[@data-drupal-selector='edit-$html_name']/div[@class='details-wrapper']/table";
|
||||
|
||||
$this->drupalGet('node/add/article');
|
||||
|
||||
$elements = $this->xpath($xpath);
|
||||
|
||||
// If the field has no item, the table should not be visible.
|
||||
$this->assertIdentical(count($elements), 0);
|
||||
|
||||
// Upload a file.
|
||||
$edit['files[' . $field_name . '_0][]'] = $this->container->get('file_system')->realpath($file->getFileUri());
|
||||
$this->drupalPostAjaxForm(NULL, $edit, "{$field_name}_0_upload_button");
|
||||
|
||||
$elements = $this->xpath($xpath);
|
||||
|
||||
// If the field has at least a item, the table should be visible.
|
||||
$this->assertIdentical(count($elements), 1);
|
||||
|
||||
// Test for AJAX error when using progress bar on file field widget
|
||||
$key = $this->randomMachineName();
|
||||
$this->drupalPost('file/progress/' . $key, 'application/json', []);
|
||||
$this->assertNoResponse(500, t('No AJAX error when using progress bar on file field widget'));
|
||||
$this->assertText('Starting upload...');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests exploiting the temporary file removal of another user using fid.
|
||||
*/
|
||||
public function testTemporaryFileRemovalExploit() {
|
||||
// Create a victim user.
|
||||
$victim_user = $this->drupalCreateUser();
|
||||
|
||||
// Create an attacker user.
|
||||
$attacker_user = $this->drupalCreateUser(array(
|
||||
'access content',
|
||||
'create article content',
|
||||
'edit any article content',
|
||||
));
|
||||
|
||||
// Log in as the attacker user.
|
||||
$this->drupalLogin($attacker_user);
|
||||
|
||||
// Perform tests using the newly created users.
|
||||
$this->doTestTemporaryFileRemovalExploit($victim_user, $attacker_user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests exploiting the temporary file removal for anonymous users using fid.
|
||||
*/
|
||||
public function testTemporaryFileRemovalExploitAnonymous() {
|
||||
// Set up an anonymous victim user.
|
||||
$victim_user = User::getAnonymousUser();
|
||||
|
||||
// Set up an anonymous attacker user.
|
||||
$attacker_user = User::getAnonymousUser();
|
||||
|
||||
// Set up permissions for anonymous attacker user.
|
||||
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array(
|
||||
'access content' => TRUE,
|
||||
'create article content' => TRUE,
|
||||
'edit any article content' => TRUE,
|
||||
));
|
||||
|
||||
// Log out so as to be the anonymous attacker user.
|
||||
$this->drupalLogout();
|
||||
|
||||
// Perform tests using the newly set up anonymous users.
|
||||
$this->doTestTemporaryFileRemovalExploit($victim_user, $attacker_user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper for testing exploiting the temporary file removal using fid.
|
||||
*
|
||||
* @param \Drupal\user\UserInterface $victim_user
|
||||
* The victim user.
|
||||
* @param \Drupal\user\UserInterface $attacker_user
|
||||
* The attacker user.
|
||||
*/
|
||||
protected function doTestTemporaryFileRemovalExploit(UserInterface $victim_user, UserInterface $attacker_user) {
|
||||
$type_name = 'article';
|
||||
$field_name = 'test_file_field';
|
||||
$this->createFileField($field_name, 'node', $type_name);
|
||||
|
||||
$test_file = $this->getTestFile('text');
|
||||
foreach (array('nojs', 'js') as $type) {
|
||||
// Create a temporary file owned by the victim user. This will be as if
|
||||
// they had uploaded the file, but not saved the node they were editing
|
||||
// or creating.
|
||||
$victim_tmp_file = $this->createTemporaryFile('some text', $victim_user);
|
||||
$victim_tmp_file = File::load($victim_tmp_file->id());
|
||||
$this->assertTrue($victim_tmp_file->isTemporary(), 'New file saved to disk is temporary.');
|
||||
$this->assertFalse(empty($victim_tmp_file->id()), 'New file has an fid.');
|
||||
$this->assertEqual($victim_user->id(), $victim_tmp_file->getOwnerId(), 'New file belongs to the victim.');
|
||||
|
||||
// Have attacker create a new node with a different uploaded file and
|
||||
// ensure it got uploaded successfully.
|
||||
$edit = [
|
||||
'title[0][value]' => $type . '-title' ,
|
||||
];
|
||||
|
||||
// Attach a file to a node.
|
||||
$edit['files[' . $field_name . '_0]'] = $this->container->get('file_system')->realpath($test_file->getFileUri());
|
||||
$this->drupalPostForm(Url::fromRoute('node.add', array('node_type' => $type_name)), $edit, t('Save'));
|
||||
$node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
|
||||
|
||||
/** @var \Drupal\file\FileInterface $node_file */
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
$this->assertFileExists($node_file, 'A file was saved to disk on node creation');
|
||||
$this->assertEqual($attacker_user->id(), $node_file->getOwnerId(), 'New file belongs to the attacker.');
|
||||
|
||||
// Ensure the file can be downloaded.
|
||||
$this->drupalGet(file_create_url($node_file->getFileUri()));
|
||||
$this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
|
||||
|
||||
// "Click" the remove button (emulating either a nojs or js submission).
|
||||
// In this POST request, the attacker "guesses" the fid of the victim's
|
||||
// temporary file and uses that to remove this file.
|
||||
$this->drupalGet($node->toUrl('edit-form'));
|
||||
switch ($type) {
|
||||
case 'nojs':
|
||||
$this->drupalPostForm(NULL, [$field_name . '[0][fids]' => (string) $victim_tmp_file->id()], 'Remove');
|
||||
break;
|
||||
|
||||
case 'js':
|
||||
$this->drupalPostAjaxForm(NULL, [$field_name . '[0][fids]' => (string) $victim_tmp_file->id()], ["{$field_name}_0_remove_button" => 'Remove']);
|
||||
break;
|
||||
}
|
||||
|
||||
// The victim's temporary file should not be removed by the attacker's
|
||||
// POST request.
|
||||
$this->assertFileExists($victim_tmp_file);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
222
web/core/modules/file/src/Tests/FileListingTest.php
Normal file
222
web/core/modules/file/src/Tests/FileListingTest.php
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\node\Entity\Node;
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\entity_test\Entity\EntityTestConstraints;
|
||||
|
||||
/**
|
||||
* Tests file listing page functionality.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FileListingTest extends FileFieldTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('views', 'file', 'image', 'entity_test');
|
||||
|
||||
/**
|
||||
* An authenticated user.
|
||||
*
|
||||
* @var \Drupal\user\UserInterface
|
||||
*/
|
||||
protected $baseUser;
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->adminUser = $this->drupalCreateUser(array('access files overview', 'bypass node access'));
|
||||
$this->baseUser = $this->drupalCreateUser();
|
||||
$this->createFileField('file', 'node', 'article', array(), array('file_extensions' => 'txt png'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates total count of usages for a file.
|
||||
*
|
||||
* @param $usage array
|
||||
* Array of file usage information as returned from file_usage subsystem.
|
||||
* @return int
|
||||
* Total usage count.
|
||||
*/
|
||||
protected function sumUsages($usage) {
|
||||
$count = 0;
|
||||
foreach ($usage as $module) {
|
||||
foreach ($module as $entity_type) {
|
||||
foreach ($entity_type as $entity) {
|
||||
$count += $entity;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests file overview with different user permissions.
|
||||
*/
|
||||
function testFileListingPages() {
|
||||
$file_usage = $this->container->get('file.usage');
|
||||
// Users without sufficient permissions should not see file listing.
|
||||
$this->drupalLogin($this->baseUser);
|
||||
$this->drupalGet('admin/content/files');
|
||||
$this->assertResponse(403);
|
||||
|
||||
// Log in with user with right permissions and test listing.
|
||||
$this->drupalLogin($this->adminUser);
|
||||
|
||||
for ($i = 0; $i < 5; $i++) {
|
||||
$nodes[] = $this->drupalCreateNode(array('type' => 'article'));
|
||||
}
|
||||
|
||||
$this->drupalGet('admin/content/files');
|
||||
$this->assertResponse(200);
|
||||
$this->assertText('No files available.');
|
||||
$this->drupalGet('admin/content/files');
|
||||
$this->assertResponse(200);
|
||||
|
||||
// Create a file with no usage.
|
||||
$file = $this->createFile();
|
||||
|
||||
$this->drupalGet('admin/content/files/usage/' . $file->id());
|
||||
$this->assertResponse(200);
|
||||
$this->assertTitle(t('File usage information for @file | Drupal', array('@file' => $file->getFilename())));
|
||||
|
||||
foreach ($nodes as &$node) {
|
||||
$this->drupalGet('node/' . $node->id() . '/edit');
|
||||
$file = $this->getTestFile('image');
|
||||
|
||||
$edit = array(
|
||||
'files[file_0]' => drupal_realpath($file->getFileUri()),
|
||||
);
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
$node = Node::load($node->id());
|
||||
}
|
||||
|
||||
$this->drupalGet('admin/content/files');
|
||||
|
||||
foreach ($nodes as $node) {
|
||||
$file = File::load($node->file->target_id);
|
||||
$this->assertText($file->getFilename());
|
||||
$this->assertLinkByHref(file_create_url($file->getFileUri()));
|
||||
$this->assertLinkByHref('admin/content/files/usage/' . $file->id());
|
||||
}
|
||||
$this->assertFalse(preg_match('/views-field-status priority-low\">\s*' . t('Temporary') . '/', $this->getRawContent()), 'All files are stored as permanent.');
|
||||
|
||||
// Use one file two times and check usage information.
|
||||
$orphaned_file = $nodes[1]->file->target_id;
|
||||
$used_file = $nodes[0]->file->target_id;
|
||||
$nodes[1]->file->target_id = $used_file;
|
||||
$nodes[1]->save();
|
||||
|
||||
$this->drupalGet('admin/content/files');
|
||||
$file = File::load($orphaned_file);
|
||||
$usage = $this->sumUsages($file_usage->listUsage($file));
|
||||
$this->assertRaw('admin/content/files/usage/' . $file->id() . '">' . $usage);
|
||||
|
||||
$file = File::load($used_file);
|
||||
$usage = $this->sumUsages($file_usage->listUsage($file));
|
||||
$this->assertRaw('admin/content/files/usage/' . $file->id() . '">' . $usage);
|
||||
|
||||
$result = $this->xpath("//td[contains(@class, 'views-field-status') and contains(text(), :value)]", array(':value' => t('Temporary')));
|
||||
$this->assertEqual(1, count($result), 'Unused file marked as temporary.');
|
||||
|
||||
// Test file usage page.
|
||||
foreach ($nodes as $node) {
|
||||
$file = File::load($node->file->target_id);
|
||||
$usage = $file_usage->listUsage($file);
|
||||
$this->drupalGet('admin/content/files/usage/' . $file->id());
|
||||
$this->assertResponse(200);
|
||||
$this->assertText($node->getTitle(), 'Node title found on usage page.');
|
||||
$this->assertText('node', 'Registering entity type found on usage page.');
|
||||
$this->assertText('file', 'Registering module found on usage page.');
|
||||
foreach ($usage as $module) {
|
||||
foreach ($module as $entity_type) {
|
||||
foreach ($entity_type as $entity) {
|
||||
$this->assertText($entity, 'Usage count found on usage page.');
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->assertLinkByHref('node/' . $node->id(), 0, 'Link to registering entity found on usage page.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests file listing usage page for entities with no canonical link template.
|
||||
*/
|
||||
function testFileListingUsageNoLink() {
|
||||
// Login with user with right permissions and test listing.
|
||||
$this->drupalLogin($this->adminUser);
|
||||
|
||||
// Create a bundle and attach a File field to the bundle.
|
||||
$bundle = $this->randomMachineName();
|
||||
entity_test_create_bundle($bundle, NULL, 'entity_test_constraints');
|
||||
$this->createFileField('field_test_file', 'entity_test_constraints', $bundle, array(), array('file_extensions' => 'txt png'));
|
||||
|
||||
// Create file to attach to entity.
|
||||
$file = File::create([
|
||||
'filename' => 'druplicon.txt',
|
||||
'uri' => 'public://druplicon.txt',
|
||||
'filemime' => 'text/plain',
|
||||
]);
|
||||
$file->setPermanent();
|
||||
file_put_contents($file->getFileUri(), 'hello world');
|
||||
$file->save();
|
||||
|
||||
// Create entity and attach the created file.
|
||||
$entity_name = $this->randomMachineName();
|
||||
$entity = EntityTestConstraints::create(array(
|
||||
'uid' => 1,
|
||||
'name' => $entity_name,
|
||||
'type' => $bundle,
|
||||
'field_test_file' => array(
|
||||
'target_id' => $file->id(),
|
||||
),
|
||||
));
|
||||
$entity->save();
|
||||
|
||||
// Create node entity and attach the created file.
|
||||
$node = $this->drupalCreateNode(array('type' => 'article', 'file' => $file));
|
||||
$node->save();
|
||||
|
||||
// Load the file usage page for the created and attached file.
|
||||
$this->drupalGet('admin/content/files/usage/' . $file->id());
|
||||
|
||||
$this->assertResponse(200);
|
||||
// Entity name should be displayed, but not linked if Entity::toUrl
|
||||
// throws an exception
|
||||
$this->assertText($entity_name, 'Entity name is added to file usage listing.');
|
||||
$this->assertNoLink($entity_name, 'Linked entity name not added to file usage listing.');
|
||||
$this->assertLink($node->getTitle());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and saves a test file.
|
||||
*
|
||||
* @return \Drupal\Core\Entity\EntityInterface
|
||||
* A file entity.
|
||||
*/
|
||||
protected function createFile() {
|
||||
// Create a new file entity.
|
||||
$file = File::create([
|
||||
'uid' => 1,
|
||||
'filename' => 'druplicon.txt',
|
||||
'uri' => 'public://druplicon.txt',
|
||||
'filemime' => 'text/plain',
|
||||
'created' => 1,
|
||||
'changed' => 1,
|
||||
'status' => FILE_STATUS_PERMANENT,
|
||||
]);
|
||||
file_put_contents($file->getFileUri(), 'hello world');
|
||||
|
||||
// Save it, inserting a new record.
|
||||
$file->save();
|
||||
|
||||
return $file;
|
||||
}
|
||||
|
||||
}
|
||||
69
web/core/modules/file/src/Tests/FileManagedAccessTest.php
Normal file
69
web/core/modules/file/src/Tests/FileManagedAccessTest.php
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests access to managed files.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FileManagedAccessTest extends FileManagedTestBase {
|
||||
|
||||
/**
|
||||
* Tests if public file is always accessible.
|
||||
*/
|
||||
function testFileAccess() {
|
||||
// Create a new file entity.
|
||||
$file = File::create(array(
|
||||
'uid' => 1,
|
||||
'filename' => 'drupal.txt',
|
||||
'uri' => 'public://drupal.txt',
|
||||
'filemime' => 'text/plain',
|
||||
'status' => FILE_STATUS_PERMANENT,
|
||||
));
|
||||
file_put_contents($file->getFileUri(), 'hello world');
|
||||
|
||||
// Save it, inserting a new record.
|
||||
$file->save();
|
||||
|
||||
// Create authenticated user to check file access.
|
||||
$account = $this->createUser(array('access site reports'));
|
||||
|
||||
$this->assertTrue($file->access('view', $account), 'Public file is viewable to authenticated user');
|
||||
$this->assertTrue($file->access('download', $account), 'Public file is downloadable to authenticated user');
|
||||
|
||||
// Create anonymous user to check file access.
|
||||
$account = $this->createUser()->getAnonymousUser();
|
||||
|
||||
$this->assertTrue($file->access('view', $account), 'Public file is viewable to anonymous user');
|
||||
$this->assertTrue($file->access('download', $account), 'Public file is downloadable to anonymous user');
|
||||
|
||||
// Create a new file entity.
|
||||
$file = File::create(array(
|
||||
'uid' => 1,
|
||||
'filename' => 'drupal.txt',
|
||||
'uri' => 'private://drupal.txt',
|
||||
'filemime' => 'text/plain',
|
||||
'status' => FILE_STATUS_PERMANENT,
|
||||
));
|
||||
file_put_contents($file->getFileUri(), 'hello world');
|
||||
|
||||
// Save it, inserting a new record.
|
||||
$file->save();
|
||||
|
||||
// Create authenticated user to check file access.
|
||||
$account = $this->createUser(array('access site reports'));
|
||||
|
||||
$this->assertFalse($file->access('view', $account), 'Private file is not viewable to authenticated user');
|
||||
$this->assertFalse($file->access('download', $account), 'Private file is not downloadable to authenticated user');
|
||||
|
||||
// Create anonymous user to check file access.
|
||||
$account = $this->createUser()->getAnonymousUser();
|
||||
|
||||
$this->assertFalse($file->access('view', $account), 'Private file is not viewable to anonymous user');
|
||||
$this->assertFalse($file->access('download', $account), 'Private file is not downloadable to anonymous user');
|
||||
}
|
||||
|
||||
}
|
||||
197
web/core/modules/file/src/Tests/FileManagedFileElementTest.php
Normal file
197
web/core/modules/file/src/Tests/FileManagedFileElementTest.php
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
/**
|
||||
* Tests the 'managed_file' element type.
|
||||
*
|
||||
* @group file
|
||||
* @todo Create a FileTestBase class and move FileFieldTestBase methods
|
||||
* that aren't related to fields into it.
|
||||
*/
|
||||
class FileManagedFileElementTest extends FileFieldTestBase {
|
||||
/**
|
||||
* Tests the managed_file element type.
|
||||
*/
|
||||
function testManagedFile() {
|
||||
// Check that $element['#size'] is passed to the child upload element.
|
||||
$this->drupalGet('file/test');
|
||||
$this->assertFieldByXpath('//input[@name="files[nested_file]" and @size="13"]', NULL, 'The custom #size attribute is passed to the child upload element.');
|
||||
|
||||
// Perform the tests with all permutations of $form['#tree'],
|
||||
// $element['#extended'], and $element['#multiple'].
|
||||
$test_file = $this->getTestFile('text');
|
||||
foreach (array(0, 1) as $tree) {
|
||||
foreach (array(0, 1) as $extended) {
|
||||
foreach (array(0, 1) as $multiple) {
|
||||
$path = 'file/test/' . $tree . '/' . $extended . '/' . $multiple;
|
||||
$input_base_name = $tree ? 'nested_file' : 'file';
|
||||
$file_field_name = $multiple ? 'files[' . $input_base_name . '][]' : 'files[' . $input_base_name . ']';
|
||||
|
||||
// Submit without a file.
|
||||
$this->drupalPostForm($path, array(), t('Save'));
|
||||
$this->assertRaw(t('The file ids are %fids.', array('%fids' => implode(',', array()))), 'Submitted without a file.');
|
||||
|
||||
// Submit with a file, but with an invalid form token. Ensure the file
|
||||
// was not saved.
|
||||
$last_fid_prior = $this->getLastFileId();
|
||||
$edit = [
|
||||
$file_field_name => drupal_realpath($test_file->getFileUri()),
|
||||
'form_token' => 'invalid token',
|
||||
];
|
||||
$this->drupalPostForm($path, $edit, t('Save'));
|
||||
$this->assertText('The form has become outdated. Copy any unsaved work in the form below');
|
||||
$last_fid = $this->getLastFileId();
|
||||
$this->assertEqual($last_fid_prior, $last_fid, 'File was not saved when uploaded with an invalid form token.');
|
||||
|
||||
// Submit a new file, without using the Upload button.
|
||||
$last_fid_prior = $this->getLastFileId();
|
||||
$edit = array($file_field_name => drupal_realpath($test_file->getFileUri()));
|
||||
$this->drupalPostForm($path, $edit, t('Save'));
|
||||
$last_fid = $this->getLastFileId();
|
||||
$this->assertTrue($last_fid > $last_fid_prior, 'New file got saved.');
|
||||
$this->assertRaw(t('The file ids are %fids.', array('%fids' => implode(',', array($last_fid)))), 'Submit handler has correct file info.');
|
||||
|
||||
// Submit no new input, but with a default file.
|
||||
$this->drupalPostForm($path . '/' . $last_fid, array(), t('Save'));
|
||||
$this->assertRaw(t('The file ids are %fids.', array('%fids' => implode(',', array($last_fid)))), 'Empty submission did not change an existing file.');
|
||||
|
||||
// Now, test the Upload and Remove buttons, with and without Ajax.
|
||||
foreach (array(FALSE, TRUE) as $ajax) {
|
||||
// Upload, then Submit.
|
||||
$last_fid_prior = $this->getLastFileId();
|
||||
$this->drupalGet($path);
|
||||
$edit = array($file_field_name => drupal_realpath($test_file->getFileUri()));
|
||||
if ($ajax) {
|
||||
$this->drupalPostAjaxForm(NULL, $edit, $input_base_name . '_upload_button');
|
||||
}
|
||||
else {
|
||||
$this->drupalPostForm(NULL, $edit, t('Upload'));
|
||||
}
|
||||
$last_fid = $this->getLastFileId();
|
||||
$this->assertTrue($last_fid > $last_fid_prior, 'New file got uploaded.');
|
||||
$this->drupalPostForm(NULL, array(), t('Save'));
|
||||
$this->assertRaw(t('The file ids are %fids.', array('%fids' => implode(',', array($last_fid)))), 'Submit handler has correct file info.');
|
||||
|
||||
// Remove, then Submit.
|
||||
$remove_button_title = $multiple ? t('Remove selected') : t('Remove');
|
||||
$remove_edit = array();
|
||||
if ($multiple) {
|
||||
$selected_checkbox = ($tree ? 'nested[file]' : 'file') . '[file_' . $last_fid . '][selected]';
|
||||
$remove_edit = array($selected_checkbox => '1');
|
||||
}
|
||||
$this->drupalGet($path . '/' . $last_fid);
|
||||
if ($ajax) {
|
||||
$this->drupalPostAjaxForm(NULL, $remove_edit, $input_base_name . '_remove_button');
|
||||
}
|
||||
else {
|
||||
$this->drupalPostForm(NULL, $remove_edit, $remove_button_title);
|
||||
}
|
||||
$this->drupalPostForm(NULL, array(), t('Save'));
|
||||
$this->assertRaw(t('The file ids are %fids.', array('%fids' => '')), 'Submission after file removal was successful.');
|
||||
|
||||
// Upload, then Remove, then Submit.
|
||||
$this->drupalGet($path);
|
||||
$edit = array($file_field_name => drupal_realpath($test_file->getFileUri()));
|
||||
if ($ajax) {
|
||||
$this->drupalPostAjaxForm(NULL, $edit, $input_base_name . '_upload_button');
|
||||
}
|
||||
else {
|
||||
$this->drupalPostForm(NULL, $edit, t('Upload'));
|
||||
}
|
||||
$remove_edit = array();
|
||||
if ($multiple) {
|
||||
$selected_checkbox = ($tree ? 'nested[file]' : 'file') . '[file_' . $this->getLastFileId() . '][selected]';
|
||||
$remove_edit = array($selected_checkbox => '1');
|
||||
}
|
||||
if ($ajax) {
|
||||
$this->drupalPostAjaxForm(NULL, $remove_edit, $input_base_name . '_remove_button');
|
||||
}
|
||||
else {
|
||||
$this->drupalPostForm(NULL, $remove_edit, $remove_button_title);
|
||||
}
|
||||
|
||||
$this->drupalPostForm(NULL, array(), t('Save'));
|
||||
$this->assertRaw(t('The file ids are %fids.', array('%fids' => '')), 'Submission after file upload and removal was successful.');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The multiple file upload has additional conditions that need checking.
|
||||
$path = 'file/test/1/1/1';
|
||||
$edit = array('files[nested_file][]' => drupal_realpath($test_file->getFileUri()));
|
||||
$fid_list = array();
|
||||
|
||||
$this->drupalGet($path);
|
||||
|
||||
// Add a single file to the upload field.
|
||||
$this->drupalPostForm(NULL, $edit, t('Upload'));
|
||||
$fid_list[] = $this->getLastFileId();
|
||||
$this->assertFieldByXpath('//input[@name="nested[file][file_' . $fid_list[0] . '][selected]"]', NULL, 'First file successfully uploaded to multiple file element.');
|
||||
|
||||
// Add another file to the same upload field.
|
||||
$this->drupalPostForm(NULL, $edit, t('Upload'));
|
||||
$fid_list[] = $this->getLastFileId();
|
||||
$this->assertFieldByXpath('//input[@name="nested[file][file_' . $fid_list[1] . '][selected]"]', NULL, 'Second file successfully uploaded to multiple file element.');
|
||||
|
||||
// Save the entire form.
|
||||
$this->drupalPostForm(NULL, array(), t('Save'));
|
||||
$this->assertRaw(t('The file ids are %fids.', array('%fids' => implode(',', $fid_list))), 'Two files saved into a single multiple file element.');
|
||||
|
||||
// Delete only the first file.
|
||||
$edit = array(
|
||||
'nested[file][file_' . $fid_list[0] . '][selected]' => '1',
|
||||
);
|
||||
$this->drupalPostForm($path . '/' . implode(',', $fid_list), $edit, t('Remove selected'));
|
||||
|
||||
// Check that the first file has been deleted but not the second.
|
||||
$this->assertNoFieldByXpath('//input[@name="nested[file][file_' . $fid_list[0] . '][selected]"]', NULL, 'An individual file can be deleted from a multiple file element.');
|
||||
$this->assertFieldByXpath('//input[@name="nested[file][file_' . $fid_list[1] . '][selected]"]', NULL, 'Second individual file not deleted when the first file is deleted from a multiple file element.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure that warning is shown if file on the field has been removed.
|
||||
*/
|
||||
public function testManagedFileRemoved() {
|
||||
$this->drupalGet('file/test/1/0/1');
|
||||
$test_file = $this->getTestFile('text');
|
||||
$file_field_name = 'files[nested_file][]';
|
||||
|
||||
$edit = [$file_field_name => drupal_realpath($test_file->getFileUri())];
|
||||
$this->drupalPostForm(NULL, $edit, t('Upload'));
|
||||
|
||||
$fid = $this->getLastFileId();
|
||||
$file = \Drupal::entityManager()->getStorage('file')->load($fid);
|
||||
$file->delete();
|
||||
|
||||
$this->drupalPostForm(NULL, $edit, t('Upload'));
|
||||
// We expect the title 'Managed <em>file & butter</em>' which got escaped
|
||||
// via a t() call before.
|
||||
$this->assertRaw('The file referenced by the Managed <em>file & butter</em> field does not exist.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a file entity can be saved when the file does not exist on disk.
|
||||
*/
|
||||
public function testFileRemovedFromDisk() {
|
||||
$this->drupalGet('file/test/1/0/1');
|
||||
$test_file = $this->getTestFile('text');
|
||||
$file_field_name = 'files[nested_file][]';
|
||||
|
||||
$edit = [$file_field_name => drupal_realpath($test_file->getFileUri())];
|
||||
$this->drupalPostForm(NULL, $edit, t('Upload'));
|
||||
$this->drupalPostForm(NULL, array(), t('Save'));
|
||||
|
||||
$fid = $this->getLastFileId();
|
||||
/** @var $file \Drupal\file\FileInterface */
|
||||
$file = $this->container->get('entity_type.manager')->getStorage('file')->load($fid);
|
||||
$file->setPermanent();
|
||||
$file->save();
|
||||
$this->assertTrue(file_unmanaged_delete($file->getFileUri()));
|
||||
$file->save();
|
||||
$this->assertTrue($file->isPermanent());
|
||||
$file->delete();
|
||||
}
|
||||
|
||||
}
|
||||
200
web/core/modules/file/src/Tests/FileManagedTestBase.php
Normal file
200
web/core/modules/file/src/Tests/FileManagedTestBase.php
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\file\FileInterface;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Base class for file tests that use the file_test module to test uploads and
|
||||
* hooks.
|
||||
*/
|
||||
abstract class FileManagedTestBase extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('file_test', 'file');
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
// Clear out any hook calls.
|
||||
file_test_reset();
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that all of the specified hook_file_* hooks were called once, other
|
||||
* values result in failure.
|
||||
*
|
||||
* @param string[] $expected
|
||||
* An array of strings containing with the hook name; for example, 'load',
|
||||
* 'save', 'insert', etc.
|
||||
*/
|
||||
function assertFileHooksCalled($expected) {
|
||||
\Drupal::state()->resetCache();
|
||||
|
||||
// Determine which hooks were called.
|
||||
$actual = array_keys(array_filter(file_test_get_all_calls()));
|
||||
|
||||
// Determine if there were any expected that were not called.
|
||||
$uncalled = array_diff($expected, $actual);
|
||||
if (count($uncalled)) {
|
||||
$this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled))));
|
||||
}
|
||||
else {
|
||||
$this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', array('%expected' => empty($expected) ? '(none)' : implode(', ', $expected))));
|
||||
}
|
||||
|
||||
// Determine if there were any unexpected calls.
|
||||
$unexpected = array_diff($actual, $expected);
|
||||
if (count($unexpected)) {
|
||||
$this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', array('%unexpected' => empty($unexpected) ? '(none)' : implode(', ', $unexpected))));
|
||||
}
|
||||
else {
|
||||
$this->assertTrue(TRUE, 'No unexpected hooks were called.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that a hook_file_* hook was called a certain number of times.
|
||||
*
|
||||
* @param string $hook
|
||||
* String with the hook name; for instance, 'load', 'save', 'insert', etc.
|
||||
* @param int $expected_count
|
||||
* Optional integer count.
|
||||
* @param string|null $message
|
||||
* Optional translated string message.
|
||||
*/
|
||||
function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
|
||||
$actual_count = count(file_test_get_calls($hook));
|
||||
|
||||
if (!isset($message)) {
|
||||
if ($actual_count == $expected_count) {
|
||||
$message = format_string('hook_file_@name was called correctly.', array('@name' => $hook));
|
||||
}
|
||||
elseif ($expected_count == 0) {
|
||||
$message = \Drupal::translation()->formatPlural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', array('@name' => $hook, '@count' => $actual_count));
|
||||
}
|
||||
else {
|
||||
$message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', array('@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count));
|
||||
}
|
||||
}
|
||||
$this->assertEqual($actual_count, $expected_count, $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that two files have the same values (except timestamp).
|
||||
*
|
||||
* @param \Drupal\file\FileInterface $before
|
||||
* File object to compare.
|
||||
* @param \Drupal\file\FileInterface $after
|
||||
* File object to compare.
|
||||
*/
|
||||
function assertFileUnchanged(FileInterface $before, FileInterface $after) {
|
||||
$this->assertEqual($before->id(), $after->id(), t('File id is the same: %file1 == %file2.', array('%file1' => $before->id(), '%file2' => $after->id())), 'File unchanged');
|
||||
$this->assertEqual($before->getOwner()->id(), $after->getOwner()->id(), t('File owner is the same: %file1 == %file2.', array('%file1' => $before->getOwner()->id(), '%file2' => $after->getOwner()->id())), 'File unchanged');
|
||||
$this->assertEqual($before->getFilename(), $after->getFilename(), t('File name is the same: %file1 == %file2.', array('%file1' => $before->getFilename(), '%file2' => $after->getFilename())), 'File unchanged');
|
||||
$this->assertEqual($before->getFileUri(), $after->getFileUri(), t('File path is the same: %file1 == %file2.', array('%file1' => $before->getFileUri(), '%file2' => $after->getFileUri())), 'File unchanged');
|
||||
$this->assertEqual($before->getMimeType(), $after->getMimeType(), t('File MIME type is the same: %file1 == %file2.', array('%file1' => $before->getMimeType(), '%file2' => $after->getMimeType())), 'File unchanged');
|
||||
$this->assertEqual($before->getSize(), $after->getSize(), t('File size is the same: %file1 == %file2.', array('%file1' => $before->getSize(), '%file2' => $after->getSize())), 'File unchanged');
|
||||
$this->assertEqual($before->isPermanent(), $after->isPermanent(), t('File status is the same: %file1 == %file2.', array('%file1' => $before->isPermanent(), '%file2' => $after->isPermanent())), 'File unchanged');
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that two files are not the same by comparing the fid and filepath.
|
||||
*
|
||||
* @param \Drupal\file\FileInterface $file1
|
||||
* File object to compare.
|
||||
* @param \Drupal\file\FileInterface $file2
|
||||
* File object to compare.
|
||||
*/
|
||||
function assertDifferentFile(FileInterface $file1, FileInterface $file2) {
|
||||
$this->assertNotEqual($file1->id(), $file2->id(), t('Files have different ids: %file1 != %file2.', array('%file1' => $file1->id(), '%file2' => $file2->id())), 'Different file');
|
||||
$this->assertNotEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have different paths: %file1 != %file2.', array('%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri())), 'Different file');
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that two files are the same by comparing the fid and filepath.
|
||||
*
|
||||
* @param \Drupal\file\FileInterface $file1
|
||||
* File object to compare.
|
||||
* @param \Drupal\file\FileInterface $file2
|
||||
* File object to compare.
|
||||
*/
|
||||
function assertSameFile(FileInterface $file1, FileInterface $file2) {
|
||||
$this->assertEqual($file1->id(), $file2->id(), t('Files have the same ids: %file1 == %file2.', array('%file1' => $file1->id(), '%file2-fid' => $file2->id())), 'Same file');
|
||||
$this->assertEqual($file1->getFileUri(), $file2->getFileUri(), t('Files have the same path: %file1 == %file2.', array('%file1' => $file1->getFileUri(), '%file2' => $file2->getFileUri())), 'Same file');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a file and save it to the files table and assert that it occurs
|
||||
* correctly.
|
||||
*
|
||||
* @param string $filepath
|
||||
* Optional string specifying the file path. If none is provided then a
|
||||
* randomly named file will be created in the site's files directory.
|
||||
* @param string $contents
|
||||
* Optional contents to save into the file. If a NULL value is provided an
|
||||
* arbitrary string will be used.
|
||||
* @param string $scheme
|
||||
* Optional string indicating the stream scheme to use. Drupal core includes
|
||||
* public, private, and temporary. The public wrapper is the default.
|
||||
* @return \Drupal\file\FileInterface
|
||||
* File entity.
|
||||
*/
|
||||
function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
|
||||
// Don't count hook invocations caused by creating the file.
|
||||
\Drupal::state()->set('file_test.count_hook_invocations', FALSE);
|
||||
$file = File::create([
|
||||
'uri' => $this->createUri($filepath, $contents, $scheme),
|
||||
'uid' => 1,
|
||||
]);
|
||||
$file->save();
|
||||
// Write the record directly rather than using the API so we don't invoke
|
||||
// the hooks.
|
||||
$this->assertTrue($file->id() > 0, 'The file was added to the database.', 'Create test file');
|
||||
|
||||
\Drupal::state()->set('file_test.count_hook_invocations', TRUE);
|
||||
return $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a file and returns its URI.
|
||||
*
|
||||
* @param string $filepath
|
||||
* Optional string specifying the file path. If none is provided then a
|
||||
* randomly named file will be created in the site's files directory.
|
||||
* @param string $contents
|
||||
* Optional contents to save into the file. If a NULL value is provided an
|
||||
* arbitrary string will be used.
|
||||
* @param string $scheme
|
||||
* Optional string indicating the stream scheme to use. Drupal core includes
|
||||
* public, private, and temporary. The public wrapper is the default.
|
||||
*
|
||||
* @return string
|
||||
* File URI.
|
||||
*/
|
||||
function createUri($filepath = NULL, $contents = NULL, $scheme = NULL) {
|
||||
if (!isset($filepath)) {
|
||||
// Prefix with non-latin characters to ensure that all file-related
|
||||
// tests work with international filenames.
|
||||
$filepath = 'Файл для тестирования ' . $this->randomMachineName();
|
||||
}
|
||||
if (!isset($scheme)) {
|
||||
$scheme = file_default_scheme();
|
||||
}
|
||||
$filepath = $scheme . '://' . $filepath;
|
||||
|
||||
if (!isset($contents)) {
|
||||
$contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
|
||||
}
|
||||
|
||||
file_put_contents($filepath, $contents);
|
||||
$this->assertTrue(is_file($filepath), t('The test file exists on the disk.'), 'Create test file');
|
||||
return $filepath;
|
||||
}
|
||||
|
||||
}
|
||||
200
web/core/modules/file/src/Tests/FileOnTranslatedEntityTest.php
Normal file
200
web/core/modules/file/src/Tests/FileOnTranslatedEntityTest.php
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Uploads files to translated nodes.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FileOnTranslatedEntityTest extends FileFieldTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = array('language', 'content_translation');
|
||||
|
||||
/**
|
||||
* The name of the file field used in the test.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $fieldName;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Create the "Basic page" node type.
|
||||
// @todo Remove the disabling of new revision creation in
|
||||
// https://www.drupal.org/node/1239558.
|
||||
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page', 'new_revision' => FALSE]);
|
||||
|
||||
// Create a file field on the "Basic page" node type.
|
||||
$this->fieldName = strtolower($this->randomMachineName());
|
||||
$this->createFileField($this->fieldName, 'node', 'page');
|
||||
|
||||
// Create and log in user.
|
||||
$permissions = array(
|
||||
'access administration pages',
|
||||
'administer content translation',
|
||||
'administer content types',
|
||||
'administer languages',
|
||||
'create content translations',
|
||||
'create page content',
|
||||
'edit any page content',
|
||||
'translate any entity',
|
||||
'delete any page content',
|
||||
);
|
||||
$admin_user = $this->drupalCreateUser($permissions);
|
||||
$this->drupalLogin($admin_user);
|
||||
|
||||
// Add a second and third language.
|
||||
$edit = array();
|
||||
$edit['predefined_langcode'] = 'fr';
|
||||
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
|
||||
|
||||
$edit = array();
|
||||
$edit['predefined_langcode'] = 'nl';
|
||||
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
|
||||
|
||||
// Enable translation for "Basic page" nodes.
|
||||
$edit = array(
|
||||
'entity_types[node]' => 1,
|
||||
'settings[node][page][translatable]' => 1,
|
||||
"settings[node][page][fields][$this->fieldName]" => 1,
|
||||
);
|
||||
$this->drupalPostForm('admin/config/regional/content-language', $edit, t('Save configuration'));
|
||||
\Drupal::entityManager()->clearCachedDefinitions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests synced file fields on translated nodes.
|
||||
*/
|
||||
public function testSyncedFiles() {
|
||||
// Verify that the file field on the "Basic page" node type is translatable.
|
||||
$definitions = \Drupal::entityManager()->getFieldDefinitions('node', 'page');
|
||||
$this->assertTrue($definitions[$this->fieldName]->isTranslatable(), 'Node file field is translatable.');
|
||||
|
||||
// Create a default language node.
|
||||
$default_language_node = $this->drupalCreateNode(array('type' => 'page', 'title' => 'Lost in translation'));
|
||||
|
||||
// Edit the node to upload a file.
|
||||
$edit = array();
|
||||
$name = 'files[' . $this->fieldName . '_0]';
|
||||
$edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[0]->uri);
|
||||
$this->drupalPostForm('node/' . $default_language_node->id() . '/edit', $edit, t('Save'));
|
||||
$first_fid = $this->getLastFileId();
|
||||
|
||||
// Translate the node into French: remove the existing file.
|
||||
$this->drupalPostForm('node/' . $default_language_node->id() . '/translations/add/en/fr', array(), t('Remove'));
|
||||
|
||||
// Upload a different file.
|
||||
$edit = array();
|
||||
$edit['title[0][value]'] = 'Bill Murray';
|
||||
$name = 'files[' . $this->fieldName . '_0]';
|
||||
$edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[1]->uri);
|
||||
$this->drupalPostForm(NULL, $edit, t('Save (this translation)'));
|
||||
// This inspects the HTML after the post of the translation, the file
|
||||
// should be displayed on the original node.
|
||||
$this->assertRaw('file--mime-text-plain');
|
||||
$second_fid = $this->getLastFileId();
|
||||
|
||||
\Drupal::entityTypeManager()->getStorage('file')->resetCache();
|
||||
|
||||
/* @var $file \Drupal\file\FileInterface */
|
||||
|
||||
// Ensure the file status of the first file permanent.
|
||||
$file = File::load($first_fid);
|
||||
$this->assertTrue($file->isPermanent());
|
||||
|
||||
// Ensure the file status of the second file is permanent.
|
||||
$file = File::load($second_fid);
|
||||
$this->assertTrue($file->isPermanent());
|
||||
|
||||
// Translate the node into dutch: remove the existing file.
|
||||
$this->drupalPostForm('node/' . $default_language_node->id() . '/translations/add/en/nl', array(), t('Remove'));
|
||||
|
||||
// Upload a different file.
|
||||
$edit = array();
|
||||
$edit['title[0][value]'] = 'Scarlett Johansson';
|
||||
$name = 'files[' . $this->fieldName . '_0]';
|
||||
$edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[2]->uri);
|
||||
$this->drupalPostForm(NULL, $edit, t('Save (this translation)'));
|
||||
$third_fid = $this->getLastFileId();
|
||||
|
||||
\Drupal::entityTypeManager()->getStorage('file')->resetCache();
|
||||
|
||||
// Ensure the first file is untouched.
|
||||
$file = File::load($first_fid);
|
||||
$this->assertTrue($file->isPermanent(), 'First file still exists and is permanent.');
|
||||
// This inspects the HTML after the post of the translation, the file
|
||||
// should be displayed on the original node.
|
||||
$this->assertRaw('file--mime-text-plain');
|
||||
|
||||
// Ensure the file status of the second file is permanent.
|
||||
$file = File::load($second_fid);
|
||||
$this->assertTrue($file->isPermanent());
|
||||
|
||||
// Ensure the file status of the third file is permanent.
|
||||
$file = File::load($third_fid);
|
||||
$this->assertTrue($file->isPermanent());
|
||||
|
||||
// Edit the second translation: remove the existing file.
|
||||
$this->drupalPostForm('fr/node/' . $default_language_node->id() . '/edit', array(), t('Remove'));
|
||||
|
||||
// Upload a different file.
|
||||
$edit = array();
|
||||
$edit['title[0][value]'] = 'David Bowie';
|
||||
$name = 'files[' . $this->fieldName . '_0]';
|
||||
$edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[3]->uri);
|
||||
$this->drupalPostForm(NULL, $edit, t('Save (this translation)'));
|
||||
$replaced_second_fid = $this->getLastFileId();
|
||||
|
||||
\Drupal::entityTypeManager()->getStorage('file')->resetCache();
|
||||
|
||||
// Ensure the first and third files are untouched.
|
||||
$file = File::load($first_fid);
|
||||
$this->assertTrue($file->isPermanent(), 'First file still exists and is permanent.');
|
||||
|
||||
$file = File::load($third_fid);
|
||||
$this->assertTrue($file->isPermanent());
|
||||
|
||||
// Ensure the file status of the replaced second file is permanent.
|
||||
$file = File::load($replaced_second_fid);
|
||||
$this->assertTrue($file->isPermanent());
|
||||
|
||||
// Delete the third translation.
|
||||
$this->drupalPostForm('nl/node/' . $default_language_node->id() . '/delete', array(), t('Delete Dutch translation'));
|
||||
|
||||
\Drupal::entityTypeManager()->getStorage('file')->resetCache();
|
||||
|
||||
// Ensure the first and replaced second files are untouched.
|
||||
$file = File::load($first_fid);
|
||||
$this->assertTrue($file->isPermanent(), 'First file still exists and is permanent.');
|
||||
|
||||
$file = File::load($replaced_second_fid);
|
||||
$this->assertTrue($file->isPermanent());
|
||||
|
||||
// Ensure the file status of the third file is now temporary.
|
||||
$file = File::load($third_fid);
|
||||
$this->assertTrue($file->isTemporary());
|
||||
|
||||
// Delete the all translations.
|
||||
$this->drupalPostForm('node/' . $default_language_node->id() . '/delete', array(), t('Delete all translations'));
|
||||
|
||||
\Drupal::entityTypeManager()->getStorage('file')->resetCache();
|
||||
|
||||
// Ensure the file status of the all files are now temporary.
|
||||
$file = File::load($first_fid);
|
||||
$this->assertTrue($file->isTemporary(), 'First file still exists and is temporary.');
|
||||
|
||||
$file = File::load($replaced_second_fid);
|
||||
$this->assertTrue($file->isTemporary());
|
||||
}
|
||||
|
||||
}
|
||||
115
web/core/modules/file/src/Tests/FilePrivateTest.php
Normal file
115
web/core/modules/file/src/Tests/FilePrivateTest.php
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\Core\Entity\Plugin\Validation\Constraint\ReferenceAccessConstraint;
|
||||
use Drupal\Component\Utility\SafeMarkup;
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\node\Entity\NodeType;
|
||||
|
||||
/**
|
||||
* Uploads a test to a private node and checks access.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FilePrivateTest extends FileFieldTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('node_access_test', 'field_test');
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
node_access_test_add_field(NodeType::load('article'));
|
||||
node_access_rebuild();
|
||||
\Drupal::state()->set('node_access_test.private', TRUE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests file access for file uploaded to a private node.
|
||||
*/
|
||||
function testPrivateFile() {
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
$type_name = 'article';
|
||||
$field_name = strtolower($this->randomMachineName());
|
||||
$this->createFileField($field_name, 'node', $type_name, array('uri_scheme' => 'private'));
|
||||
|
||||
$test_file = $this->getTestFile('text');
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE));
|
||||
\Drupal::entityManager()->getStorage('node')->resetCache(array($nid));
|
||||
/* @var \Drupal\node\NodeInterface $node */
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$field_name}->target_id);
|
||||
// Ensure the file can be viewed.
|
||||
$this->drupalGet('node/' . $node->id());
|
||||
$this->assertRaw($node_file->getFilename(), 'File reference is displayed after attaching it');
|
||||
// Ensure the file can be downloaded.
|
||||
$this->drupalGet(file_create_url($node_file->getFileUri()));
|
||||
$this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
|
||||
$this->drupalLogOut();
|
||||
$this->drupalGet(file_create_url($node_file->getFileUri()));
|
||||
$this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
|
||||
|
||||
// Create a field with no view access. See
|
||||
// field_test_entity_field_access().
|
||||
$no_access_field_name = 'field_no_view_access';
|
||||
$this->createFileField($no_access_field_name, 'node', $type_name, array('uri_scheme' => 'private'));
|
||||
// Test with the field that should deny access through field access.
|
||||
$this->drupalLogin($this->adminUser);
|
||||
$nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE));
|
||||
\Drupal::entityManager()->getStorage('node')->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$node_file = File::load($node->{$no_access_field_name}->target_id);
|
||||
|
||||
// Ensure the file cannot be downloaded.
|
||||
$file_url = file_create_url($node_file->getFileUri());
|
||||
$this->drupalGet($file_url);
|
||||
$this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.');
|
||||
|
||||
// Attempt to reuse the file when editing a node.
|
||||
$edit = array();
|
||||
$edit['title[0][value]'] = $this->randomMachineName();
|
||||
$this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish'));
|
||||
$new_node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
|
||||
$edit[$field_name . '[0][fids]'] = $node_file->id();
|
||||
$this->drupalPostForm('node/' . $new_node->id() . '/edit', $edit, t('Save and keep published'));
|
||||
// Make sure the form submit failed - we stayed on the edit form.
|
||||
$this->assertUrl('node/' . $new_node->id() . '/edit');
|
||||
// Check that we got the expected constraint form error.
|
||||
$constraint = new ReferenceAccessConstraint();
|
||||
$this->assertRaw(SafeMarkup::format($constraint->message, array('%type' => 'file', '%id' => $node_file->id())));
|
||||
// Attempt to reuse the existing file when creating a new node, and confirm
|
||||
// that access is still denied.
|
||||
$edit = array();
|
||||
$edit['title[0][value]'] = $this->randomMachineName();
|
||||
$edit[$field_name . '[0][fids]'] = $node_file->id();
|
||||
$this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish'));
|
||||
$new_node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
|
||||
$this->assertTrue(empty($new_node), 'Node was not created.');
|
||||
$this->assertUrl('node/add/' . $type_name);
|
||||
$this->assertRaw(SafeMarkup::format($constraint->message, array('%type' => 'file', '%id' => $node_file->id())));
|
||||
|
||||
// Now make file_test_file_download() return everything.
|
||||
\Drupal::state()->set('file_test.allow_all', TRUE);
|
||||
// Delete the node.
|
||||
$node->delete();
|
||||
// Ensure the file can still be downloaded by the owner.
|
||||
$this->drupalGet($file_url);
|
||||
$this->assertResponse(200, 'Confirmed that the owner still has access to the temporary file.');
|
||||
|
||||
// Ensure the file cannot be downloaded by an anonymous user.
|
||||
$this->drupalLogout();
|
||||
$this->drupalGet($file_url);
|
||||
$this->assertResponse(403, 'Confirmed that access is denied for an anonymous user to the temporary file.');
|
||||
|
||||
// Ensure the file cannot be downloaded by another user.
|
||||
$account = $this->drupalCreateUser();
|
||||
$this->drupalLogin($account);
|
||||
$this->drupalGet($file_url);
|
||||
$this->assertResponse(403, 'Confirmed that access is denied for another user to the temporary file.');
|
||||
}
|
||||
|
||||
}
|
||||
97
web/core/modules/file/src/Tests/FileTokenReplaceTest.php
Normal file
97
web/core/modules/file/src/Tests/FileTokenReplaceTest.php
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Core\Render\BubbleableMetadata;
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Generates text using placeholders for dummy content to check file token
|
||||
* replacement.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class FileTokenReplaceTest extends FileFieldTestBase {
|
||||
/**
|
||||
* Creates a file, then tests the tokens generated from it.
|
||||
*/
|
||||
function testFileTokenReplacement() {
|
||||
$node_storage = $this->container->get('entity.manager')->getStorage('node');
|
||||
$token_service = \Drupal::token();
|
||||
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
|
||||
|
||||
// Create file field.
|
||||
$type_name = 'article';
|
||||
$field_name = 'field_' . strtolower($this->randomMachineName());
|
||||
$this->createFileField($field_name, 'node', $type_name);
|
||||
|
||||
$test_file = $this->getTestFile('text');
|
||||
// Coping a file to test uploads with non-latin filenames.
|
||||
$filename = drupal_dirname($test_file->getFileUri()) . '/текстовый файл.txt';
|
||||
$test_file = file_copy($test_file, $filename);
|
||||
|
||||
// Create a new node with the uploaded file.
|
||||
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
|
||||
|
||||
// Load the node and the file.
|
||||
$node_storage->resetCache(array($nid));
|
||||
$node = $node_storage->load($nid);
|
||||
$file = File::load($node->{$field_name}->target_id);
|
||||
|
||||
// Generate and test sanitized tokens.
|
||||
$tests = array();
|
||||
$tests['[file:fid]'] = $file->id();
|
||||
$tests['[file:name]'] = Html::escape($file->getFilename());
|
||||
$tests['[file:path]'] = Html::escape($file->getFileUri());
|
||||
$tests['[file:mime]'] = Html::escape($file->getMimeType());
|
||||
$tests['[file:size]'] = format_size($file->getSize());
|
||||
$tests['[file:url]'] = Html::escape(file_create_url($file->getFileUri()));
|
||||
$tests['[file:created]'] = format_date($file->getCreatedTime(), 'medium', '', NULL, $language_interface->getId());
|
||||
$tests['[file:created:short]'] = format_date($file->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
|
||||
$tests['[file:changed]'] = format_date($file->getChangedTime(), 'medium', '', NULL, $language_interface->getId());
|
||||
$tests['[file:changed:short]'] = format_date($file->getChangedTime(), 'short', '', NULL, $language_interface->getId());
|
||||
$tests['[file:owner]'] = Html::escape($this->adminUser->getDisplayName());
|
||||
$tests['[file:owner:uid]'] = $file->getOwnerId();
|
||||
|
||||
$base_bubbleable_metadata = BubbleableMetadata::createFromObject($file);
|
||||
$metadata_tests = [];
|
||||
$metadata_tests['[file:fid]'] = $base_bubbleable_metadata;
|
||||
$metadata_tests['[file:name]'] = $base_bubbleable_metadata;
|
||||
$metadata_tests['[file:path]'] = $base_bubbleable_metadata;
|
||||
$metadata_tests['[file:mime]'] = $base_bubbleable_metadata;
|
||||
$metadata_tests['[file:size]'] = $base_bubbleable_metadata;
|
||||
$bubbleable_metadata = clone $base_bubbleable_metadata;
|
||||
$metadata_tests['[file:url]'] = $bubbleable_metadata->addCacheContexts(['url.site']);
|
||||
$bubbleable_metadata = clone $base_bubbleable_metadata;
|
||||
$metadata_tests['[file:created]'] = $bubbleable_metadata->addCacheTags(['rendered']);
|
||||
$metadata_tests['[file:created:short]'] = $bubbleable_metadata;
|
||||
$metadata_tests['[file:changed]'] = $bubbleable_metadata;
|
||||
$metadata_tests['[file:changed:short]'] = $bubbleable_metadata;
|
||||
$bubbleable_metadata = clone $base_bubbleable_metadata;
|
||||
$metadata_tests['[file:owner]'] = $bubbleable_metadata->addCacheTags(['user:2']);
|
||||
$metadata_tests['[file:owner:uid]'] = $bubbleable_metadata;
|
||||
|
||||
// Test to make sure that we generated something for each token.
|
||||
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
|
||||
|
||||
foreach ($tests as $input => $expected) {
|
||||
$bubbleable_metadata = new BubbleableMetadata();
|
||||
$output = $token_service->replace($input, array('file' => $file), array('langcode' => $language_interface->getId()), $bubbleable_metadata);
|
||||
$this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', array('%token' => $input)));
|
||||
$this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
|
||||
}
|
||||
|
||||
// Generate and test unsanitized tokens.
|
||||
$tests['[file:name]'] = $file->getFilename();
|
||||
$tests['[file:path]'] = $file->getFileUri();
|
||||
$tests['[file:mime]'] = $file->getMimeType();
|
||||
$tests['[file:size]'] = format_size($file->getSize());
|
||||
|
||||
foreach ($tests as $input => $expected) {
|
||||
$output = $token_service->replace($input, array('file' => $file), array('langcode' => $language_interface->getId(), 'sanitize' => FALSE));
|
||||
$this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input)));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,125 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\node\Entity\Node;
|
||||
|
||||
/**
|
||||
* Uploads private files to translated node and checks access.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class PrivateFileOnTranslatedEntityTest extends FileFieldTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = array('language', 'content_translation');
|
||||
|
||||
/**
|
||||
* The name of the file field used in the test.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $fieldName;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Create the "Basic page" node type.
|
||||
$this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
|
||||
|
||||
// Create a file field on the "Basic page" node type.
|
||||
$this->fieldName = strtolower($this->randomMachineName());
|
||||
$this->createFileField($this->fieldName, 'node', 'page', array('uri_scheme' => 'private'));
|
||||
|
||||
// Create and log in user.
|
||||
$permissions = array(
|
||||
'access administration pages',
|
||||
'administer content translation',
|
||||
'administer content types',
|
||||
'administer languages',
|
||||
'create content translations',
|
||||
'create page content',
|
||||
'edit any page content',
|
||||
'translate any entity',
|
||||
);
|
||||
$admin_user = $this->drupalCreateUser($permissions);
|
||||
$this->drupalLogin($admin_user);
|
||||
|
||||
// Add a second language.
|
||||
$edit = array();
|
||||
$edit['predefined_langcode'] = 'fr';
|
||||
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
|
||||
|
||||
// Enable translation for "Basic page" nodes.
|
||||
$edit = array(
|
||||
'entity_types[node]' => 1,
|
||||
'settings[node][page][translatable]' => 1,
|
||||
"settings[node][page][fields][$this->fieldName]" => 1,
|
||||
);
|
||||
$this->drupalPostForm('admin/config/regional/content-language', $edit, t('Save configuration'));
|
||||
\Drupal::entityManager()->clearCachedDefinitions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests private file fields on translated nodes.
|
||||
*/
|
||||
public function testPrivateLanguageFile() {
|
||||
// Verify that the file field on the "Basic page" node type is translatable.
|
||||
$definitions = \Drupal::entityManager()->getFieldDefinitions('node', 'page');
|
||||
$this->assertTrue($definitions[$this->fieldName]->isTranslatable(), 'Node file field is translatable.');
|
||||
|
||||
// Create a default language node.
|
||||
$default_language_node = $this->drupalCreateNode(array('type' => 'page'));
|
||||
|
||||
// Edit the node to upload a file.
|
||||
$edit = array();
|
||||
$name = 'files[' . $this->fieldName . '_0]';
|
||||
$edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[0]->uri);
|
||||
$this->drupalPostForm('node/' . $default_language_node->id() . '/edit', $edit, t('Save'));
|
||||
$last_fid_prior = $this->getLastFileId();
|
||||
|
||||
// Languages are cached on many levels, and we need to clear those caches.
|
||||
$this->rebuildContainer();
|
||||
|
||||
// Ensure the file can be downloaded.
|
||||
\Drupal::entityManager()->getStorage('node')->resetCache(array($default_language_node->id()));
|
||||
$node = Node::load($default_language_node->id());
|
||||
$node_file = File::load($node->{$this->fieldName}->target_id);
|
||||
$this->drupalGet(file_create_url($node_file->getFileUri()));
|
||||
$this->assertResponse(200, 'Confirmed that the file attached to the English node can be downloaded.');
|
||||
|
||||
// Translate the node into French.
|
||||
$this->drupalGet('node/' . $default_language_node->id() . '/translations');
|
||||
$this->clickLink(t('Add'));
|
||||
|
||||
// Remove the existing file.
|
||||
$this->drupalPostForm(NULL, array(), t('Remove'));
|
||||
|
||||
// Upload a different file.
|
||||
$edit = array();
|
||||
$edit['title[0][value]'] = $this->randomMachineName();
|
||||
$name = 'files[' . $this->fieldName . '_0]';
|
||||
$edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[1]->uri);
|
||||
$this->drupalPostForm(NULL, $edit, t('Save (this translation)'));
|
||||
$last_fid = $this->getLastFileId();
|
||||
|
||||
// Verify the translation was created.
|
||||
\Drupal::entityManager()->getStorage('node')->resetCache(array($default_language_node->id()));
|
||||
$default_language_node = Node::load($default_language_node->id());
|
||||
$this->assertTrue($default_language_node->hasTranslation('fr'), 'Node found in database.');
|
||||
$this->assertTrue($last_fid > $last_fid_prior, 'New file got saved.');
|
||||
|
||||
// Ensure the file attached to the translated node can be downloaded.
|
||||
$french_node = $default_language_node->getTranslation('fr');
|
||||
$node_file = File::load($french_node->{$this->fieldName}->target_id);
|
||||
$this->drupalGet(file_create_url($node_file->getFileUri()));
|
||||
$this->assertResponse(200, 'Confirmed that the file attached to the French node can be downloaded.');
|
||||
}
|
||||
|
||||
}
|
||||
24
web/core/modules/file/src/Tests/RemoteFileSaveUploadTest.php
Normal file
24
web/core/modules/file/src/Tests/RemoteFileSaveUploadTest.php
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
/**
|
||||
* Tests the file uploading functions.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class RemoteFileSaveUploadTest extends SaveUploadTest {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('file_test');
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->config('system.file')->set('default_scheme', 'dummy-remote')->save();
|
||||
}
|
||||
|
||||
}
|
||||
362
web/core/modules/file/src/Tests/SaveUploadTest.php
Normal file
362
web/core/modules/file/src/Tests/SaveUploadTest.php
Normal file
|
|
@ -0,0 +1,362 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests;
|
||||
|
||||
use Drupal\file\Entity\File;
|
||||
|
||||
/**
|
||||
* Tests the file_save_upload() function.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class SaveUploadTest extends FileManagedTestBase {
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('dblog');
|
||||
|
||||
/**
|
||||
* An image file path for uploading.
|
||||
*
|
||||
* @var \Drupal\file\FileInterface
|
||||
*/
|
||||
protected $image;
|
||||
|
||||
/**
|
||||
* A PHP file path for upload security testing.
|
||||
*/
|
||||
protected $phpfile;
|
||||
|
||||
/**
|
||||
* The largest file id when the test starts.
|
||||
*/
|
||||
protected $maxFidBefore;
|
||||
|
||||
/**
|
||||
* Extension of the image filename.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $imageExtension;
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$account = $this->drupalCreateUser(array('access site reports'));
|
||||
$this->drupalLogin($account);
|
||||
|
||||
$image_files = $this->drupalGetTestFiles('image');
|
||||
$this->image = File::create((array) current($image_files));
|
||||
|
||||
list(, $this->imageExtension) = explode('.', $this->image->getFilename());
|
||||
$this->assertTrue(is_file($this->image->getFileUri()), "The image file we're going to upload exists.");
|
||||
|
||||
$this->phpfile = current($this->drupalGetTestFiles('php'));
|
||||
$this->assertTrue(is_file($this->phpfile->uri), 'The PHP file we are going to upload exists.');
|
||||
|
||||
$this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
|
||||
|
||||
// Upload with replace to guarantee there's something there.
|
||||
$edit = array(
|
||||
'file_test_replace' => FILE_EXISTS_REPLACE,
|
||||
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()),
|
||||
);
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$this->assertRaw(t('You WIN!'), 'Found the success message.');
|
||||
|
||||
// Check that the correct hooks were called then clean out the hook
|
||||
// counters.
|
||||
$this->assertFileHooksCalled(array('validate', 'insert'));
|
||||
file_test_reset();
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the file_save_upload() function.
|
||||
*/
|
||||
function testNormal() {
|
||||
$max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
|
||||
$this->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
|
||||
$file1 = File::load($max_fid_after);
|
||||
$this->assertTrue($file1, 'Loaded the file.');
|
||||
// MIME type of the uploaded image may be either image/jpeg or image/png.
|
||||
$this->assertEqual(substr($file1->getMimeType(), 0, 5), 'image', 'A MIME type was set.');
|
||||
|
||||
// Reset the hook counters to get rid of the 'load' we just called.
|
||||
file_test_reset();
|
||||
|
||||
// Upload a second file.
|
||||
$image2 = current($this->drupalGetTestFiles('image'));
|
||||
$edit = array('files[file_test_upload]' => drupal_realpath($image2->uri));
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$this->assertRaw(t('You WIN!'));
|
||||
$max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('validate', 'insert'));
|
||||
|
||||
$file2 = File::load($max_fid_after);
|
||||
$this->assertTrue($file2, 'Loaded the file');
|
||||
// MIME type of the uploaded image may be either image/jpeg or image/png.
|
||||
$this->assertEqual(substr($file2->getMimeType(), 0, 5), 'image', 'A MIME type was set.');
|
||||
|
||||
// Load both files using File::loadMultiple().
|
||||
$files = File::loadMultiple(array($file1->id(), $file2->id()));
|
||||
$this->assertTrue(isset($files[$file1->id()]), 'File was loaded successfully');
|
||||
$this->assertTrue(isset($files[$file2->id()]), 'File was loaded successfully');
|
||||
|
||||
// Upload a third file to a subdirectory.
|
||||
$image3 = current($this->drupalGetTestFiles('image'));
|
||||
$image3_realpath = drupal_realpath($image3->uri);
|
||||
$dir = $this->randomMachineName();
|
||||
$edit = array(
|
||||
'files[file_test_upload]' => $image3_realpath,
|
||||
'file_subdir' => $dir,
|
||||
);
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$this->assertRaw(t('You WIN!'));
|
||||
$this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test extension handling.
|
||||
*/
|
||||
function testHandleExtension() {
|
||||
// The file being tested is a .gif which is in the default safe list
|
||||
// of extensions to allow when the extension validator isn't used. This is
|
||||
// implicitly tested at the testNormal() test. Here we tell
|
||||
// file_save_upload() to only allow ".foo".
|
||||
$extensions = 'foo';
|
||||
$edit = array(
|
||||
'file_test_replace' => FILE_EXISTS_REPLACE,
|
||||
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()),
|
||||
'extensions' => $extensions,
|
||||
);
|
||||
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $extensions . '</em>';
|
||||
$this->assertRaw($message, 'Cannot upload a disallowed extension');
|
||||
$this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('validate'));
|
||||
|
||||
// Reset the hook counters.
|
||||
file_test_reset();
|
||||
|
||||
$extensions = 'foo ' . $this->imageExtension;
|
||||
// Now tell file_save_upload() to allow the extension of our test image.
|
||||
$edit = array(
|
||||
'file_test_replace' => FILE_EXISTS_REPLACE,
|
||||
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()),
|
||||
'extensions' => $extensions,
|
||||
);
|
||||
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload an allowed extension.');
|
||||
$this->assertRaw(t('You WIN!'), 'Found the success message.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('validate', 'load', 'update'));
|
||||
|
||||
// Reset the hook counters.
|
||||
file_test_reset();
|
||||
|
||||
// Now tell file_save_upload() to allow any extension.
|
||||
$edit = array(
|
||||
'file_test_replace' => FILE_EXISTS_REPLACE,
|
||||
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()),
|
||||
'allow_all_extensions' => TRUE,
|
||||
);
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload any extension.');
|
||||
$this->assertRaw(t('You WIN!'), 'Found the success message.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('validate', 'load', 'update'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test dangerous file handling.
|
||||
*/
|
||||
function testHandleDangerousFile() {
|
||||
$config = $this->config('system.file');
|
||||
// Allow the .php extension and make sure it gets renamed to .txt for
|
||||
// safety. Also check to make sure its MIME type was changed.
|
||||
$edit = array(
|
||||
'file_test_replace' => FILE_EXISTS_REPLACE,
|
||||
'files[file_test_upload]' => drupal_realpath($this->phpfile->uri),
|
||||
'is_image_file' => FALSE,
|
||||
'extensions' => 'php',
|
||||
);
|
||||
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '.txt' . '</em>';
|
||||
$this->assertRaw($message, 'Dangerous file was renamed.');
|
||||
$this->assertRaw(t('File MIME type is text/plain.'), "Dangerous file's MIME type was changed.");
|
||||
$this->assertRaw(t('You WIN!'), 'Found the success message.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('validate', 'insert'));
|
||||
|
||||
// Ensure dangerous files are not renamed when insecure uploads is TRUE.
|
||||
// Turn on insecure uploads.
|
||||
$config->set('allow_insecure_uploads', 1)->save();
|
||||
// Reset the hook counters.
|
||||
file_test_reset();
|
||||
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
|
||||
$this->assertRaw(t('File name is @filename', array('@filename' => $this->phpfile->filename)), 'Dangerous file was not renamed when insecure uploads is TRUE.');
|
||||
$this->assertRaw(t('You WIN!'), 'Found the success message.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('validate', 'insert'));
|
||||
|
||||
// Turn off insecure uploads.
|
||||
$config->set('allow_insecure_uploads', 0)->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Test file munge handling.
|
||||
*/
|
||||
function testHandleFileMunge() {
|
||||
// Ensure insecure uploads are disabled for this test.
|
||||
$this->config('system.file')->set('allow_insecure_uploads', 0)->save();
|
||||
$this->image = file_move($this->image, $this->image->getFileUri() . '.foo.' . $this->imageExtension);
|
||||
|
||||
// Reset the hook counters to get rid of the 'move' we just called.
|
||||
file_test_reset();
|
||||
|
||||
$extensions = $this->imageExtension;
|
||||
$edit = array(
|
||||
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()),
|
||||
'extensions' => $extensions,
|
||||
);
|
||||
|
||||
$munged_filename = $this->image->getFilename();
|
||||
$munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
|
||||
$munged_filename .= '_.' . $this->imageExtension;
|
||||
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
|
||||
$this->assertRaw(t('File name is @filename', array('@filename' => $munged_filename)), 'File was successfully munged.');
|
||||
$this->assertRaw(t('You WIN!'), 'Found the success message.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('validate', 'insert'));
|
||||
|
||||
// Ensure we don't munge files if we're allowing any extension.
|
||||
// Reset the hook counters.
|
||||
file_test_reset();
|
||||
|
||||
$edit = array(
|
||||
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()),
|
||||
'allow_all_extensions' => TRUE,
|
||||
);
|
||||
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
|
||||
$this->assertRaw(t('File name is @filename', array('@filename' => $this->image->getFilename())), 'File was not munged when allowing any extension.');
|
||||
$this->assertRaw(t('You WIN!'), 'Found the success message.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('validate', 'insert'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test renaming when uploading over a file that already exists.
|
||||
*/
|
||||
function testExistingRename() {
|
||||
$edit = array(
|
||||
'file_test_replace' => FILE_EXISTS_RENAME,
|
||||
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri())
|
||||
);
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$this->assertRaw(t('You WIN!'), 'Found the success message.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('validate', 'insert'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test replacement when uploading over a file that already exists.
|
||||
*/
|
||||
function testExistingReplace() {
|
||||
$edit = array(
|
||||
'file_test_replace' => FILE_EXISTS_REPLACE,
|
||||
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri())
|
||||
);
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$this->assertRaw(t('You WIN!'), 'Found the success message.');
|
||||
|
||||
// Check that the correct hooks were called.
|
||||
$this->assertFileHooksCalled(array('validate', 'load', 'update'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for failure when uploading over a file that already exists.
|
||||
*/
|
||||
function testExistingError() {
|
||||
$edit = array(
|
||||
'file_test_replace' => FILE_EXISTS_ERROR,
|
||||
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri())
|
||||
);
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
|
||||
|
||||
// Check that the no hooks were called while failing.
|
||||
$this->assertFileHooksCalled(array());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for no failures when not uploading a file.
|
||||
*/
|
||||
function testNoUpload() {
|
||||
$this->drupalPostForm('file-test/upload', array(), t('Submit'));
|
||||
$this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests for log entry on failing destination.
|
||||
*/
|
||||
function testDrupalMovingUploadedFileError() {
|
||||
// Create a directory and make it not writable.
|
||||
$test_directory = 'test_drupal_move_uploaded_file_fail';
|
||||
drupal_mkdir('temporary://' . $test_directory, 0000);
|
||||
$this->assertTrue(is_dir('temporary://' . $test_directory));
|
||||
|
||||
$edit = array(
|
||||
'file_subdir' => $test_directory,
|
||||
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri())
|
||||
);
|
||||
|
||||
\Drupal::state()->set('file_test.disable_error_collection', TRUE);
|
||||
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
|
||||
$this->assertResponse(200, 'Received a 200 response for posted test file.');
|
||||
$this->assertRaw(t('File upload error. Could not move uploaded file.'), 'Found the failure message.');
|
||||
$this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
|
||||
|
||||
// Uploading failed. Now check the log.
|
||||
$this->drupalGet('admin/reports/dblog');
|
||||
$this->assertResponse(200);
|
||||
$this->assertRaw(t('Upload error. Could not move uploaded file @file to destination @destination.', array(
|
||||
'@file' => $this->image->getFilename(),
|
||||
'@destination' => 'temporary://' . $test_directory . '/' . $this->image->getFilename()
|
||||
)), 'Found upload error log entry.');
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\file\Tests\Views;
|
||||
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\file\Entity\File;
|
||||
use Drupal\views\Tests\ViewTestBase;
|
||||
use Drupal\views\Views;
|
||||
use Drupal\views\Tests\ViewTestData;
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
|
||||
/**
|
||||
* Tests file on user relationship handler.
|
||||
*
|
||||
* @group file
|
||||
*/
|
||||
class RelationshipUserFileDataTest extends ViewTestBase {
|
||||
|
||||
/**
|
||||
* Modules to install.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('file', 'file_test_views', 'user');
|
||||
|
||||
/**
|
||||
* Views used by this test.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $testViews = array('test_file_user_file_data');
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Create the user profile field and instance.
|
||||
FieldStorageConfig::create(array(
|
||||
'entity_type' => 'user',
|
||||
'field_name' => 'user_file',
|
||||
'type' => 'file',
|
||||
'translatable' => '0',
|
||||
))->save();
|
||||
FieldConfig::create([
|
||||
'label' => 'User File',
|
||||
'description' => '',
|
||||
'field_name' => 'user_file',
|
||||
'entity_type' => 'user',
|
||||
'bundle' => 'user',
|
||||
'required' => 0,
|
||||
])->save();
|
||||
|
||||
ViewTestData::createTestViews(get_class($this), array('file_test_views'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests using the views file relationship.
|
||||
*/
|
||||
public function testViewsHandlerRelationshipUserFileData() {
|
||||
$file = File::create([
|
||||
'fid' => 2,
|
||||
'uid' => 2,
|
||||
'filename' => 'image-test.jpg',
|
||||
'uri' => "public://image-test.jpg",
|
||||
'filemime' => 'image/jpeg',
|
||||
'created' => 1,
|
||||
'changed' => 1,
|
||||
'status' => FILE_STATUS_PERMANENT,
|
||||
]);
|
||||
$file->enforceIsNew();
|
||||
file_put_contents($file->getFileUri(), file_get_contents('core/modules/simpletest/files/image-1.png'));
|
||||
$file->save();
|
||||
|
||||
$account = $this->drupalCreateUser();
|
||||
$account->user_file->target_id = 2;
|
||||
$account->save();
|
||||
|
||||
$view = Views::getView('test_file_user_file_data');
|
||||
// Tests \Drupal\taxonomy\Plugin\views\relationship\NodeTermData::calculateDependencies().
|
||||
$expected = [
|
||||
'module' => [
|
||||
'file',
|
||||
'user',
|
||||
],
|
||||
];
|
||||
$this->assertIdentical($expected, $view->getDependencies());
|
||||
$this->executeView($view);
|
||||
$expected_result = array(
|
||||
array(
|
||||
'file_managed_user__user_file_fid' => '2',
|
||||
),
|
||||
);
|
||||
$column_map = array('file_managed_user__user_file_fid' => 'file_managed_user__user_file_fid');
|
||||
$this->assertIdenticalResultset($view, $expected_result, $column_map);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in a new issue