- <?php
- * @file
- * Tests for file.module.
- */
-
- * Provides methods specifically for testing File module's field handling.
- */
- class FileTestHelper extends BackdropWebTestCase {
- protected $profile = 'standard';
- protected $admin_user;
-
- function setUp() {
-
-
-
- $modules = func_get_args();
- if (isset($modules[0]) && is_array($modules[0])) {
- $modules = $modules[0];
- }
- $modules[] = 'file';
- $modules[] = 'path';
- $modules[] = 'file_module_test';
- parent::setUp($modules);
- $this->admin_user = $this->backdropCreateUser(array(
- 'access file overview',
- 'manage files',
- 'access content',
- 'access administration pages',
- 'administer site configuration',
- 'administer users',
- 'administer permissions',
- 'administer content types',
- 'administer nodes',
- 'bypass node access',
- 'administer fields',
- 'create url aliases',
- 'delete files',
- ));
- $this->backdropLogin($this->admin_user);
- }
-
-
- * Get a file from the database based on its filename.
- *
- * @param $filename
- * A file filename, usually generated by $this->randomName().
- * @param $reset
- * (optional) Whether to reset the internal file_load() cache.
- *
- * @return
- * A file object matching $filename.
- */
- function getFileByFilename($filename, $reset = FALSE) {
- $files = file_load_multiple(array(), array('filename' => $filename), $reset);
-
- $returned_file = reset($files);
- return $returned_file;
- }
-
- protected function createFile($settings = array()) {
-
- $settings += array(
- 'filepath' => 'Файлдлятестирования ' . $this->randomName(),
- 'filemime' => 'text/plain',
- 'uid' => 1,
- 'timestamp' => REQUEST_TIME,
- 'status' => FILE_STATUS_PERMANENT,
- 'contents' => "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.",
- 'scheme' => file_default_scheme(),
- 'type' => NULL,
- );
-
- $filepath = $settings['scheme'] . '://' . $settings['filepath'];
-
- file_put_contents($filepath, $settings['contents']);
- $this->assertTrue(is_file($filepath), t('The test file exists on the disk.'), 'Create test file');
-
- $file = new File();
- $file->uri = $filepath;
- $file->filename = backdrop_basename($file->uri);
- $file->filemime = $settings['filemime'];
- $file->uid = $settings['uid'];
- $file->timestamp = $settings['timestamp'];
- $file->filesize = filesize($file->uri);
- $file->status = $settings['status'];
- $file->type = $settings['type'];
-
-
- if (!isset($file->type)) {
- $file->type = FILE_TYPE_NONE;
- }
-
-
-
- if ($file->type === FILE_TYPE_NONE) {
- $type = file_get_type($file);
- if (isset($type)) {
- $file->type = $type;
- }
- }
-
-
-
- $this->assertNotIdentical(backdrop_write_record('file_managed', $file), FALSE, t('The file was added to the database.'), 'Create test file');
-
- return $file;
- }
-
- protected function createFileType($overrides = array()) {
- $type = new stdClass();
- $type->type = 'test';
- $type->name = "Test";
- $type->module = 'file';
- $type->description = '';
- $type->mimetypes = array('image/jpeg', 'image/gif', 'image/png', 'image/tiff');
-
- foreach ($overrides as $k => $v) {
- $type->$k = $v;
- }
-
- file_type_save($type);
-
- file_display_save($type->type, 'default', array(
- 'formatter' => 'file_field_file_download_link',
- 'settings' => array(
- 'file_field_file_download_link' => array(
- 'text' => 'Download [file:name]',
- ),
- ),
- ));
-
- return $type;
- }
-
-
- * Retrieves a sample file of the specified type.
- */
- function getTestFile($type_name, $size = NULL) {
-
- $file = current($this->backdropGetTestFiles($type_name, $size));
-
-
- $file->filesize = filesize($file->uri);
-
- return entity_create('file', (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 $name
- * The name of the new field (all lowercase), exclude the "field_" prefix.
- * @param $type_name
- * The node type that this field will be added to.
- * @param $field_settings
- * A list of field settings that will be added to the defaults.
- * @param $instance_settings
- * A list of instance settings that will be added to the instance defaults.
- * @param $widget_settings
- * A list of widget settings that will be added to the widget defaults.
- */
- function createFileField($name, $type_name, $field_settings = array(), $instance_settings = array(), $widget_settings = array()) {
- $cardinality = 1;
- if (isset($field_settings['cardinality'])) {
- $cardinality = $field_settings['cardinality'];
- unset($field_settings['cardinality']);
- }
- $field = array(
- 'field_name' => $name,
- 'type' => 'file',
- 'cardinality' => $cardinality,
- 'settings' => $field_settings,
- );
- field_create_field($field);
-
- $this->attachFileField($name, 'node', $type_name, $instance_settings, $widget_settings);
- }
-
-
- * Attaches a file field to an entity.
- *
- * @param $name
- * The name of the new field (all lowercase), exclude the "field_" prefix.
- * @param $entity_type
- * The entity type this field will be added to.
- * @param $bundle
- * The bundle this field will be added to.
- * @param $field_settings
- * A list of field settings that will be added to the defaults.
- * @param $instance_settings
- * A list of instance settings that will be added to the instance defaults.
- * @param $widget_settings
- * A list of widget settings that will be added to the widget defaults.
- */
- function attachFileField($name, $entity_type, $bundle, $instance_settings = array(), $widget_settings = array()) {
- $instance = array(
- 'field_name' => $name,
- 'label' => $name,
- 'entity_type' => $entity_type,
- 'bundle' => $bundle,
- 'required' => !empty($instance_settings['required']),
- 'settings' => array(),
- 'widget' => array(
- 'type' => 'file_generic',
- 'settings' => array(),
- ),
- );
- $instance['settings'] = array_merge($instance['settings'], $instance_settings);
- $instance['widget']['settings'] = array_merge($instance['widget']['settings'], $widget_settings);
- field_create_instance($instance);
- }
-
-
- * Updates an existing file field with new settings.
- */
- function updateFileField($name, $type_name, $instance_settings = array(), $widget_settings = array()) {
- $instance = field_info_instance('node', $name, $type_name);
- $instance['settings'] = array_merge($instance['settings'], $instance_settings);
- $instance['widget']['settings'] = array_merge($instance['widget']['settings'], $widget_settings);
-
- field_update_instance($instance);
- }
-
-
- * Uploads a file to a node.
- */
- function uploadNodeFile($file, $field_name, $nid_or_type, $new_revision = TRUE, $extras = array()) {
- $langcode = LANGUAGE_NONE;
- $edit = array(
- "title" => $this->randomName(),
- 'revision' => (string) (int) $new_revision,
- );
-
- if (is_numeric($nid_or_type)) {
- $nid = $nid_or_type;
- }
- else {
-
- $extras['type'] = $nid_or_type;
- $node = $this->backdropCreateNode($extras);
- $nid = $node->nid;
-
- $this->backdropCreateNode(get_object_vars($node));
- $node = node_load($nid, NULL, TRUE);
- $this->assertNotEqual($nid, $node->vid, 'Node revision exists.');
- }
-
-
- $edit['files[' . $field_name . '_' . $langcode . '_0]'] = backdrop_realpath($file->uri);
- $this->backdropPost("node/$nid/edit", $edit, t('Save'));
-
- 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->backdropPost('node/' . $nid . '/edit', array(), t('Remove'));
- $this->backdropPost(NULL, $edit, t('Save'));
- }
-
-
- * Replaces a file within a node.
- */
- function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
- $edit = array(
- 'files[' . $field_name . '_' . LANGUAGE_NONE . '_0]' => backdrop_realpath($file->uri),
- 'revision' => (string) (int) $new_revision,
- );
-
- $this->backdropPost('node/' . $nid . '/edit', array(), t('Remove'));
- $this->backdropPost(NULL, $edit, t('Save'));
- }
-
-
- * 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->uri));
- $this->assertTrue(is_file($file->uri), $message);
- }
-
-
- * Asserts that a file exists in the database.
- */
- function assertFileEntryExists($file, $message = NULL) {
- entity_get_controller('file')->resetCache();
- $db_file = file_load($file->fid);
- $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', array('%file' => $file->uri));
- $this->assertEqual($db_file->uri, $file->uri, $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->uri));
- $this->assertFalse(is_file($file->uri), $message);
- }
-
-
- * Asserts that a file does not exist in the database.
- */
- function assertFileEntryNotExists($file, $message) {
- entity_get_controller('file')->resetCache();
- $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', array('%file' => $file->uri));
- $this->assertFalse(file_load($file->fid), $message);
- }
-
-
- * Asserts that a file's status is set to permanent in the database.
- */
- function assertFileIsPermanent($file, $message = NULL) {
- $message = isset($message) ? $message : format_string('File %file is permanent.', array('%file' => $file->uri));
- $this->assertTrue($file->status == FILE_STATUS_PERMANENT, $message);
- }
-
-
- * Creates a temporary file, for a specific user.
- *
- * @param string $data
- * A string containing the contents of the file.
- * @param int $uid
- * The user ID of the file owner.
- *
- * @return object
- * A file object, or FALSE on error.
- */
- function createTemporaryFile($data, $uid = NULL) {
- $file = file_save_data($data);
-
- if ($file) {
- $file->uid = isset($uid) ? $uid : $this->admin_user->uid;
-
- $file->status = 0;
- file_save($file);
- }
-
- return $file;
- }
- }
-
- * Tests adding a file to a non-node entity.
- */
- class FileTaxonomyTermTestCase extends BackdropWebTestCase {
- protected $admin_user;
-
- public function setUp() {
- $modules[] = 'file';
- $modules[] = 'taxonomy';
- parent::setUp($modules);
- $this->admin_user = $this->backdropCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer taxonomy'));
- $this->backdropLogin($this->admin_user);
- }
-
-
- * Creates a file field and attaches it to the "Tags" taxonomy vocabulary.
- *
- * @param $name
- * The field name of the file field to create.
- * @param $uri_scheme
- * The URI scheme to use for the file field (for example, "private" to
- * create a field that stores private files or "public" to create a field
- * that stores public files).
- */
- protected function createAttachFileField($name, $uri_scheme) {
- $field = array(
- 'field_name' => $name,
- 'type' => 'file',
- 'settings' => array(
- 'uri_scheme' => $uri_scheme,
- ),
- 'cardinality' => 1,
- );
- field_create_field($field);
-
- $instance = array(
- 'field_name' => $name,
- 'label' => 'File',
- 'entity_type' => 'taxonomy_term',
- 'bundle' => 'tags',
- 'required' => FALSE,
- 'settings' => array(),
- 'widget' => array(
- 'type' => 'file_generic',
- 'settings' => array(),
- ),
- );
- field_create_instance($instance);
- }
-
-
- * Tests that a public file can be attached to a taxonomy term.
- */
- public function testTermFilePublic() {
- $this->_testTermFile('public');
- }
-
-
- * Tests that a private file can be attached to a taxonomy term.
- */
- public function testTermFilePrivate() {
- $this->_testTermFile('private');
- }
-
-
- * Runs tests for attaching a file field to a taxonomy term.
- *
- * @param $uri_scheme
- * The URI scheme to use for the file field, either "public" or "private".
- */
- protected function _testTermFile($uri_scheme) {
- $field_name = strtolower($this->randomName());
- $this->createAttachFileField($field_name, $uri_scheme);
-
- $file = current($this->backdropGetTestFiles('text'));
-
- $file->filesize = filesize($file->uri);
- $langcode = LANGUAGE_NONE;
- $edit = array(
- "name" => $this->randomName(),
- );
-
- $edit['files[' . $field_name . '_' . $langcode . '_0]'] = backdrop_realpath($file->uri);
- $this->backdropPost("admin/structure/taxonomy/tags/add", $edit, t('Save'));
-
- $tid = db_query_range('SELECT tid FROM {taxonomy_term_data} ORDER BY tid DESC', 0, 1)->fetchField();
- $terms = entity_load('taxonomy_term', array($tid));
- $term = $terms[$tid];
- $fid = $term->{$field_name}[LANGUAGE_NONE][0]['fid'];
-
- $this->backdropGet("taxonomy/term/$tid/edit");
- $file_input_name = $field_name . '[' . LANGUAGE_NONE . '][0][fid]';
- $this->assertFieldByXpath('//input[@type="hidden" and @name="' . $file_input_name . '"]', $fid, 'File is attached on edit form.');
-
- $edit = array(
- "name" => $this->randomName(),
- );
- $this->backdropPost("taxonomy/term/$tid/edit", $edit, t('Save'));
-
- $this->backdropGet("taxonomy/term/$tid/edit");
- $file_input_name = $field_name . '[' . LANGUAGE_NONE . '][0][fid]';
- $this->assertFieldByXpath('//input[@type="hidden" and @name="' . $file_input_name . '"]', $fid, 'File is attached on edit form.');
-
- $terms = entity_load('taxonomy_term', array($tid), array(), TRUE);
- $term = $terms[$tid];
- $this->assertTrue(!empty($term->{$field_name}[LANGUAGE_NONE]), 'Term has attached files.');
- $this->assertEqual($term->{$field_name}[LANGUAGE_NONE][0]['fid'], $fid, 'Same File ID is attached to the term.');
- }
- }
-
- * Tests the 'managed_file' element type.
- *
- * @todo Create a FileTestCase base class and move FileTestHelper methods
- * that aren't related to fields into it.
- */
- class FileManagedFileElementTestCase extends FileTestHelper {
-
- * Tests the managed_file element type.
- */
- function testManagedFile() {
-
- $this->backdropGet('file/test');
- $this->assertFieldByXpath('//input[@name="files[nested_file]" and @size="13"]', NULL, 'The custom #size attribute is passed to the child upload element.');
-
-
-
- foreach (array(0, 1) as $tree) {
- foreach (array(0, 1) as $extended) {
- $test_file = $this->getTestFile('text');
- $path = 'file/test/' . $tree . '/' . $extended;
- $input_base_name = $tree ? 'nested_file' : 'file';
-
-
- $this->backdropPost($path, array(), t('Save'));
- $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submitted without a file.');
-
-
-
- $last_fid_prior = $this->getLastFileId();
- $edit = array(
- 'files[' . $input_base_name . ']' => backdrop_realpath($test_file->uri),
- 'form_token' => 'invalid token',
- );
- $this->backdropPost($path, $edit, t('Save'));
- $this->assertText('The form has become outdated.');
- $last_fid = $this->getLastFileId();
- $this->assertEqual($last_fid_prior, $last_fid, 'File was not saved when uploaded with an invalid form token.');
-
-
- $last_fid_prior = $this->getLastFileId();
- $edit = array('files[' . $input_base_name . ']' => backdrop_realpath($test_file->uri));
- $this->backdropPost($path, $edit, t('Save'));
- $last_fid = $this->getLastFileId();
- $this->assertTrue($last_fid > $last_fid_prior, 'New file got saved.');
- $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Submit handler has correct file info.');
-
-
- $this->backdropPost($path . '/' . $last_fid, array(), t('Save'));
- $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Empty submission did not change an existing file.');
-
-
- foreach (array(FALSE, TRUE) as $ajax) {
-
- $last_fid_prior = $this->getLastFileId();
- $this->backdropGet($path);
- $edit = array('files[' . $input_base_name . ']' => backdrop_realpath($test_file->uri));
- if ($ajax) {
- $this->backdropPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
- }
- else {
- $this->backdropPost(NULL, $edit, t('Upload'));
- }
- $last_fid = $this->getLastFileId();
- $this->assertTrue($last_fid > $last_fid_prior, 'New file got uploaded.');
- $this->backdropPost(NULL, array(), t('Save'));
- $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Submit handler has correct file info.');
-
-
- $this->backdropGet($path . '/' . $last_fid);
- if ($ajax) {
- $this->backdropPostAJAX(NULL, array(), $input_base_name . '_remove_button');
- }
- else {
- $this->backdropPost(NULL, array(), t('Remove'));
- }
- $this->backdropPost(NULL, array(), t('Save'));
- $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submission after file removal was successful.');
-
-
- $this->backdropGet($path);
- $edit = array('files[' . $input_base_name . ']' => backdrop_realpath($test_file->uri));
- if ($ajax) {
- $this->backdropPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
- $this->backdropPostAJAX(NULL, array(), $input_base_name . '_remove_button');
- }
- else {
- $this->backdropPost(NULL, $edit, t('Upload'));
- $this->backdropPost(NULL, array(), t('Remove'));
- }
- $this->backdropPost(NULL, array(), t('Save'));
- $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submission after file upload and removal was successful.');
- }
- }
- }
- }
-
-
- * Tests file_ajax_upload() parents_hash.
- */
- function testManagedFileParentsHash() {
-
-
- foreach (array(0, 1) as $tree) {
- foreach (array(0, 1) as $extended) {
- $test_file = $this->getTestFile('text');
- $path = 'file/test/' . $tree . '/' . $extended;
- $input_base_name = $tree ? 'nested_file' : 'file';
-
-
- $last_fid_prior = $this->getLastFileId();
- $this->backdropGet($path);
- $edit = array('files[' . $input_base_name . ']' => backdrop_realpath($test_file->uri));
-
-
- $xpath = '//*[@name="' . $input_base_name . '_upload_button"]';
- $element = $this->xpath($xpath);
- $element_id = (string) $element[0]['id'];
- $ajax_settings = $this->backdropSettings['ajax'][$element_id];
-
- $ajax_path = explode('/', $ajax_settings['url']);
- array_pop($ajax_path);
- $ajax_path = implode('/', $ajax_path);
- $this->assertNoRaw(t('Invalid upload token.'));
- $this->backdropPostAJAX(NULL, $edit, $input_base_name . '_upload_button', $ajax_path);
- $this->assertRaw(t('Invalid upload token.'));
- $last_fid = $this->getLastFileId();
- $this->assertEqual($last_fid, $last_fid_prior, 'No new file got uploaded.');
- }
- }
- }
- }
-
- * Tests file field widget.
- */
- class FileFieldWidgetTestCase extends FileTestHelper {
-
- * Tests upload and remove buttons for a single-valued File field.
- */
- function testSingleValuedWidget() {
-
-
-
-
- $type_name = 'page';
- $field_name = strtolower($this->randomName());
- $this->createFileField($field_name, $type_name);
- $field = field_info_field($field_name);
- $instance = field_info_instance('node', $field_name, $type_name);
-
- $test_file = $this->getTestFile('text');
-
- foreach (array('nojs', 'js') as $type) {
-
-
-
-
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
-
-
- $this->backdropGet(file_create_url($node_file->uri));
- $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
-
-
- $this->backdropGet("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.');
-
-
- switch ($type) {
- case 'nojs':
- $this->backdropPost(NULL, array(), t('Remove'));
- break;
- case 'js':
- $button = $this->xpath('//input[@type="submit" and @value="' . t('Remove') . '"]');
- $this->backdropPostAJAX(NULL, array(), array((string) $button[0]['name'] => (string) $button[0]['value']));
- break;
- }
-
-
- $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.');
-
-
- $this->backdropPost(NULL, array(), t('Save'));
- $node = node_load($nid, NULL, TRUE);
- $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'File was successfully removed from the node.');
- }
- }
-
-
- * Tests exploiting the temporary file removal of another user using fid.
- */
- function testTemporaryFileRemovalExploit() {
-
- $victim_user = $this->backdropCreateUser();
-
-
- $attacker_user = $this->backdropCreateUser(array(
- 'access content',
- 'create page content',
- 'edit any page content',
- ));
-
-
- $this->backdropLogin($attacker_user);
-
-
- $this->doTestTemporaryFileRemovalExploit($victim_user->uid, $attacker_user->uid);
- }
-
-
- * Tests exploiting the temporary file removal for anonymous users using fid.
- */
- public function testTemporaryFileRemovalExploitAnonymous() {
-
- $victim_uid = 0;
-
-
- $attacker_uid = 0;
-
-
- user_role_change_permissions(BACKDROP_ANONYMOUS_ROLE, array(
- 'access content' => TRUE,
- 'create page content' => TRUE,
- 'edit any page content' => TRUE,
- ));
-
-
-
- $this->backdropLogout();
-
-
- $this->doTestTemporaryFileRemovalExploit($victim_uid, $attacker_uid);
- }
-
-
- * Tests validation with the Upload button.
- */
- function testWidgetValidation() {
- $type_name = 'post';
- $field_name = strtolower($this->randomName());
- $this->createFileField($field_name, $type_name);
- $this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt'));
-
- foreach (array('nojs', 'js') as $type) {
-
- $node = $this->backdropCreateNode(array('type' => 'post'));
- $nid = $node->nid;
- $this->backdropGet("node/$nid/edit");
- $test_file_text = $this->getTestFile('text');
- $test_file_image = $this->getTestFile('image');
- $field = field_info_field($field_name);
- $name = 'files[' . $field_name . '_' . LANGUAGE_NONE . '_0]';
-
-
- $edit[$name] = backdrop_realpath($test_file_image->uri);
- switch ($type) {
- case 'nojs':
- $this->backdropPost(NULL, $edit, t('Upload'));
- break;
-
- case 'js':
- $button = $this->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]');
- $this->backdropPostAJAX(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)));
-
-
- $edit[$name] = backdrop_realpath($test_file_text->uri);
- switch ($type) {
- case 'nojs':
- $this->backdropPost(NULL, $edit, t('Upload'));
- break;
-
- case 'js':
- $button = $this->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]');
- $this->backdropPostAJAX(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)));
- }
- }
-
-
- * Helper for testing exploiting the temporary file removal using fid.
- *
- * @param int $victim_uid
- * The victim user ID.
- * @param int $attacker_uid
- * The attacker user ID.
- */
- protected function doTestTemporaryFileRemovalExploit($victim_uid, $attacker_uid) {
-
-
-
-
- $type_name = 'page';
- $field_name = 'test_file_field';
- $this->createFileField($field_name, $type_name);
-
- $test_file = $this->getTestFile('text');
- foreach (array('nojs', 'js') as $type) {
-
-
-
- $victim_tmp_file = $this->createTemporaryFile('some text', $victim_uid);
- $victim_tmp_file = file_load($victim_tmp_file->fid);
- $this->assertTrue($victim_tmp_file->status != FILE_STATUS_PERMANENT, 'New file saved to disk is temporary.');
- $this->assertFalse(empty($victim_tmp_file->fid), 'New file has a fid');
- $this->assertEqual($victim_uid, $victim_tmp_file->uid, 'New file belongs to the victim user');
-
-
-
- $edit = array(
- 'title' => $type . '-title',
- );
-
-
- $langcode = LANGUAGE_NONE;
- $edit['files[' . $field_name . '_' . $langcode . '_0]'] = backdrop_realpath($test_file->uri);
- $this->backdropPost("node/add/$type_name", $edit, 'Save');
- $node = $this->backdropGetNodeByTitle($edit['title']);
- $node_file = file_load($node->{$field_name}[$langcode][0]['fid']);
- $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
- $this->assertEqual($attacker_uid, $node_file->uid, 'New file belongs to the attacker.');
-
-
- $this->backdropGet(file_create_url($node_file->uri));
- $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
-
-
-
-
- $this->backdropGet('node/' . $node->nid . '/edit');
- switch ($type) {
- case 'nojs':
- $this->backdropPost(NULL, array("{$field_name}[$langcode][0][fid]" => (string) $victim_tmp_file->fid), 'Remove');
- break;
- case 'js':
- $button = $this->xpath('//input[@type="submit" and @value="Remove"]');
- $this->backdropPostAJAX(NULL, array("{$field_name}[$langcode][0][fid]" => (string) $victim_tmp_file->fid), array((string) $button[0]['name'] => (string) $button[0]['value']));
- break;
- }
-
-
-
- $this->assertFileExists($victim_tmp_file);
- }
- }
-
-
- * Tests upload and remove buttons for multiple multi-valued File fields.
- */
- function testMultiValuedWidget() {
-
-
-
-
- $type_name = 'page';
- $field_name = 'file1';
- $field_name2 = 'file2';
- $this->createFileField($field_name, $type_name, array('cardinality' => 3));
- $this->createFileField($field_name2, $type_name, array('cardinality' => 3));
-
- $field = field_info_field($field_name);
- $instance = field_info_instance('node', $field_name, $type_name);
-
- $field2 = field_info_field($field_name2);
- $instance2 = field_info_instance('node', $field_name2, $type_name);
-
- $test_file = $this->getTestFile('text');
-
- foreach (array('nojs', 'js') as $type) {
-
-
-
-
-
-
-
-
- $this->backdropGet("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 . '_' . LANGUAGE_NONE . '_' . $delta . ']' => backdrop_realpath($test_file->uri));
-
-
- $this->backdropPost(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) {
-
- $remaining = 3;
-
-
-
-
-
-
- foreach (array(1,1,0) as $delta) {
-
-
- $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 . '_' . LANGUAGE_NONE . '_' . $key. '_remove_button');
- }
-
-
- $button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $delta . '_remove_button';
- switch ($type) {
- case 'nojs':
-
-
-
-
-
-
-
- foreach ($buttons as $button) {
- if ($button['name'] != $button_name) {
- $button['value'] = 'DUMMY';
- }
- }
- $this->backdropPost(NULL, array(), t('Remove'));
- break;
- case 'js':
-
-
- $this->backdropPostAJAX(NULL, array(), array($button_name => t('Remove')));
- break;
- }
- $num_expected_remove_buttons--;
- $remaining--;
-
-
-
- $upload_button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $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)));
-
-
- $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)));
- }
- }
-
-
- $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), format_string('After removing all files, there is no "Remove" button displayed (JSMode=%type).', array('%type' => $type)));
-
-
- $this->backdropPost(NULL, array(
- 'title' => $this->randomName(),
- 'path[auto]' => FALSE,
- 'path[alias]' => '',
- ), t('Save'));
- $matches = array();
- preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
- $nid = $matches[1];
- $node = node_load($nid, NULL, TRUE);
- $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'Node was successfully saved without any files.');
- }
- }
-
-
- * Tests a file field with a "Private files" upload destination setting.
- */
- function testPrivateFileSetting() {
-
-
-
-
- $type_name = 'page';
- $field_name = strtolower($this->randomName());
- $this->createFileField($field_name, $type_name);
- $field = field_info_field($field_name);
- $instance = field_info_instance('node', $field_name, $type_name);
-
- $test_file = $this->getTestFile('text');
-
-
- $edit = array('field[settings][uri_scheme]' => 'private');
- $this->backdropPost("admin/structure/types/manage/$type_name/fields/$field_name", $edit, t('Save settings'));
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
-
-
- $this->backdropGet(file_create_url($node_file->uri));
- $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
-
-
-
- $this->backdropGet("admin/structure/types/manage/$type_name/fields/$field_name");
- $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and @disabled="disabled"]', 'public', 'Upload destination setting disabled.');
-
-
- node_delete($nid);
- $this->backdropGet("admin/structure/types/manage/$type_name/fields/$field_name");
- $this->assertFieldByXpath('//input[@id="edit-field-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->backdropCreateUser(array('access comments'));
-
-
- $edit = array(
- 'anonymous[access comments]' => FALSE,
- );
- $this->backdropPost('admin/config/people/permissions', $edit, t('Save permissions'));
-
-
- $edit = array(
- 'fields[_add_new_field][label]' => $label = $this->randomName(),
- 'fields[_add_new_field][field_name]' => $name = strtolower($this->randomName()),
- 'fields[_add_new_field][type]' => 'file',
- 'fields[_add_new_field][widget_type]' => 'file_generic',
- );
- $this->backdropPost('admin/structure/types/manage/post/comment/fields', $edit, t('Save'));
- $edit = array('field[settings][uri_scheme]' => 'private');
- $this->backdropPost(NULL, $edit, t('Save field settings'));
- $this->backdropPost(NULL, array(), t('Save settings'));
-
-
- $text_file = $this->getTestFile('text');
- $edit = array(
- 'title' => $this->randomName(),
- );
- $this->backdropPost('node/add/post', $edit, t('Save'));
- $node = $this->backdropGetNodeByTitle($edit['title']);
-
-
- $text_file = $this->getTestFile('text');
- $edit = array(
- 'files[field_' . $name . '_' . LANGUAGE_NONE . '_' . 0 . ']' => backdrop_realpath($text_file->uri),
- 'comment_body[' . LANGUAGE_NONE . '][0][value]' => $comment_body = $this->randomName(),
- );
- $this->backdropPost(NULL, $edit, t('Save'));
-
-
- preg_match('/comment-([0-9]+)/', $this->getUrl(), $matches);
- $cid = $matches[1];
-
-
- $this->backdropLogin($user);
-
- $comment = comment_load($cid);
- $comment_file = (object) $comment->{'field_' . $name}[LANGUAGE_NONE][0];
- $this->assertFileExists($comment_file, 'New file saved to disk on node creation.');
-
- $url = file_create_url($comment_file->uri);
- $this->assertNotEqual($url, NULL, 'Confirmed that the URL is valid');
- $this->backdropGet(file_create_url($comment_file->uri));
- $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
-
-
- $this->backdropLogout();
- $this->backdropGet(file_create_url($comment_file->uri));
- $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
-
-
- $this->backdropLogin($this->admin_user);
- $edit = array(
- 'status' => NODE_NOT_PUBLISHED,
- );
- $this->backdropPost('node/' . $node->nid . '/edit', $edit, t('Save'));
-
-
- $this->backdropLogin($user);
- $this->backdropGet(file_create_url($comment_file->uri));
- $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
- }
-
- }
-
- * Tests file handling with node revisions.
- */
- class FileFieldRevisionTestCase extends FileTestHelper {
-
- * 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() {
- $type_name = 'post';
- $field_name = strtolower($this->randomName());
- $this->createFileField($field_name, $type_name);
- $field = field_info_field($field_name);
- $instance = field_info_instance('node', $field_name, $type_name);
-
-
- $this->attachFileField($field_name, 'user', 'user');
-
- $test_file = $this->getTestFile('text');
-
-
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
-
-
- $node = node_load($nid, NULL, TRUE);
- $node_file_r1 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $node_vid_r1 = $node->vid;
- $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.');
-
-
- $this->replaceNodeFile($test_file, $field_name, $nid);
- $node = node_load($nid, NULL, TRUE);
- $node_file_r2 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $node_vid_r2 = $node->vid;
- $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.');
-
-
- $node = node_load($nid, $node_vid_r1, TRUE);
- $this->assertEqual($node_file_r1, (object) $node->{$field_name}[LANGUAGE_NONE][0], '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.');
-
-
-
- $this->backdropPost('node/' . $nid . '/edit', array('revision' => '1'), t('Save'));
- $node = node_load($nid, NULL, TRUE);
- $node_file_r3 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $node_vid_r3 = $node->vid;
- $this->assertEqual($node_file_r2, $node_file_r3, '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.');
-
-
- $this->backdropPost('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert'));
- $node = node_load($nid, NULL, TRUE);
- $node_file_r4 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $node_vid_r4 = $node->vid;
- $this->assertEqual($node_file_r1, $node_file_r4, '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.');
-
-
-
- $this->backdropPost('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.');
-
-
- $user = $this->backdropCreateUser();
- $user->{$field_name}[LANGUAGE_NONE][0] = (array) $node_file_r3;
- $user->save();
- $this->backdropGet('user/' . $user->uid . '/edit');
-
-
- $this->backdropPost('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.');
-
-
- user_delete($user->uid);
-
-
-
- clearstatcache();
-
-
-
- db_update('file_managed')
- ->fields(array(
- 'timestamp' => REQUEST_TIME - (BACKDROP_MAXIMUM_TEMP_FILE_AGE + 1),
- ))
- ->condition('fid', $node_file_r3->fid)
- ->execute();
- backdrop_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.');
-
-
- $this->backdropPost('node/' . $nid . '/delete', array(), t('Delete'));
-
-
- db_update('file_managed')
- ->fields(array(
- 'timestamp' => REQUEST_TIME - (BACKDROP_MAXIMUM_TEMP_FILE_AGE + 1),
- ))
- ->condition('fid', $node_file_r1->fid)
- ->execute();
- backdrop_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.');
- }
- }
-
- * Tests that formatters are working properly.
- */
- class FileFieldDisplayTestCase extends FileTestHelper {
-
- * Tests normal formatter display on node display.
- */
- function testNodeDisplay() {
- $field_name = strtolower($this->randomName());
- $type_name = 'post';
- $field_settings = array(
- 'display_field' => '1',
- 'display_default' => '1',
- );
- $instance_settings = array(
- 'description_field' => '1',
- );
- $widget_settings = array();
- $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
- $field = field_info_field($field_name);
- $instance = field_info_instance('node', $field_name, $type_name);
-
-
-
- $node = $this->backdropCreateNode(array('type' => $type_name));
- $file_formatters = array('file_default', 'file_table', 'file_url_plain', 'hidden');
- foreach ($file_formatters as $formatter) {
- $edit = array(
- "fields[$field_name][type]" => $formatter,
- );
- $this->backdropPost("admin/structure/types/manage/$type_name/display/default", $edit, t('Save'));
- $this->backdropGet('node/' . $node->nid);
- $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');
-
-
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
- $this->backdropGet('node/' . $nid . '/edit');
-
-
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $default_output = theme('file_link', array('file' => $node_file));
- $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
-
-
- $edit = array($field_name . '[' . LANGUAGE_NONE . '][0][display]' => FALSE);
- $this->backdropPost('node/' . $nid . '/edit', $edit, t('Save'));
-
- $this->assertNoRaw($default_output, 'Field is hidden when "display" option is unchecked.');
-
- }
- }
-
- * Tests various validations.
- */
- class FileFieldValidateTestCase extends FileTestHelper {
- protected $field;
- protected $node_type;
-
-
- * Tests the required property on file fields.
- */
- function testRequired() {
- $type_name = 'post';
- $field_name = strtolower($this->randomName());
- $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
- $field = field_info_field($field_name);
- $instance = field_info_instance('node', $field_name, $type_name);
-
- $test_file = $this->getTestFile('text');
-
-
- $langcode = LANGUAGE_NONE;
- $edit = array("title" => $this->randomName());
- $this->backdropPost('node/add/' . $type_name, $edit, t('Save'));
- $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required file field was empty.');
-
-
- $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->uri, '@field_name' => $field_name, '@type_name' => $type_name)));
-
- $node = node_load($nid, NULL, TRUE);
-
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $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.');
-
-
- field_delete_field($field_name);
- field_purge_batch(10);
- $this->createFileField($field_name, $type_name, array('cardinality' => FIELD_CARDINALITY_UNLIMITED), array('required' => '1'));
-
-
- $edit = array('title' => $this->randomName());
- $this->backdropPost('node/add/' . $type_name, $edit, t('Save'));
- $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required multiple value file field was empty.');
-
-
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $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.');
-
-
- field_delete_field($field_name);
- }
-
-
- * Tests the max file size validator.
- */
- function testFileMaxSize() {
- $type_name = 'post';
- $field_name = strtolower($this->randomName());
- $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
- $field = field_info_field($field_name);
- $instance = field_info_instance('node', $field_name, $type_name);
-
- $small_file = $this->getTestFile('text', 131072);
- $large_file = $this->getTestFile('text', 1310720);
-
-
- $sizes = array(
- '1M' => 1048576,
- '1024K' => 1048576,
- '1048576' => 1048576,
- );
-
- foreach ($sizes as $max_filesize => $file_limit) {
-
- $this->updateFileField($field_name, $type_name, array('max_filesize' => $max_filesize));
- $instance = field_info_instance('node', $field_name, $type_name);
-
-
- $nid = $this->uploadNodeFile($small_file, $field_name, $type_name);
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) under the max limit (%maxsize).', array('%filesize' => format_size($small_file->filesize), '%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->filesize), '%maxsize' => $max_filesize)));
-
-
- $nid = $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->filesize), '%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->filesize), '%maxsize' => $max_filesize)));
- }
-
-
- $this->updateFileField($field_name, $type_name, array('max_filesize' => ''));
-
-
- $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->filesize))));
- $this->assertFileEntryExists($node_file, format_string('File entry exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->filesize))));
-
-
- field_delete_field($field_name);
- }
-
-
- * Tests file extension checking.
- */
- function testFileExtension() {
- $type_name = 'post';
- $field_name = strtolower($this->randomName());
- $this->createFileField($field_name, $type_name);
- $field = field_info_field($field_name);
- $instance = field_info_instance('node', $field_name, $type_name);
-
- $test_file = $this->getTestFile('image');
- list(, $test_file_extension) = explode('.', $test_file->filename);
-
-
- $this->updateFileField($field_name, $type_name, array('file_extensions' => ''));
-
-
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $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.');
-
-
- $this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt'));
-
-
- $nid = $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.');
-
-
- $this->updateFileField($field_name, $type_name, array('file_extensions' => "txt $test_file_extension"));
-
-
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $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.');
-
-
- field_delete_field($field_name);
- }
-
-
- * Tests default display of File Field.
- */
- function testDefaultFileFieldDisplay() {
- $field_name = strtolower($this->randomName());
- $type_name = 'post';
- $field_settings = array(
- 'display_field' => '1',
- 'display_default' => '0',
- );
- $instance_settings = array(
- 'description_field' => '1',
- );
- $widget_settings = array();
- $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
- $field = field_info_field($field_name);
- $instance = field_info_instance('node', $field_name, $type_name);
-
- $test_file = $this->getTestFile('text');
-
-
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
-
- $this->backdropGet('node/' . $nid . '/edit');
- $this->assertFieldByXPath('//input[@type="checkbox" and @name="' . $field_name . '[und][0][display]"]', NULL, 'Default file display checkbox field exists.');
- $this->assertFieldByXPath('//input[@type="checkbox" and @name="' . $field_name . '[und][0][display]" and not(@checked)]', NULL, 'Default file display is off.');
- }
- }
-
- * Tests that files are uploaded to proper locations.
- */
- class FileFieldPathTestCase extends FileTestHelper {
-
- * Tests the normal formatter display on node display.
- */
- function testUploadPath() {
- $field_name = strtolower($this->randomName());
- $type_name = 'post';
- $field = $this->createFileField($field_name, $type_name);
- $test_file = $this->getTestFile('text');
-
-
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
-
-
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $this->assertPathMatch('public://' . $test_file->filename, $node_file->uri, format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->uri)));
-
-
- $field = $this->updateFileField($field_name, $type_name, array('file_directory' => 'foo/bar/baz'));
-
-
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
-
-
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
- $this->assertPathMatch('public://foo/bar/baz/' . $test_file->filename, $node_file->uri, format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->uri)));
-
-
-
- $field = $this->updateFileField($field_name, $type_name, array('file_directory' => '[current-user:uid]/[current-user:name]'));
-
-
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
-
-
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
-
-
- $data = array('user' => $this->admin_user);
- $subdirectory = token_replace('[user:uid]/[user:name]', $data);
- $this->assertPathMatch('public://' . $subdirectory . '/' . $test_file->filename, $node_file->uri, format_string('The file %file was uploaded to the correct path with token replacements.', array('%file' => $node_file->uri)));
- }
-
-
- * Asserts that a file is uploaded to the right location.
- *
- * @param $expected_path
- * The location where the file is expected to be uploaded. Duplicate file
- * names to not need to be taken into account.
- * @param $actual_path
- * Where the file was actually uploaded.
- * @param $message
- * The message to display with this assertion.
- */
- function assertPathMatch($expected_path, $actual_path, $message) {
-
-
- $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);
- }
- }
-
- * Tests the file token replacement in strings.
- */
- class FileTokenReplaceTestCase extends FileTestHelper {
-
- * Creates a file, then tests the tokens generated from it.
- */
- function testFileTokenReplacement() {
- global $language;
-
-
- $type_name = 'post';
- $field_name = 'field_' . strtolower($this->randomName());
- $this->createFileField($field_name, $type_name);
- $field = field_info_field($field_name);
- $instance = field_info_instance('node', $field_name, $type_name);
-
- $test_file = $this->getTestFile('text');
-
- $filename = backdrop_dirname($test_file->uri) . '/текстовый файл.txt';
- $test_file = file_copy($test_file, $filename);
-
-
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
-
-
- $node = node_load($nid, NULL, TRUE);
- $file = file_load($node->{$field_name}[LANGUAGE_NONE][0]['fid']);
-
-
- $tests = array();
- $tests['[file:fid]'] = $file->fid;
- $tests['[file:name]'] = check_plain($file->filename);
- $tests['[file:path]'] = check_plain($file->uri);
- $tests['[file:mime]'] = check_plain($file->filemime);
- $tests['[file:size]'] = format_size($file->filesize);
- $tests['[file:url]'] = check_plain(file_create_url($file->uri));
- $tests['[file:timestamp]'] = format_date($file->timestamp, 'medium', '', NULL, $language->langcode);
- $tests['[file:timestamp:short]'] = format_date($file->timestamp, 'short', '', NULL, $language->langcode);
- $tests['[file:owner]'] = check_plain(user_format_name($this->admin_user));
- $tests['[file:owner:uid]'] = $file->uid;
-
-
- $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
-
- foreach ($tests as $input => $expected) {
- $output = token_replace($input, array('file' => $file), array('language' => $language));
- $this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', array('%token' => $input)));
- }
-
-
- $tests['[file:name]'] = $file->filename;
- $tests['[file:path]'] = $file->uri;
- $tests['[file:mime]'] = $file->filemime;
- $tests['[file:size]'] = format_size($file->filesize);
-
- foreach ($tests as $input => $expected) {
- $output = token_replace($input, array('file' => $file), array('language' => $language, 'sanitize' => FALSE));
- $this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input)));
- }
- }
- }
-
- * Tests file access on private nodes.
- */
- class FilePrivateTestCase extends FileTestHelper {
- function setUp() {
- parent::setUp(array('node_access_test', 'field_test'));
- node_access_rebuild();
- state_set('node_access_test_private', TRUE);
-
-
- config_set('system.core', 'cache', 0);
- }
-
-
- * Tests file access for file uploaded to a private node.
- */
- function testPrivateFile() {
-
-
-
-
- $type_name = 'page';
- $field_name = strtolower($this->randomName());
- $this->createFileField($field_name, $type_name, array('uri_scheme' => 'private'));
-
-
- $no_access_field_name = 'field_no_view_access';
- $this->createFileField($no_access_field_name, $type_name, array('uri_scheme' => 'private'));
-
- $test_file = $this->getTestFile('text');
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE));
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
-
- $this->backdropGet(file_create_url($node_file->uri));
- $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
- $this->backdropLogout();
- $this->backdropGet(file_create_url($node_file->uri));
- $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
-
-
- $this->backdropLogin($this->admin_user);
- $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE));
- $node = node_load($nid, NULL, TRUE);
- $node_file = (object) $node->{$no_access_field_name}[LANGUAGE_NONE][0];
-
- $this->backdropGet(file_create_url($node_file->uri));
- $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.');
-
-
-
- $edit = array();
- $edit['title'] = $this->randomName(8);
- $edit[$field_name . '[' . LANGUAGE_NONE . '][0][fid]'] = $node_file->fid;
- $this->backdropPost('node/add/page', $edit, t('Save'));
- $new_node = $this->backdropGetNodeByTitle($edit['title']);
- $this->assertTrue(!empty($new_node), 'Node was created.');
- $this->assertUrl('node/' . $new_node->nid);
- $this->assertNoRaw($node_file->filename, 'File without view field access permission does not appear after attempting to attach it to a new node.');
- $this->backdropGet(file_create_url($node_file->uri));
- $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission after attempting to attach it to a new node.');
-
-
-
- $this->backdropLogout();
- user_role_grant_permissions(BACKDROP_ANONYMOUS_ROLE, array(
- "create $type_name content",
- 'access content',
- ));
- $test_file = $this->getTestFile('text');
- $this->backdropGet('node/add/' . $type_name);
- $edit = array('files[' . $field_name . '_' . LANGUAGE_NONE . '_0]' => backdrop_realpath($test_file->uri));
- $this->backdropPost(NULL, $edit, t('Upload'));
- $files = file_load_multiple(array(), array('uid' => 0));
- $this->assertEqual(1, count($files), 'Loaded one anonymous file.');
- $file = end($files);
- $this->assertNotEqual($file->status, FILE_STATUS_PERMANENT, 'File is temporary.');
- $usage = file_usage_list($file);
- $this->assertFalse($usage, 'No file usage found.');
- $file_url = file_create_url($file->uri);
- $this->backdropGet($file_url);
- $this->assertResponse(200, 'Confirmed that the anonymous uploader has access to the temporary file.');
-
- $this->curlClose();
- $this->cookies = array();
- $this->backdropGet($file_url);
- $this->assertResponse(403, 'Confirmed that another anonymous user cannot access the temporary file.');
-
-
-
- $test_file = $this->getTestFile('text');
- $this->backdropGet('node/add/' . $type_name);
- $edit = array();
- $edit['title'] = $this->randomName();
- $edit['files[' . $field_name . '_' . LANGUAGE_NONE . '_0]'] = backdrop_realpath($test_file->uri);
- $this->backdropPost(NULL, $edit, t('Save'));
- $new_node = $this->backdropGetNodeByTitle($edit['title']);
- $file = file_load($new_node->{$field_name}[LANGUAGE_NONE][0]['fid']);
- $this->assertEqual($file->status, FILE_STATUS_PERMANENT, 'File is permanent.');
- $usage = file_usage_list($file);
- $this->assertTrue($usage, 'File usage found.');
- $file_url = file_create_url($file->uri);
- $this->backdropGet($file_url);
- $this->assertResponse(200, 'Confirmed that the anonymous uploader has access to the permanent file that is referenced by a published node.');
-
- $this->curlClose();
- $this->cookies = array();
- $this->backdropGet($file_url);
- $this->assertResponse(200, 'Confirmed that another anonymous user also has access to the permanent file that is referenced by a published node.');
-
-
-
-
-
- $test_file = $this->getTestFile('text');
- $this->backdropGet('node/add/' . $type_name);
- $edit = array();
- $edit['title'] = $this->randomName();
- $edit['files[' . $field_name . '_' . LANGUAGE_NONE . '_0]'] = backdrop_realpath($test_file->uri);
- $this->backdropPost(NULL, $edit, t('Save'));
- $new_node = $this->backdropGetNodeByTitle($edit['title']);
- $new_node->status = NODE_NOT_PUBLISHED;
- node_save($new_node);
- $file = file_load($new_node->{$field_name}[LANGUAGE_NONE][0]['fid']);
- $this->assertEqual($file->status, FILE_STATUS_PERMANENT, 'File is permanent.');
- $usage = file_usage_list($file);
- $this->assertTrue($usage, 'File usage found.');
- $file_url = file_create_url($file->uri);
- $this->backdropGet($file_url);
- $this->assertResponse(403, 'Confirmed that the anonymous uploader cannot access the permanent file when it is referenced by an unpublished node.');
-
- $this->curlClose();
- $this->cookies = array();
- $this->backdropGet($file_url);
- $this->assertResponse(403, 'Confirmed that another anonymous user cannot access the permanent file when it is referenced by an unpublished node.');
- }
-
-
- * Tests file access for private nodes when file download access is granted.
- */
- function testPrivateFileDownloadAccessGranted() {
-
-
- $test_file = $this->getTestFile('text');
- $uri = file_unmanaged_move($test_file->uri, 'private://');
- $file_url = file_create_url($uri);
- $this->backdropGet($file_url);
- $this->assertResponse(403, 'Access is not granted to an arbitrary private file by default.');
- state_set('file_module_test_grant_download_access', TRUE);
- $this->backdropGet($file_url);
- $this->assertResponse(200, 'Access is granted to an arbitrary private file after a module grants access to all private files in hook_file_download().');
-
-
- $type_name = 'page';
- $field_name = strtolower($this->randomName());
- $this->createFileField($field_name, $type_name, array('uri_scheme' => 'private'));
- $test_file = $this->getTestFile('text');
- $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => FALSE));
- $node = node_load($nid, NULL, TRUE);
- $file_url = file_create_url($node->{$field_name}[LANGUAGE_NONE][0]['uri']);
-
-
-
-
-
- $node->status = NODE_NOT_PUBLISHED;
- node_save($node);
- $this->backdropLogin($this->admin_user);
- $this->backdropGet("node/$nid");
- $this->assertResponse(200, 'Administrator can access the unpublished node.');
- $this->backdropGet($file_url);
- $this->assertResponse(200, 'Administrator can download the file attached to the unpublished node.');
- $this->backdropLogOut();
- $this->backdropGet("node/$nid");
- $this->assertResponse(403, 'Anonymous user cannot access the unpublished node.');
- $this->backdropGet($file_url);
- $this->assertResponse(403, 'Anonymous user cannot download the file attached to the unpublished node.');
-
-
-
- $node->status = NODE_PUBLISHED;
- node_save($node);
- $this->backdropLogin($this->admin_user);
- $this->backdropGet("node/$nid");
- $this->assertResponse(200, 'Administrator can access the published node.');
- $this->backdropGet($file_url);
- $this->assertResponse(200, 'Administrator can download the file attached to the published node.');
- $this->backdropLogOut();
- $this->backdropGet("node/$nid");
- $this->assertResponse(200, 'Anonymous user can access the published node.');
- $this->backdropGet($file_url);
- $this->assertResponse(200, 'Anonymous user can download the file attached to the published node.');
-
-
-
-
- $node->private = TRUE;
- node_save($node);
- $this->backdropLogin($this->admin_user);
- $this->backdropGet("node/$nid");
- $this->assertResponse(200, 'Administrator can access the private node.');
- $this->backdropGet($file_url);
- $this->assertResponse(200, 'Administrator can download the file attached to the private node.');
- $this->backdropLogOut();
- $this->backdropGet("node/$nid");
- $this->assertResponse(403, 'Anonymous user cannot access the private node.');
- $this->backdropGet($file_url);
- $this->assertResponse(403, 'Anonymous user cannot download the file attached to the private node.');
- }
- }
-
- * Confirm that file field submissions work correctly for anonymous visitors.
- */
- class FileFieldAnonymousSubmission extends FileTestHelper {
-
- function setUp() {
- parent::setUp();
-
-
- user_role_grant_permissions(BACKDROP_ANONYMOUS_ROLE, array(
- 'create page content',
- 'access content',
- 'create url aliases'
- ));
- }
-
-
- * Tests the basic node submission for an anonymous visitor.
- */
- function testAnonymousNode() {
- $bundle_label = 'Page';
- $node_title = 'Test page';
-
-
- $this->backdropGet('node/add/page');
- $this->assertResponse(200, 'Loaded the page node form.');
- $this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));
-
- $edit = array(
- 'title' => $node_title,
- 'body[und][0][value]' => 'Test page',
- 'body[und][0][format]' => 'filtered_html',
- 'path[auto]' => FALSE,
- 'path[alias]' => '',
- );
- $this->backdropPost(NULL, $edit, t('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.
- */
- function testAnonymousNodeWithFile() {
- $type_name = 'page';
- $bundle_label = 'Page';
- $node_title = 'Test page';
-
- $field_name = strtolower($this->randomName());
- $this->createFileField($field_name, $type_name);
-
-
- $this->backdropGet('node/add/' . $type_name);
- $this->assertResponse(200, 'Loaded the page node form.');
- $this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));
-
-
- $test_file = $this->getTestFile('text');
-
-
- $edit = array(
- 'title' => $node_title,
- 'body[und][0][value]' => 'Test page',
- 'body[und][0][format]' => 'filtered_html',
- 'files[' . $field_name .'_und_0]' => backdrop_realpath($test_file->uri),
- 'path[auto]' => FALSE,
- 'path[alias]' => '',
- );
- $this->backdropPost(NULL, $edit, t('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->assertEqual($node->{$field_name}[LANGUAGE_NONE][0]['filename'], $test_file->filename, 'The file was uploaded successfully.');
- }
- }
-
-
- * Tests file submission for an anonymous visitor with a missing node title.
- */
- function testAnonymousNodeWithFileWithoutTitle() {
- $this->backdropLogout();
- $this->_testNodeWithFileWithoutTitle();
- }
-
-
- * Tests file submission for an authenticated user with a missing node title.
- */
- function testAuthenticatedNodeWithFileWithoutTitle() {
- $admin_user = $this->backdropCreateUser(array(
- 'bypass node access',
- 'access content overview',
- 'administer nodes',
- 'create url aliases',
- ));
- $this->backdropLogin($admin_user);
- $this->_testNodeWithFileWithoutTitle();
- }
-
-
- * Helper method to test file submissions with missing node titles.
- */
- protected function _testNodeWithFileWithoutTitle() {
- $type_name = 'page';
- $bundle_label = 'Page';
- $node_title = 'Test page';
-
- $field_name = strtolower($this->randomName());
- $this->createFileField($field_name, $type_name);
-
-
- $this->backdropGet('node/add/page');
- $this->assertResponse(200, 'Loaded the page node form.');
- $this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));
-
-
- $test_file = $this->getTestFile('text');
-
-
- $edit = array(
- 'body[und][0][value]' => 'Test page',
- 'body[und][0][format]' => 'filtered_html',
- 'files[' . $field_name .'_und_0]' => backdrop_realpath($test_file->uri),
- 'path[auto]' => FALSE,
- 'path[alias]' => '',
- );
- $this->backdropPost(NULL, $edit, t('Save'));
- $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(t('!name field is required.', array('!name' => t('Title'))));
-
-
-
- $edit = array(
- 'title' => $node_title,
- );
- $this->backdropPost(NULL, $edit, t('Save'));
-
-
- $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->assertEqual($node->{$field_name}[LANGUAGE_NONE][0]['filename'], $test_file->filename, 'The file was uploaded successfully.');
- }
- }
-
- }
-
- * Tests file type classification functionality.
- */
- class FileFileTypeClassificationTestCase extends BackdropWebTestCase {
-
- function setUp() {
- parent::setUp();
- }
-
-
- * Test that existing files are properly classified by file type.
- */
- function testFileTypeClassification() {
-
- $file = current($this->backdropGetTestFiles('text'));
- $text_file = new File((array) $file);
- file_save($text_file);
-
- $file = current($this->backdropGetTestFiles('image'));
- $image_file = new File((array) $file);
- file_save($image_file);
-
-
-
-
- $file_type = $this->getFileType($text_file);
- $this->assertEqual($file_type['type'], 'document', t('The text file was properly assigned the Document file type.'));
- $file_type = $this->getFileType($image_file);
- $this->assertEqual($file_type['type'], 'image', t('The image file was properly assigned the Image file type.'));
- }
-
-
- * Get the file type of a given file.
- *
- * @param $file
- * A file object.
- *
- * @return
- * The file's file type as a string.
- */
- function getFileType($file) {
- $type = db_select('file_managed', 'fm')
- ->fields('fm', array('type'))
- ->condition('fid', $file->fid, '=')
- ->execute()
- ->fetchAssoc();
-
- return $type;
- }
- }
-
- * Tests basic file entity functionality.
- */
- class FileUnitTestCase extends FileTestHelper {
-
-
- * Regression tests for core issue https://www.drupal.org/node/1239376.
- */
- function testMimeTypeMappings() {
- $tests = array(
- 'public://test.ogg' => 'audio/ogg',
- 'public://test.mkv' => 'video/x-m4v',
- 'public://test.mka' => 'audio/x-matroska',
- 'public://test.mkv' => 'video/x-matroska',
- 'public://test.webp' => 'image/webp',
- );
- foreach ($tests as $input => $expected) {
- $this->assertEqual(file_get_mimetype($input), $expected);
- }
- }
-
-
- * Tests basic file entity properties.
- */
- function testFile() {
-
- $file = $this->getTestFile('text');
- $file->uid = 1;
- $file->status = FILE_STATUS_PERMANENT;
- $file = new File((array) $file);
- file_save($file);
-
-
- $ids = entity_extract_ids('file', $file);
- $this->assertIdentical($ids, array($file->fid, NULL, 'document'));
-
-
- $uri = entity_uri('file', $file);
- $this->assertEqual($uri['path'], $file->uri);
- }
-
-
- * Tests storing image height and width as file metadata.
- */
- function testImageDimensions() {
-
- $file = current($this->backdropGetTestFiles('image'));
- $image_file = new File((array) $file);
- file_save($image_file);
- $this->assertTrue(isset($image_file->metadata['height']), 'Image height retrieved on file_save() for an image file.');
- $this->assertTrue(isset($image_file->metadata['width']), 'Image width retrieved on file_save() for an image file.');
-
- $file = current($this->backdropGetTestFiles('text'));
- $text_file = new File((array) $file);
- file_save($text_file);
- $this->assertFalse(isset($text_file->metadata['height']), 'No image height retrieved on file_save() for an text file.');
- $this->assertFalse(isset($text_file->metadata['width']), 'No image width retrieved on file_save() for an text file.');
-
-
-
- entity_get_controller('file')->resetCache();
-
- $file = file_load($image_file->fid);
- $this->assertTrue(isset($file->metadata['height']), 'Image dimensions retrieved on file_load() for an image file.');
- $this->assertTrue(isset($file->metadata['width']), 'Image dimensions retrieved on file_load() for an image file.');
-
- $this->assertEqual($file->metadata['height'], $image_file->metadata['height'], 'Loaded image height is equal to saved image height.');
- $this->assertEqual($file->metadata['width'], $image_file->metadata['width'], 'Loaded image width is equal to saved image width.');
-
- $file = file_load($text_file->fid);
- $this->assertFalse(isset($file->metadata['height']), 'No image height retrieved on file_load() for an text file.');
- $this->assertFalse(isset($file->metadata['width']), 'No image width retrieved on file_load() for an text file.');
-
-
-
- $height = $image_file->metadata['width'] / 2;
- $width = $image_file->metadata['height'] / 2;
- $image = image_load($image_file->uri);
- image_resize($image, $width, $height);
- image_save($image);
- file_save($image_file);
-
- $this->assertEqual($image_file->metadata['height'], $height, 'Image file height updated by file_save().');
- $this->assertEqual($image_file->metadata['width'], $width, 'Image file width updated by file_save().');
-
-
- entity_get_controller('file')->resetCache();
-
- $file = file_load($image_file->fid);
- $this->assertEqual($file->metadata['height'], $height, 'Updated image height retrieved by file_load().');
- $this->assertEqual($file->metadata['width'], $width, 'Updated image width retrieved by file_load().');
-
-
- $this->assertTrue(db_query('SELECT COUNT(*) FROM {file_metadata} WHERE fid = :fid', array(':fid' => $file->fid))->fetchField(), 'Row exists in {file_metadata} before file_delete().');
- file_delete($file->fid);
- $this->assertFalse(db_query('SELECT COUNT(*) FROM {file_metadata} WHERE fid = :fid', array(':fid' => $file->fid))->fetchField(), 'Row deleted in {file_metadata} on file_delete().');
- }
- }
-
- * Tests editing existing file entities.
- */
- class FileEditTestCase extends FileTestHelper {
- protected $web_user;
- protected $admin_user;
-
- function setUp() {
- parent::setUp();
-
-
- $this->web_user = $this->backdropCreateUser(array('edit own document files', 'manage files', 'create files','access file overview'));
-
- }
-
-
- * Check file edit functionality.
- */
- function testFileEdit() {
- $this->backdropLogin($this->web_user);
- $name_key = "filename";
-
- $file = $this->createFile(array('type' => 'image'));
-
-
- $file = $this->getFileByFilename($file->filename);
- $this->assertTrue($file, t('File found in database.'));
-
-
- $this->backdropGet('admin/content/files');
- $this->clickLink(t('Manage'));
- $edit_url = url("file/$file->fid/manage", array('absolute' => TRUE));
- $actual_url = strtok($this->getURL(), '?');
- $this->assertEqual($edit_url, $actual_url, t('On edit page.'));
-
-
- $this->assertFieldByName($name_key, $file->filename, t('Name field displayed.'));
-
-
- $this->assertNoFieldByName('op', t('Delete'), 'Delete button not found.');
-
-
- $edit = array();
- $edit[$name_key] = $this->randomName(8);
-
- $this->backdropPost(NULL, $edit, t('Save'));
-
-
- $this->assertText($edit[$name_key], t('Name displayed.'));
- }
-
- }
-
- * Tests creating new file entities through the file upload wizard.
- */
- class FileUploadWizardTestCase extends FileTestHelper {
-
- function setUp() {
- parent::setUp();
-
- $this->private_files_directory = config_get('system.core', 'file_private_path');
-
-
- config_set('system.core', 'file_private_path', '');
-
- $web_user = $this->backdropCreateUser(array(
- 'create files',
- 'view files',
- 'view own private files',
- 'manage files',
- ));
- $this->backdropLogin($web_user);
- }
-
-
- * Test the basic file upload wizard functionality.
- */
- function testFileUploadWizardBasic() {
- $test_file = $this->getTestFile('text');
-
-
- $edit = array();
- $edit['files[upload]'] = backdrop_realpath($test_file->uri);
- $this->backdropPost('file/add', $edit, t('Next'));
-
-
- $fid = $this->getLastFileId();
- $file = file_load($fid);
- $this->assertTrue($file, t('File found in database.'));
-
-
- $this->assertRaw(t('@type %name was uploaded.', array('@type' => 'Document', '%name' => $file->filename)), t('Document file uploaded.'));
- }
-
-
- * Test the file upload wizard type step.
- */
- function testFileUploadWizardTypes() {
- $test_file = $this->getTestFile('text');
-
-
- $this->createFileType(array('type' => 'document1', 'name' => 'Document 1', 'mimetypes' => array('text/plain')));
- $this->createFileType(array('type' => 'document2', 'name' => 'Document 2', 'mimetypes' => array('text/plain')));
-
-
- $edit = array();
- $edit['files[upload]'] = backdrop_realpath($test_file->uri);
- $this->backdropPost('file/add', $edit, t('Next'));
-
-
- $edit = array();
- $edit['type'] = 'document2';
- $this->backdropPost(NULL, $edit, t('Next'));
-
-
- $fid = $this->getLastFileId();
- $file = file_load($fid);
- $this->assertTrue($file, t('File found in database.'));
-
-
- $this->assertRaw(t('@type %name was uploaded.', array('@type' => 'Document 2', '%name' => $file->filename)), t('Document 2 file uploaded.'));
- }
-
-
- * Test the file upload wizard scheme step.
- */
- function testFileUploadWizardSchemes() {
- $test_file = $this->getTestFile('text');
-
-
- config_set('system.core', 'file_private_path', $this->private_files_directory);
-
-
- $edit = array();
- $edit['files[upload]'] = backdrop_realpath($test_file->uri);
- $this->backdropPost('file/add', $edit, t('Next'));
-
-
- $edit = array();
- $edit['scheme'] = 'private';
- $this->backdropPost(NULL, $edit, t('Next'));
-
-
- $fid = $this->getLastFileId();
- $file = file_load($fid);
- $this->assertTrue($file, t('File found in database.'));
-
-
- $this->assertRaw(t('@type %name was uploaded.', array('@type' => 'Document', '%name' => $file->filename)), t('Document file uploaded privately.'));
- }
-
-
- * Test the file upload wizard field step.
- */
- function testFileUploadWizardFields() {
- $test_file = $this->getTestFile('image');
- $filename = $this->randomName();
- $alt = $this->randomName();
- $title = $this->randomName();
-
-
-
-
- $field = array('field_name' => 'field_file_image_alt_text', 'type' => 'text');
- field_create_field($field);
- $instance = array(
- 'field_name' => 'field_file_image_alt_text',
- 'entity_type' => 'file',
- 'bundle' => 'image',
- 'label' => 'Alt',
- );
- field_create_instance($instance);
-
- $field = array('field_name' => 'field_file_image_title_text', 'type' => 'text');
- field_create_field($field);
- $instance = array(
- 'field_name' => 'field_file_image_title_text',
- 'entity_type' => 'file',
- 'bundle' => 'image',
- 'label' => 'Title',
- );
- field_create_instance($instance);
-
-
- $edit = array();
- $edit['files[upload]'] = backdrop_realpath($test_file->uri);
- $this->backdropPost('file/add', $edit, t('Next'));
-
-
- $edit = array();
- $edit['filename'] = $filename;
- $edit['field_file_image_alt_text[' . LANGUAGE_NONE . '][0][value]'] = $alt;
- $edit['field_file_image_title_text[' . LANGUAGE_NONE . '][0][value]'] = $title;
- $this->backdropPost(NULL, $edit, t('Save'));
-
-
- $this->assertRaw(t('@type %name was uploaded.', array('@type' => 'Image', '%name' => $filename)), t('Image file uploaded.'));
-
-
- $fid = $this->getLastFileId();
- $file = file_load($fid);
- $this->assertTrue($file, t('File found in database.'));
-
-
- $alt_value = $file->field_file_image_alt_text['und'][0]['value'];
- $this->assertEqual($alt_value, $alt, t('Alt text was stored as field data.'));
- $title_value = $file->field_file_image_title_text['und'][0]['value'];
- $this->assertEqual($title_value, $title, t('Title text was stored as field data.'));
- }
-
-
- * Test skipping each of the file upload wizard steps.
- */
- function testFileUploadWizardStepSkipping() {
- $test_file = $this->getTestFile('image');
- $filename = $this->randomName();
-
-
- config_set('system.core', 'file_private_path', $this->private_files_directory);
-
- $this->createFileType(array('type' => 'image1', 'name' => 'Image 1', 'mimetypes' => array('image/jpeg', 'image/gif', 'image/png', 'image/tiff')));
- $this->createFileType(array('type' => 'image2', 'name' => 'Image 2', 'mimetypes' => array('image/jpeg', 'image/gif', 'image/png', 'image/tiff')));
-
- $field_name = backdrop_strtolower($this->randomName() . '_field_name');
- $field = array('field_name' => $field_name, 'type' => 'text');
- field_create_field($field);
- $instance = array(
- 'field_name' => $field_name,
- 'entity_type' => 'file',
- 'bundle' => 'image2',
- 'label' => $this->randomName() . '_label',
- );
- field_create_instance($instance);
-
-
- $debug_i = 0;
- foreach (array('types', 'schemes', 'fields') as $skipped_step) {
-
- switch ($skipped_step) {
- case 'types':
- config_set('file.settings', 'upload_wizard_skip_file_type', TRUE);
- break;
- case 'schemes':
- config_set('file.settings', 'upload_wizard_skip_scheme', TRUE);
- break;
- case 'fields':
- config_set('file.settings', 'upload_wizard_skip_fields', TRUE);
- break;
- }
-
-
- debug('Step 0: Upload a basic image file.');
- $edit = array();
- $edit['files[upload]'] = backdrop_realpath($test_file->uri);
- $this->backdropPost('file/add', $edit, t('Next'));
-
- $debug_i++;
- debug('Step ' . $debug_i . ': ' . $skipped_step);
-
-
- if ($skipped_step != 'types') {
- debug('Step 1: File type selection.');
- $this->assertText('File type', 'Types step confirmed.');
- $edit = array();
- $edit['type'] = 'image2';
- $this->backdropPost(NULL, $edit, t('Next'));
- }
- else{
- debug('Skipping types');
- }
-
-
- if ($skipped_step != 'schemes') {
- debug('Step 2: Scheme selection.');
- $this->assertText('Private local files', 'Schemes step confirmed.');
- $edit = array();
- $edit['scheme'] = 'private';
- $this->backdropPost(NULL, $edit, t('Next'));
- }
- else {
- debug('Skipping schemes');
- }
-
-
- if ($skipped_step != 'fields') {
-
-
-
- if ($skipped_step != 'types') {
- debug('Step 3: Attached fields.');
- $this->assertText('Configure file fields', 'Fields step confirmed.');
- $edit = array();
- $edit['filename'] = $filename;
- $edit[$field_name . '[' . LANGUAGE_NONE . '][0][value]'] = $this->randomName();
- $this->backdropPost(NULL, $edit, t('Save'));
- }
- }
- else {
- debug('Skipping fields');
- }
-
-
- $fid = $this->getLastFileId();
- $file = file_load($fid);
- $this->assertTrue($file, t('File found in database.'));
-
-
- $type = file_type_load($file->type);
-
- $this->assertRaw(t('@type %name was uploaded.', array('@type' => $type->name, '%name' => $file->filename)), t('Image file uploaded.'));
-
-
- $config = config('file.settings');
- $config->set('upload_wizard_skip_file_type', FALSE);
- $config->set('upload_wizard_skip_scheme', FALSE);
- $config->set('upload_wizard_skip_fields', FALSE);
- $config->save();
- }
- }
- }
-
- * Test file administration page functionality.
- */
- class FileAdminTestCase extends FileTestHelper {
- function setUp() {
- parent::setUp();
-
-
-
-
- $roles = user_roles();
- foreach ($roles as $rid => $role) {
- user_role_revoke_permissions($rid, array('view files'));
- }
-
-
- $this->backdropCreateContentType(array('type' => 'page', 'name' => 'Page'));
- $this->backdropCreateContentType(array('type' => 'post', 'name' => 'Post'));
-
- $this->base_user_1 = $this->backdropCreateUser(array('access file overview'));
- $this->base_user_2 = $this->backdropCreateUser(array('access file overview', 'delete files'));
- $this->base_user_3 = $this->backdropCreateUser(array('access file overview', 'delete files', 'manage files'));
-
- }
-
-
- * Tests that the table sorting works on the files admin pages.
- */
- function testFilesAdminSort() {
- $this->backdropLogin($this->admin_user);
- $i = 0;
- foreach (array('dd', 'aa', 'DD', 'bb', 'cc', 'CC', 'AA', 'BB') as $prefix) {
- $this->createFile(array('filepath' => $prefix . $this->randomName(6), 'timestamp' => $i));
- $i++;
- }
-
-
- $files_query = db_select('file_managed', 'fm')
- ->fields('fm', array('fid'))
- ->orderBy('timestamp', 'DESC')
- ->execute()
- ->fetchCol();
-
- $files_form = array();
- $this->backdropGet('admin/content/files');
- foreach ($this->xpath('//table/tbody/tr/td/div/input/@value') as $input) {
- $files_form[] = $input;
- }
- $this->assertEqual($files_query, $files_form, 'Files are sorted in the form according to the default query.');
-
-
-
- $files_query = db_select('file_managed', 'fm')
- ->fields('fm', array('fid'))
- ->orderBy('filename')
- ->execute()
- ->fetchCol();
-
- $files_form = array();
- $this->backdropGet('admin/content/files', array('query' => array('sort' => 'asc', 'order' => 'filename')));
- foreach ($this->xpath('//table/tbody/tr/td/div/input/@value') as $input) {
- $files_form[] = $input;
- }
- $this->assertEqual($files_query, $files_form, 'Files are sorted in the form the same as they are in the query.');
- }
-
-
- * Tests file overview with different user permissions.
- */
- function testFileAdminPages() {
- $this->backdropLogin($this->admin_user);
-
-
- $field_name = strtolower($this->randomName());
- $type_name = 'post';
- $this->createFileField($field_name, $type_name, array(), array('file_extensions' => ''));
-
-
- $files = array();
- $files['file_1'] = $this->getTestFile('text');
- $files['file_2'] = $this->getTestFile('text', 131072);
- $files['file_3'] = $this->getTestFile('text', 1310720);
- $files['file_4'] = $this->getTestFile('image', 125);
- $files['file_5'] = $this->getTestFile('image', 183);
- $files['file_6'] = $this->getTestFile('image', 1885);
-
- foreach ($files as $file) {
-
- $nid = $this->uploadNodeFile($file, $field_name, $type_name);
- sleep(1);
- }
-
-
- $files_query = db_select('file_managed', 'f')
- ->fields('f', array('fid'))
- ->orderBy('timestamp', 'DESC')
- ->execute()
- ->fetchCol();
-
-
- $files = array();
- foreach ($files_query as $fid) {
- $files[$fid] = file_load($fid);
- }
-
-
- $edit[$field_name . '[und][0][fid]'] = $fid;
- $this->backdropPost('node/' . $nid . '/edit', $edit, 'Save');
-
- $files_list = array();
- $this->backdropGet('admin/content/files');
- foreach ($this->xpath('//table/tbody/tr/td/div/input/@value') as $input) {
- $files_list[] = (string) $input;
- }
- $this->assertEqual($files_query, $files_list, 'Files correctly sorted by timestamp, by default.');
-
-
- $files_query = db_select('file_managed', 'f')
- ->fields('f', array('fid'))
- ->orderBy('filesize')
- ->execute()
- ->fetchCol();
-
- $files_list = array();
- $this->backdropGet('admin/content/files', array('query' => array('sort' => 'asc', 'order' => 'filesize')));
- foreach ($this->xpath('//table/tbody/tr/td/div/input/@value') as $input) {
- $files_list[] = $input;
- }
- $this->assertEqual($files_query, $files_list, 'Files correctly sorted by filesize.');
-
-
- $index = 0;
- foreach ($files as $file) {
- $this->assertLinkByHref('file/' . $file->fid . '/delete');
-
- $this->assertFieldByName('bulk_form[' . $index . ']', '', 'Bulk operations found.');
- $index++;
- }
-
-
- $this->backdropLogout();
- $this->backdropLogin($this->base_user_1);
- $this->backdropGet('admin/content/files');
- $this->assertResponse(200);
- foreach ($files as $file) {
- $this->assertNoLinkByHref('file/' . $file->fid . '/delete');
- }
-
-
- $this->backdropLogout();
- $this->backdropLogin($this->base_user_2);
- $this->backdropGet('admin/content/files');
- $this->assertResponse(200);
- foreach ($files as $file) {
- $this->assertLinkByHref('file/' . $file->fid . '/delete');
-
-
- $this->assertNoLinkByHref('file/' . $file->fid . '/manage');
-
-
- $this->backdropGet('file/' . $file->fid . '/delete');
- $count = db_query("SELECT count(fid) FROM {file_usage} WHERE fid = :fid", array(':fid' => $file->fid))->fetchField();
- if ($count == 0) {
- $text = 'This file has no known content referencing it';
- }
- else {
- $singular = 'This file is referenced by one piece of content.';
- $plural = "This file is referenced by @count pieces of content.";
- $text = format_plural($count, $singular, $plural);
- }
- $this->assertText($text, 'Correct file usage counts appear on confirm page: ', $count);
-
- $this->clickLink('Cancel');
- }
-
-
- $this->backdropLogout();
- $this->backdropLogin($this->base_user_3);
- $this->backdropGet('admin/content/files');
- $this->assertResponse(200);
- foreach ($files as $file) {
- $this->assertLinkByHref('file/' . $file->fid . '/manage');
- }
-
-
- $parts = explode('.', $file->uri);
- $extension = array_pop($parts);
- $new_filename = 'changedme' . $extension;
- $edit = array();
- $edit['filename'] = $new_filename;
- $this->backdropPost('file/' . $file->fid . '/manage', $edit, 'Save');
- $this->assertText($new_filename, 'File name changed in database.');
-
-
-
- $edit = array();
- $test_file = $this->getTestFile('text', 131072);
- $edit['files[replace_upload]'] = backdrop_realpath($test_file->uri);
- $this->backdropPost('file/' . $file->fid . '/manage', $edit, 'Save');
- $this->assertText(format_size(131072), 'File size matches new upload.');
-
- $edit = array();
- $test_file = $this->getTestFile('text', 1310720);
- $edit['files[replace_upload]'] = backdrop_realpath($test_file->uri);
- $this->backdropPost('file/' . $file->fid . '/manage', $edit, 'Save');
- $this->assertText(format_size(1310720), 'File size matches new upload.');
- }
- }
-
- * Tests the file usage page.
- */
- class FileUsageTestCase extends FileTestHelper {
-
- function setUp() {
- parent::setUp();
-
- $web_user = $this->backdropCreateUser(array('create files', 'bypass file access', 'edit own post content'));
- $this->backdropLogin($web_user);
- }
-
-
- * Create a file and verify its usage information.
- */
- function testFileUsagePage() {
- $image_field = 'field_image';
- $image = $this->getTestFile('image');
-
-
- $edit = array(
- "files[" . $image_field . "_" . LANGUAGE_NONE . "_0]" => backdrop_realpath($image->uri),
- );
- $node = $this->backdropCreateNode(array('type' => 'post'));
- $this->backdropPost('node/' . $node->nid . '/edit', $edit, t('Save'));
-
-
- $fid = $this->getLastFileId();
- $file = file_load($fid);
-
-
- $this->backdropGet('file/' . $file->fid . '/usage');
-
-
- $this->assertLink($node->title);
- $this->assertLinkByHref(backdrop_get_path_alias('node/' . $node->nid));
-
-
- $expected_values = array(
- 'type' => 'node',
- 'count' => 1,
- );
- foreach ($expected_values as $name => $value) {
- $this->assertTrue($this->xpath('//table/tbody/tr/td[normalize-space(text())=:text]', array(':text' => $value)), t('File usage @name was found in the table.', array('@name' => $name)));
- }
-
-
-
-
- file_usage_add($file, 'example_module', 'node', $node->nid, 2);
-
-
- $this->backdropGet('file/' . $file->fid . '/usage');
- $expected_values['count'] = 3;
- foreach ($expected_values as $name => $value) {
- $this->assertTrue($this->xpath('//table/tbody/tr/td[normalize-space(text())=:text]', array(':text' => $value)), t('File usage @name was found in the table.', array('@name' => $name)));
- }
-
-
-
- file_usage_add($file, 'test_module', 'imaginary', 1);
-
-
- $this->backdropGet('file/' . $file->fid . '/usage');
-
-
- $this->assertNoLink('test_module');
- $this->assertRaw('test_module', 'Module name used in place of link to the entity.');
-
-
- $expected_values = array(
- 'type' => 'imaginary',
- 'count' => 1,
- );
- foreach ($expected_values as $name => $value) {
- $this->assertTrue($this->xpath('//table/tbody/tr/td[normalize-space(text())=:text]', array(':text' => $value)), t('File usage @name was found in the table.', array('@name' => $name)));
- }
- }
- }
-
- * Test changing the scheme of a file.
- */
- class FileChangeSchemeTestCase extends FileTestHelper {
-
- function testChangeScheme() {
-
- $file = $this->createFile(array('type' => 'document'));
- $this->assertEqual(file_uri_scheme($file->uri), 'public', 'File is public.');
-
-
- $user = $this->backdropCreateUser(array('edit any document files'));
- $this->backdropLogin($user);
-
- $this->backdropGet('file/' . $file->fid . '/manage');
- $this->assertNoFieldByName('scheme');
-
-
- $user = $this->backdropCreateUser(array('edit any document files', 'manage files'));
- $this->backdropLogin($user);
-
- $this->backdropGet('file/' . $file->fid . '/manage');
- $this->assertFieldByName('scheme', 'public');
-
- $this->backdropPost(NULL, array('scheme' => 'private'), 'Save');
- $file = entity_load_unchanged('file', $file->fid);
- $this->assertEqual(file_uri_scheme($file->uri), 'private', 'File has changed to private.');
- }
-
- }
-
- * Tests replacing the file associated with a file entity.
- */
- class FileReplaceTestCase extends FileTestHelper {
-
- function setUp() {
- parent::setUp();
- $this->backdropLogin($this->admin_user);
- }
-
-
- * @todo Test image dimensions for an image field are reset when a file is replaced.
- * @todo Test image styles are cleared when an image is updated.
- */
- function testReplaceFile() {
-
- $file = $this->createFile(array('type' => 'document'));
-
-
- $user = $this->backdropCreateUser(array('edit any document files'));
-
-
-
- $this->backdropGet('file/' . $file->fid . '/manage');
- $this->assertFieldByName('files[replace_upload]');
-
-
- $this->backdropPost(NULL, array(), t('Save'));
- $this->assertText(t('File: @file has been updated.', array('@file' => $file->filename)), 'File was updated without file upload.');
-
-
- $original = clone $file;
- $replacement = $this->getTestFile('text');
-
-
- $edit = array();
- $edit['files[replace_upload]'] = backdrop_realpath($replacement->uri);
- $this->backdropPost('file/' . $file->fid . '/manage', $edit, t('Save'));
- $this->assertText(t('File: @file has been updated.', array('@file' => $file->filename)), 'File was updated with file upload.');
-
-
- $file = file_load($file->fid);
-
-
- $this->assertEqual($file->filename, $original->filename, 'Updated file name did not change.');
- $this->assertNotEqual($file->filesize, $original->filesize, 'Updated file size changed from previous file.');
- $this->assertEqual($file->filesize, $replacement->filesize, 'Updated file size matches uploaded file.');
- $this->assertEqual(file_get_contents($file->uri), file_get_contents($replacement->uri), 'Updated file contents matches uploaded file.');
- $this->assertFalse(entity_load('file', FALSE, array('status' => 0)), 'Temporary file used for replacement was deleted.');
-
-
- $image = $this->getTestFile('image');
- $edit['files[replace_upload]'] = backdrop_realpath($image->uri);
-
-
- $this->backdropPost('file/' . $file->fid . '/manage', $edit, t('Save'));
- $this->assertRaw(t('The specified file %file could not be uploaded. Only files with the following extensions are allowed:', array('%file' => $image->filename)), 'File validation works, upload failed correctly.');
-
-
- $file2 = new stdClass();
- $file2->uri = 'oembed://' . $this->randomName();
- $file2->filename = backdrop_basename($file2->uri);
- $file2->filemime = 'image/oembed';
- $file2->type = 'image';
- $file2->uid = 1;
- $file2->timestamp = REQUEST_TIME;
- $file2->filesize = 0;
- $file2->status = 0;
-
-
- $this->assertTrue(backdrop_write_record('file_managed', $file2), 'Non-local file was added to the database.');
-
-
- $this->backdropGet('file/' . $file2->fid . '/manage');
- $this->assertNoFieldByName('files[replace_upload]');
- }
- }
-
- * Tests adding support for bundles to the core 'file' entity.
- */
- class FileTypeTestCase extends FileTestHelper {
-
- function setUp() {
- parent::setUp();
- }
-
-
- * Test admin pages access and functionality.
- */
- function testAdminPages() {
-
- $user = $this->backdropCreateUser(array('administer file types'));
- $this->backdropLogin($user);
-
- $this->backdropGet('admin/structure/file-types');
- $this->assertResponse(200, 'File types admin page is accessible');
- }
-
-
- * Test creating a new type. Basic CRUD.
- */
- function testCreate() {
- $type_machine_type = 'foo';
- $type_machine_label = 'foobar';
- $type = $this->createFileType(array('type' => $type_machine_type, 'name' => $type_machine_label));
- $loaded_type = file_type_load($type_machine_type);
- $this->assertEqual($loaded_type->name, $type_machine_label, "Was able to create a type and retrieve it.");
- }
-
-
- * Test file types CRUD UI.
- */
- function testTypesCrudUi() {
- $this->backdropGet('admin/structure/file-types');
- $this->assertResponse(403, 'File types UI page is not accessible to unauthorized users.');
-
- $user = $this->backdropCreateUser(array('administer file types', 'administer fields'));
- $this->backdropLogin($user);
-
- $this->backdropGet('admin/structure/file-types');
- $this->assertResponse(200, 'File types UI page is accessible to users with adequate permission.');
-
-
- $edit = array(
- 'name' => t('Test type'),
- 'type' => 'test_type',
-
- 'description' => t('This is dummy file type used just for testing.'),
- 'mimetypes' => 'image/png',
- );
- $this->backdropGet('admin/structure/file-types/add');
- $this->backdropPost(NULL, $edit, t('Save'));
- $this->assertText(t('The file type @type has been updated.', array('@type' => $edit['name'])), 'New file type successfully created.');
- $this->assertText($edit['name'], 'New file type created: name found.');
- $this->assertText($edit['description'], 'New file type created: description found.');
- $this->assertFieldByXPath("//table//td[1]//div[1]", $edit['name'], 'The label of the newly-created file type is shown in the table.');
- $this->assertFieldByXPath("//table//td[1]//div[2]", '(' . t('Machine name: @machine_name', array('@machine_name' => $edit['type'])) . ')', 'The machine name of the newly-created file type is shown in the table.');
- $this->assertFieldByXPath("//table//td[2]", $edit['description'], 'The description of the newly-created file type is shown in the table.');
- $this->assertFieldByXPath("//table//td[3]", t('Custom'), 'The storage state of the newly-created file type is shown in the table.');
- $this->assertLink(t('Disable'), 0, 'Able to disable newly created file type.');
- $this->assertLink(t('Delete'), 0, 'Able to delete newly created file type.');
- $this->assertLinkByHref('admin/structure/file-types/manage/' . str_replace('_', '-', $edit['type']) . '/disable', 0, 'Disable link disables.');
- $this->assertLinkByHref('admin/structure/file-types/manage/' . str_replace('_', '-', $edit['type']) . '/delete', 0, 'Delete link points to delete confirmation page.');
- $this->assertEqual($edit['type'], config_get('file.type.' . $edit['type'], 'type'), 'The newly-created file type is stored in config.');
-
-
- $this->backdropGet('admin/structure/file-types/manage/' . $edit['type'] . '/edit');
- $this->assertRaw(t('Save'), 'Save button found on edit page.');
- $this->assertRaw(t('Delete'), 'Delete button found on edit page.');
- $this->assertRaw($edit['name'], 'name found on file type edit page');
- $this->assertText($edit['description'], 'Description found on file type edit page');
- $this->assertText($edit['mimetypes'], 'Mime-type configuration found on file type edit page');
- $this->assertText(t('Available media types'), 'Mimetype list present on edit form.');
-
-
- $edit['name'] = t('New type name');
- $this->backdropPost(NULL, array('name' => $edit['name']), t('Save'));
- $this->assertRaw(t('The file type %type has been updated.', array('%type' => $edit['name'])), 'File type was modified.');
- $this->assertText($edit['name'], 'Modified name found on file types list.');
- $this->assertEqual($edit['name'], config_get('file.type.' . $edit['type'], 'name'), 'The file type name was updated in config.');
-
-
- $url_type = str_replace('_', '-', $edit['type']);
- $this->clickFileTypeOperationLink(t('Disable'), $url_type . '/disable');
- $this->assertTrue(config_get('file.type.' . $edit['type'], 'disabled'), 'The file type was disabled in config.');
- $this->assertRaw(t('The file type %type has been disabled.', array('%type' => $edit['name'])), 'Disable confirmation message found.');
- $this->assertLink(t('Enable'), 0, 'Able to re-enable newly created file type.');
- $this->clickFileTypeOperationLink(t('Enable'), $url_type . '/enable');
- $this->assertFalse(config_get('file.type.' . $edit['type'], 'disabled'), 'The file type was enabled in config.');
- $this->assertRaw(t('The file type %type has been enabled.', array('%type' => $edit['name'])), 'Enable confirmation message found.');
- $this->assertLink(t('Disable'), 0, 'Able to disable newly created file type again.');
-
-
- $this->backdropGet('admin/structure/file-types/manage/' . $edit['type'] . '/delete');
- $this->assertText(t('Are you sure you want to delete the file type @type?', array('@type' => $edit['name'])), 'Delete confirmation page found.');
- $this->backdropPost(NULL, array(), t('Delete'));
- $this->assertRaw(t('The file type %type has been deleted.', array('%type' => $edit['name'])), 'Delete confirmation message found.');
- $this->backdropGet('admin/structure/file-types');
- $this->assertNoText($edit['name'], 'File type successfully deleted.');
-
-
- $this->backdropGet('admin/structure/file-types/manage/image/edit');
- $this->assertRaw(t('Image'), 'name found on file type edit page');
- $this->assertText("image/*", 'Mime-type configuration found on file type edit page');
- $this->backdropPost(NULL, array('name' => t('Funky images')), t('Save'));
- $this->assertText(t('The file type @type has been updated.', array('@type' => t('Funky images'))), 'File type was modified.');
- $this->assertText(t('Funky image'), 'Modified name found on file types list.');
- $this->assertLink(t('Revert'), 0, 'Able to revert overridden file type.');
- $this->assertLinkByHref('admin/structure/file-types/manage/image/revert', 0, 'Revert link points to revert confirmation page.');
-
-
- $this->backdropGet('admin/structure/file-types/manage/image/revert');
- $this->assertText(t('Are you sure you want to revert the file type @type?', array('@type' => t('Funky images'))), 'Revert confirmation page found.');
- $this->backdropPost(NULL, array(), t('Revert'));
- $this->assertText(t('The file type @type has been reverted.', array('@type' => t('Funky images'))), 'Revert confirmation message found.');
-
- $this->assertText(t('Image'), 'Reverted file type found in list.');
- $this->assertNoText(t('Overridden'), 'No overridden file types remain.');
- }
-
-
- * Click a link to perform an operation on a view.
- *
- * In general, we expect lots of links titled "enable" or "disable" on the
- * various views listing pages, and they might have tokens in them. So we
- * need special code to find the correct one to click.
- *
- * @param $label
- * Text between the anchor tags of the desired link.
- * @param $unique_href_part
- * A unique string that is expected to occur within the href of the desired
- * link. For example, if the link URL is expected to look like
- * "admin/structure/views/view/frontpage/...", then "/frontpage/" could be
- * passed as the expected unique string.
- *
- * @return
- * The page content that results from clicking on the link, or FALSE on
- * failure. Failure also results in a failed assertion.
- */
- function clickFileTypeOperationLink($label, $unique_href_part) {
- $links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
- foreach ($links as $link_index => $link) {
- $position = strpos($link['href'], $unique_href_part);
- if ($position !== FALSE) {
- $index = $link_index;
- break;
- }
- }
- $this->assertTrue(isset($index), t('Link to "@label" containing @part found.', array('@label' => $label, '@part' => $unique_href_part)));
- if (isset($index)) {
- return $this->clickLink($label, $index);
- }
- else {
- return FALSE;
- }
- }
- }
-
- * Tests the file entity access API.
- */
- class FileAccessTestCase extends FileTestHelper {
-
- function setUp() {
- parent::setUp();
-
-
-
- $roles = user_roles();
- foreach ($roles as $rid => $role) {
- user_role_revoke_permissions($rid, array('view files'));
- }
- }
-
-
- * Runs basic tests for file_access function.
- */
- function testFileAccess() {
- $file = $this->createFile(array('type' => 'image'));
-
-
- $web_user = $this->backdropCreateUser(array('bypass file access'));
- $this->backdropLogin($web_user);
- $this->assertFileAccess(array('create' => TRUE), NULL, $web_user);
- $this->assertFileAccess(array('view' => TRUE, 'download' => TRUE, 'update' => TRUE, 'delete' => TRUE), $file, $web_user);
-
-
-
- $web_user = $this->backdropCreateUser(array('manage files'));
- $this->backdropLogin($web_user);
- $this->assertFileAccess(array('view' => FALSE, 'download' => FALSE, 'update' => TRUE, 'delete' => FALSE), $file, $web_user);
-
-
- $web_user = $this->backdropCreateUser(array('create files'));
- $this->backdropLogin($web_user);
- $this->assertFileAccess(array('view' => FALSE), $file, $web_user);
-
- $this->assertFileAccess(array('create' => TRUE), NULL, $web_user);
-
-
- $web_user = $this->backdropCreateUser(array('create files', 'view own files'));
- $this->backdropLogin($web_user);
- $this->assertFileAccess(array('view' => FALSE), $file, $web_user);
- $file->uid = $web_user->uid;
- $this->assertFileAccess(array('view' => TRUE), $file, $web_user);
-
-
- $web_user = $this->backdropCreateUser(array('create files', 'download own image files'));
- $this->backdropLogin($web_user);
- $this->assertFileAccess(array('download' => FALSE), $file, $web_user);
- $file->uid = $web_user->uid;
- $this->assertFileAccess(array('download' => TRUE), $file, $web_user);
-
-
- $web_user = $this->backdropCreateUser(array('create files', 'view own files', 'edit own image files'));
- $this->backdropLogin($web_user);
- $this->assertFileAccess(array('update' => FALSE), $file, $web_user);
- $file->uid = $web_user->uid;
- $this->assertFileAccess(array('update' => TRUE), $file, $web_user);
-
-
- $web_user = $this->backdropCreateUser(array('create files', 'view own files', 'edit own image files', 'delete own image files'));
- $this->backdropLogin($web_user);
- $this->assertFileAccess(array('delete' => FALSE), $file, $web_user);
- $file->uid = $web_user->uid;
- $this->assertFileAccess(array('delete' => TRUE), $file, $web_user);
-
-
- $web_user = $this->backdropCreateUser(array('create files', 'view files'));
- $this->backdropLogin($web_user);
- $this->assertFileAccess(array('view' => TRUE), $file, $web_user);
-
-
- $web_user = $this->backdropCreateUser(array('create files', 'download any image files'));
- $this->backdropLogin($web_user);
- $this->assertFileAccess(array('download' => TRUE), $file, $web_user);
-
-
- $web_user = $this->backdropCreateUser(array('create files', 'view files', 'edit any image files'));
- $this->backdropLogin($web_user);
- $this->assertFileAccess(array('update' => TRUE), $file, $web_user);
-
-
- $web_user = $this->backdropCreateUser(array('create files', 'view files', 'edit any image files', 'delete any image files'));
- $this->backdropLogin($web_user);
- $this->assertFileAccess(array('delete' => TRUE), $file, $web_user);
- }
-
-
- * Tests page access.
- *
- * Verifies the privileges required to access the following pages:
- * file/%/view
- * file/%/download
- * file/%/edit
- * file/%/usage
- * file/%/delete
- */
- function testFilePageAccess() {
-
- $web_user = $this->backdropCreateUser();
- $this->backdropLogin($web_user);
-
- $file = $this->createFile(array('type' => 'document','uid' => $web_user->uid));
-
-
- $this->backdropGet("file/{$file->fid}/view");
- $this->assertResponse(403, 'Users without access can not view their own files');
-
-
- user_role_change_permissions(BACKDROP_AUTHENTICATED_ROLE, array(
- 'view own files' => TRUE,
- ));
- $this->backdropGet("file/{$file->fid}/view");
- $this->assertResponse(200, 'Users with access can view their own files');
-
-
- $file->uid = 1;
- file_save($file);
- $this->backdropGet("file/{$file->fid}/view");
- $this->assertResponse(403, 'Users with access can not view any file');
-
-
- user_role_change_permissions(BACKDROP_AUTHENTICATED_ROLE, array(
- 'view files' => TRUE,
- ));
- $this->backdropGet("file/{$file->fid}/view");
- $this->assertResponse(200, 'Users with access can view any file');
-
-
- $file->uid = $web_user->uid;
- file_save($file);
- $url ='file/' . $file->fid . '/download';
- $this->backdropGet($url);
- $this->assertResponse(403, 'Users without access can not download their own files');
-
-
- user_role_change_permissions(BACKDROP_AUTHENTICATED_ROLE, array(
- 'download own document files' => TRUE,
- ));
- $this->backdropGet($url);
- $this->assertResponse(200, 'Users with access can download their own files');
-
-
- $file->uid = 1;
- file_save($file);
- $url = "file/{$file->fid}/download";
- $this->backdropGet($url);
- $this->assertResponse(403, 'Users without access can not download any file');
-
-
- user_role_change_permissions(BACKDROP_AUTHENTICATED_ROLE, array(
- 'download any document files' => TRUE,
- ));
- $this->backdropGet($url);
- $this->assertResponse(200, 'Users with access can download any file');
-
-
- $file->uid = $web_user->uid;
- file_save($file);
- $this->backdropGet("file/{$file->fid}/manage");
- $this->assertResponse(403, 'Users without access can not edit own files');
-
-
- $this->backdropGet("file/{$file->fid}/usage");
- $this->assertResponse(403, 'Users without access can not check the usage of their own files');
-
-
- user_role_change_permissions(BACKDROP_AUTHENTICATED_ROLE, array(
- 'edit own document files' => TRUE,
- ));
- $this->backdropGet("file/{$file->fid}/manage");
- $this->assertResponse(200, 'Users with access can edit own files');
-
-
- $this->backdropGet("file/{$file->fid}/usage");
- $this->assertResponse(200, 'Users with access can check the usage of their own files');
-
-
- $file->uid = 1;
- file_save($file);
- $this->backdropGet("file/{$file->fid}/manage");
- $this->assertResponse(403, 'Users without access can not edit any file');
-
-
- $this->backdropGet("file/{$file->fid}/usage");
- $this->assertResponse(403, 'Users without access can not check the usage of any file');
-
-
- user_role_change_permissions(BACKDROP_AUTHENTICATED_ROLE, array(
- 'edit any document files' => TRUE,
- ));
- $this->backdropGet("file/{$file->fid}/manage");
- $this->assertResponse(200, 'Users with access can edit any file');
-
-
- $this->backdropGet("file/{$file->fid}/usage");
- $this->assertResponse(200, 'Users with access can check the usage of any file');
-
-
- $file->uid = $web_user->uid;
- file_save($file);
- $this->backdropGet("file/{$file->fid}/delete");
- $this->assertResponse(403, 'Users without access can not delete their own files');
-
-
- user_role_change_permissions(BACKDROP_AUTHENTICATED_ROLE, array(
- 'delete own document files' => TRUE,
- ));
- $this->backdropGet("file/{$file->fid}/delete");
- $this->assertResponse(200, 'Users with access can delete their own files');
-
-
- $file->uid = 1;
- file_save($file);
- $this->backdropGet("file/{$file->fid}/delete");
- $this->assertResponse(403, 'Users without access can not delete any file');
-
-
- user_role_change_permissions(BACKDROP_AUTHENTICATED_ROLE, array(
- 'delete any document files' => TRUE,
- ));
- $this->backdropGet("file/{$file->fid}/delete");
- $this->assertResponse(200, 'Users with access can delete any file');
- }
-
-
- * Test to see if we have access to download private files when granted the permissions.
- */
- function testFilePrivateDownloadAccess() {
- foreach ($this->getPrivateDownloadAccessCases() as $case) {
-
- $authenticated_user = !is_null($case['permissions']);
- if ($authenticated_user) {
- $account = $this->backdropCreateUser($case['permissions']);
- $this->backdropLogin($account);
- }
-
-
- if (!empty($case['owner'])) {
- $file = $this->createFile(array('type' => 'document', 'uid' => $account->uid, 'scheme' => 'private'));
-
-
- $arguments = array('%name' => $file->filename, '%username' => $account->name, '%uri' => $file->uri);
- $this->assertTrue(is_file($file->uri), format_string('File %name owned by %username successfully created at %uri.', $arguments));
- $url = file_create_url($file->uri);
- $message_file_info = ' ' . format_string('File %uri was checked.', array('%uri' => $file->uri));
- }
-
-
- $this->backdropGet($url);
- $this->assertResponse($case['expect'], $case['message'] . $message_file_info);
-
-
- if ($authenticated_user) {
- $this->backdropLogout();
- }
- }
- }
-
-
- * Asserts file_access correctly grants or denies access.
- */
- function assertFileAccess($ops, $file, $account) {
- backdrop_static_reset('file_access');
- backdrop_static_reset('user_access');
- foreach ($ops as $op => $result) {
- $msg = t("file_access returns @result with operation '@op'.", array('@result' => $result ? 'true' : 'false', '@op' => $op));
- $this->assertEqual($result, file_access($op, $file, $account), $msg);
- }
- }
-
-
- * Helper for testFilePrivateDownloadAccess() test.
- *
- * Defines several cases for accesing private files.
- *
- * @return array
- * Array of associative arrays, each one having the next keys:
- * - "message" string with the assertion message.
- * - "permissions" array of permissions or NULL for anonymous user.
- * - "expect" expected HTTP response code.
- * - "owner" Optional boolean indicating if the user is a file owner.
- */
- function getPrivateDownloadAccessCases() {
- return array(
- array(
- 'message' => "File owners cannot download their own files unless they are granted the 'view own private files' permission.",
- 'permissions' => array(),
- 'expect' => 403,
- 'owner' => TRUE,
- ),
- array(
- 'message' => "File owners can download their own files as they have been granted the 'view own private files' permission.",
- 'permissions' => array('view own private files'),
- 'expect' => 200,
- 'owner' => TRUE,
- ),
- array(
- 'message' => "Anonymous users cannot download private files.",
- 'permissions' => NULL,
- 'expect' => 403,
- ),
- array(
- 'message' => "Authenticated users cannot download each other's private files.",
- 'permissions' => array(),
- 'expect' => 403,
- ),
- array(
- 'message' => "Users who can view public files are not able to download private files.",
- 'permissions' => array('view files'),
- 'expect' => 403,
- ),
- array(
- 'message' => "Users who bypass file access can download any file.",
- 'permissions' => array('bypass file access'),
- 'expect' => 200,
- ),
- );
- }
- }
-
- * Tests overriding file attributes.
- */
- class FileAttributeOverrideTestCase extends FileTestHelper {
-
-
- * Test to see if file attributes can be overridden.
- */
- function testFileFileAttributeOverrides() {
- $overrides = array(
- 'width' => 40,
- 'height' => 20,
- );
-
-
- $file = $this->createFile(array('type' => 'image'));
-
-
- foreach ($overrides as $override => $value) {
- $file->override['attributes'][$override] = $value;
- }
-
-
- $build = file_view_file($file, 'full');
-
-
- foreach ($overrides as $attribute => $expected_value) {
- $this->assertEqual($build['#item'][$attribute], $expected_value, format_string('The %attribute was overridden correctly.', array('%attribute' => $attribute)));
- }
- }
- }