<?php

/**
 * @file
 * Tests for file.module.
 */

/**
 * Provides methods specifically for testing File module's field handling.
 */
class FileFieldTestCase extends DrupalWebTestCase {
  protected $admin_user;

  function setUp() {
    // Since this is a base class for many test cases, support the same
    // flexibility that DrupalWebTestCase::setUp() has for the modules to be
    // passed in as either an array or a variable number of string arguments.
    $modules = func_get_args();
    if (isset($modules[0]) && is_array($modules[0])) {
      $modules = $modules[0];
    }
    $modules[] = 'file';
    $modules[] = 'file_module_test';
    parent::setUp($modules);
    $this->admin_user = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer users', 'administer permissions', 'administer content types', 'administer nodes', 'bypass node access', 'administer fields'));
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Retrieves a sample file of the specified type.
   */
  function getTestFile($type_name, $size = NULL) {
    // Get a file to upload.
    $file = current($this->drupalGetTestFiles($type_name, $size));

    // Add a filesize property to files as would be read by file_load().
    $file->filesize = filesize($file->uri);

    return $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()) {
    $field = array(
      'field_name' => $name,
      'type' => 'file',
      'settings' => array(),
      'cardinality' => !empty($field_settings['cardinality']) ? $field_settings['cardinality'] : 1,
    );
    $field['settings'] = array_merge($field['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 {
      // Add a new node.
      $extras['type'] = $nid_or_type;
      $node = $this->drupalCreateNode($extras);
      $nid = $node->nid;
      // Save at least one revision to better simulate a real site.
      $this->drupalCreateNode(get_object_vars($node));
      $node = node_load($nid, NULL, TRUE);
      $this->assertNotEqual($nid, $node->vid, 'Node revision exists.');
    }

    // Attach a file to the node.
    $edit['files[' . $field_name . '_' . $langcode . '_0]'] = drupal_realpath($file->uri);
    $this->drupalPost("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->drupalPost('node/' . $nid . '/edit', array(), t('Remove'));
    $this->drupalPost(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]' => drupal_realpath($file->uri),
      'revision' => (string) (int) $new_revision,
    );

    $this->drupalPost('node/' . $nid . '/edit', array(), t('Remove'));
    $this->drupalPost(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, NULL, NULL);

    if ($file) {
      $file->uid = isset($uid) ? $uid : $this->admin_user->uid;
      // Change the file status to be temporary.
      $file->status = NULL;
      return file_save($file);
    }

    return $file;
  }
}

/**
 * Tests adding a file to a non-node entity.
 */
class FileTaxonomyTermTestCase extends DrupalWebTestCase {
  protected $admin_user;

  public static function getInfo() {
    return array(
      'name' => 'Taxonomy term file test',
      'description' => 'Tests adding a file to a non-node entity.',
      'group' => 'File',
    );
  }

  public function setUp() {
    $modules[] = 'file';
    $modules[] = 'taxonomy';
    parent::setUp($modules);
    $this->admin_user = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer taxonomy'));
    $this->drupalLogin($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);
    // Attach an instance of it.
    $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.
   *
   * This is a regression test for https://www.drupal.org/node/2305017.
   */
  public function testTermFilePublic() {
    $this->_testTermFile('public');
  }

  /**
   * Tests that a private file can be attached to a taxonomy term.
   *
   * This is a regression test for https://www.drupal.org/node/2305017.
   */
  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);
    // Get a file to upload.
    $file = current($this->drupalGetTestFiles('text'));
    // Add a filesize property to files as would be read by file_load().
    $file->filesize = filesize($file->uri);
    $langcode = LANGUAGE_NONE;
    $edit = array(
      "name" => $this->randomName(),
    );
    // Attach a file to the term.
    $edit['files[' . $field_name . '_' . $langcode . '_0]'] = drupal_realpath($file->uri);
    $this->drupalPost("admin/structure/taxonomy/tags/add", $edit, t('Save'));
    // Find the term ID we just created.
    $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'];
    // Check that the uploaded file is present on the edit form.
    $this->drupalGet("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 the term and change name without changing the file.
    $edit = array(
      "name" => $this->randomName(),
    );
    $this->drupalPost("taxonomy/term/$tid/edit", $edit, t('Save'));
    // Check that the uploaded file is still present on the edit form.
    $this->drupalGet("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.');
    // Load term while resetting the cache.
    $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 FileFieldTestCase methods
 *   that aren't related to fields into it.
 */
class FileManagedFileElementTestCase extends FileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Managed file element test',
      'description' => 'Tests the managed_file element type.',
      'group' => 'File',
    );
  }

  /**
   * Tests the managed_file element type.
   */
  function testManagedFile() {
    // Check that $element['#size'] is passed to the child upload element.
    $this->drupalGet('file/test');
    $this->assertFieldByXpath('//input[@name="files[nested_file]" and @size="13"]', NULL, 'The custom #size attribute is passed to the child upload element.');

    // Perform the tests with all permutations of $form['#tree'] and
    // $element['#extended'].
    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';

        // Submit without a file.
        $this->drupalPost($path, array(), t('Save'));
        $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submitted without a file.');

        // Submit with a file, but with an invalid form token. Ensure the file
        // was not saved.
        $last_fid_prior = $this->getLastFileId();
        $edit = array(
          'files[' . $input_base_name . ']' => drupal_realpath($test_file->uri),
          'form_token' => 'invalid token',
        );
        $this->drupalPost($path, $edit, t('Save'));
        $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
        $last_fid = $this->getLastFileId();
        $this->assertEqual($last_fid_prior, $last_fid, 'File was not saved when uploaded with an invalid form token.');

        // Submit a new file, without using the Upload button.
        $last_fid_prior = $this->getLastFileId();
        $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
        $this->drupalPost($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.');

        // Submit no new input, but with a default file.
        $this->drupalPost($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.');

        // Now, test the Upload and Remove buttons, with and without Ajax.
        foreach (array(FALSE, TRUE) as $ajax) {
          // Upload, then Submit.
          $last_fid_prior = $this->getLastFileId();
          $this->drupalGet($path);
          $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
          if ($ajax) {
            $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
          }
          else {
            $this->drupalPost(NULL, $edit, t('Upload'));
          }
          $last_fid = $this->getLastFileId();
          $this->assertTrue($last_fid > $last_fid_prior, 'New file got uploaded.');
          $this->drupalPost(NULL, array(), t('Save'));
          $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Submit handler has correct file info.');

          // Remove, then Submit.
          $this->drupalGet($path . '/' . $last_fid);
          if ($ajax) {
            $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
          }
          else {
            $this->drupalPost(NULL, array(), t('Remove'));
          }
          $this->drupalPost(NULL, array(), t('Save'));
          $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submission after file removal was successful.');

          // Upload, then Remove, then Submit.
          $this->drupalGet($path);
          $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
          if ($ajax) {
            $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
            $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
          }
          else {
            $this->drupalPost(NULL, $edit, t('Upload'));
            $this->drupalPost(NULL, array(), t('Remove'));
          }
          $this->drupalPost(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 field widget.
 */
class FileFieldWidgetTestCase extends FileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'File field widget test',
      'description' => 'Tests the file field widget, single and multi-valued, with and without AJAX, with public and private files.',
      'group' => 'File',
    );
  }

  /**
   * Tests upload and remove buttons for a single-valued File field.
   */
  function testSingleValuedWidget() {
    // Use 'page' instead of 'article', so that the 'article' image field does
    // not conflict with this test. If in the future the 'page' type gets its
    // own default file or image field, this test can be made more robust by
    // using a custom node type.
    $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) {
      // Create a new node with the uploaded file and ensure it got uploaded
      // successfully.
      // @todo This only tests a 'nojs' submission, because drupalPostAJAX()
      //   does not yet support file uploads.
      $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.');

      // Test that running field_attach_update() leaves the file intact.
      $field = new stdClass();
      $field->type = $type_name;
      $field->nid = $nid;
      field_attach_update('node', $field);
      $node = node_load($nid);
      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
      $this->assertFileExists($node_file, 'New file still saved to disk on field update.');

      // Ensure the file can be downloaded.
      $this->drupalGet(file_create_url($node_file->uri));
      $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');

      // Ensure the edit page has a remove button instead of an upload button.
      $this->drupalGet("node/$nid/edit");
      $this->assertNoFieldByXPath('//input[@type="submit"]', t('Upload'), 'Node with file does not display the "Upload" button.');
      $this->assertFieldByXpath('//input[@type="submit"]', t('Remove'), 'Node with file displays the "Remove" button.');

      // "Click" the remove button (emulating either a nojs or js submission).
      switch ($type) {
        case 'nojs':
          $this->drupalPost(NULL, array(), t('Remove'));
          break;
        case 'js':
          $button = $this->xpath('//input[@type="submit" and @value="' . t('Remove') . '"]');
          $this->drupalPostAJAX(NULL, array(), array((string) $button[0]['name'] => (string) $button[0]['value']));
          break;
      }

      // Ensure the page now has an upload button instead of a remove button.
      $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), 'After clicking the "Remove" button, it is no longer displayed.');
      $this->assertFieldByXpath('//input[@type="submit"]', t('Upload'), 'After clicking the "Remove" button, the "Upload" button is displayed.');

      // Save the node and ensure it does not have the file.
      $this->drupalPost(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() {
    // Create a victim user.
    $victim_user = $this->drupalCreateUser();

    // Create an attacker user.
    $attacker_user = $this->drupalCreateUser(array(
      'access content',
      'create page content',
      'edit any page content',
    ));

    // Log in as the attacker user.
    $this->drupalLogin($attacker_user);

    // Perform tests using the newly created users.
    $this->doTestTemporaryFileRemovalExploit($victim_user->uid, $attacker_user->uid);
  }

  /**
   * Tests exploiting the temporary file removal for anonymous users using fid.
   */
  public function testTemporaryFileRemovalExploitAnonymous() {
    // Set up an anonymous victim user.
    $victim_uid = 0;

    // Set up an anonymous attacker user.
    $attacker_uid = 0;

    // Set up permissions for anonymous attacker user.
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
      'access content' => TRUE,
      'create page content' => TRUE,
      'edit any page content' => TRUE,
    ));

    // In order to simulate being the anonymous attacker user, we need to log
    // out here since setUp() has logged in the admin.
    $this->drupalLogout();

    // Perform tests using the newly set up users.
    $this->doTestTemporaryFileRemovalExploit($victim_uid, $attacker_uid);
  }

  /**
   * 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) {
    // Use 'page' instead of 'article', so that the 'article' image field does
    // not conflict with this test. If in the future the 'page' type gets its
    // own default file or image field, this test can be made more robust by
    // using a custom node type.
    $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) {
      // Create a temporary file owned by the anonymous victim user. This will be
      // as if they had uploaded the file, but not saved the node they were
      // editing or creating.
      $victim_tmp_file = $this->createTemporaryFile('some text', $victim_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');

      // Have attacker create a new node with a different uploaded file and
      // ensure it got uploaded successfully.
      // @todo Can we test AJAX? See https://www.drupal.org/node/2538260
      $edit = array(
        'title' => $type . '-title',
      );

      // Attach a file to a node.
      $langcode = LANGUAGE_NONE;
      $edit['files[' . $field_name . '_' . $langcode . '_0]'] = drupal_realpath($test_file->uri);
      $this->drupalPost("node/add/$type_name", $edit, 'Save');
      $node = $this->drupalGetNodeByTitle($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.');

      // Ensure the file can be downloaded.
      $this->drupalGet(file_create_url($node_file->uri));
      $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');

      // "Click" the remove button (emulating either a nojs or js submission).
      // In this POST request, the attacker "guesses" the fid of the victim's
      // temporary file and uses that to remove this file.
      $this->drupalGet('node/' . $node->nid . '/edit');
      switch ($type) {
        case 'nojs':
          $this->drupalPost(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->drupalPostAJAX(NULL, array("{$field_name}[$langcode][0][fid]" => (string) $victim_tmp_file->fid), array((string) $button[0]['name'] => (string) $button[0]['value']));
          break;
      }

      // The victim's temporary file should not be removed by the attacker's
      // POST request.
      $this->assertFileExists($victim_tmp_file);
    }
  }

  /**
   * Tests upload and remove buttons for multiple multi-valued File fields.
   */
  function testMultiValuedWidget() {
    // Use 'page' instead of 'article', so that the 'article' image field does
    // not conflict with this test. If in the future the 'page' type gets its
    // own default file or image field, this test can be made more robust by
    // using a custom node type.
    $type_name = 'page';
    $field_name = strtolower($this->randomName());
    $field_name2 = strtolower($this->randomName());
    $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) {
      // Visit the node creation form, and upload 3 files for each field. Since
      // the field has cardinality of 3, ensure the "Upload" button is displayed
      // until after the 3rd file, and after that, isn't displayed. Because
      // SimpleTest triggers the last button with a given name, so upload to the
      // second field first.
      // @todo This is only testing a non-Ajax upload, because drupalPostAJAX()
      //   does not yet emulate jQuery's file upload.
      //
      $this->drupalGet("node/add/$type_name");
      foreach (array($field_name2, $field_name) as $each_field_name) {
        for ($delta = 0; $delta < 3; $delta++) {
          $edit = array('files[' . $each_field_name . '_' . LANGUAGE_NONE . '_' . $delta . ']' => drupal_realpath($test_file->uri));
          // If the Upload button doesn't exist, drupalPost() will automatically
          // fail with an assertion message.
          $this->drupalPost(NULL, $edit, t('Upload'));
        }
      }
      $this->assertNoFieldByXpath('//input[@type="submit"]', t('Upload'), 'After uploading 3 files for each field, the "Upload" button is no longer displayed.');

      $num_expected_remove_buttons = 6;

      foreach (array($field_name, $field_name2) as $current_field_name) {
        // How many uploaded files for the current field are remaining.
        $remaining = 3;
        // Test clicking each "Remove" button. For extra robustness, test them out
        // of sequential order. They are 0-indexed, and get renumbered after each
        // iteration, so array(1, 1, 0) means:
        // - First remove the 2nd file.
        // - Then remove what is then the 2nd file (was originally the 3rd file).
        // - Then remove the first file.
        foreach (array(1,1,0) as $delta) {
          // Ensure we have the expected number of Remove buttons, and that they
          // are numbered sequentially.
          $buttons = $this->xpath('//input[@type="submit" and @value="Remove"]');
          $this->assertTrue(is_array($buttons) && count($buttons) === $num_expected_remove_buttons, format_string('There are %n "Remove" buttons displayed (JSMode=%type).', array('%n' => $num_expected_remove_buttons, '%type' => $type)));
          foreach ($buttons as $i => $button) {
            $key = $i >= $remaining ? $i - $remaining : $i;
            $check_field_name = $field_name2;
            if ($current_field_name == $field_name && $i < $remaining) {
              $check_field_name = $field_name;
            }

            $this->assertIdentical((string) $button['name'], $check_field_name . '_' . LANGUAGE_NONE . '_' . $key. '_remove_button');
          }

          // "Click" the remove button (emulating either a nojs or js submission).
          $button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $delta . '_remove_button';
          switch ($type) {
            case 'nojs':
              // drupalPost() takes a $submit parameter that is the value of the
              // button whose click we want to emulate. Since we have multiple
              // buttons with the value "Remove", and want to control which one we
              // use, we change the value of the other ones to something else.
              // Since non-clicked buttons aren't included in the submitted POST
              // data, and since drupalPost() will result in $this being updated
              // with a newly rebuilt form, this doesn't cause problems.
              foreach ($buttons as $button) {
                if ($button['name'] != $button_name) {
                  $button['value'] = 'DUMMY';
                }
              }
              $this->drupalPost(NULL, array(), t('Remove'));
              break;
            case 'js':
              // drupalPostAJAX() lets us target the button precisely, so we don't
              // require the workaround used above for nojs.
              $this->drupalPostAJAX(NULL, array(), array($button_name => t('Remove')));
              break;
          }
          $num_expected_remove_buttons--;
          $remaining--;

          // Ensure an "Upload" button for the current field is displayed with the
          // correct name.
          $upload_button_name = $current_field_name . '_' . 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)));

          // Ensure only at most one button per field is displayed.
          $buttons = $this->xpath('//input[@type="submit" and @value="Upload"]');
          $expected = $current_field_name == $field_name ? 1 : 2;
          $this->assertTrue(is_array($buttons) && count($buttons) == $expected, format_string('After removing a file, only one "Upload" button for each possible field is displayed (JSMode=%type).', array('%type' => $type)));
        }
      }

      // Ensure the page now has no Remove buttons.
      $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), format_string('After removing all files, there is no "Remove" button displayed (JSMode=%type).', array('%type' => $type)));

      // Save the node and ensure it does not have any files.
      $this->drupalPost(NULL, array('title' => $this->randomName()), 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() {
    // Use 'page' instead of 'article', so that the 'article' image field does
    // not conflict with this test. If in the future the 'page' type gets its
    // own default file or image field, this test can be made more robust by
    // using a custom node type.
    $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');

    // Change the field setting to make its files private, and upload a file.
    $edit = array('field[settings][uri_scheme]' => 'private');
    $this->drupalPost("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.');

    // Ensure the private file is available to the user who uploaded it.
    $this->drupalGet(file_create_url($node_file->uri));
    $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');

    // Ensure we can't change 'uri_scheme' field settings while there are some
    // entities with uploaded files.
    $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_name");
    $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and @disabled="disabled"]', 'public', 'Upload destination setting disabled.');

    // Delete node and confirm that setting could be changed.
    node_delete($nid);
    $this->drupalGet("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->drupalCreateUser(array('access comments'));

    // Remove access comments permission from anon user.
    $edit = array(
      DRUPAL_ANONYMOUS_RID . '[access comments]' => FALSE,
    );
    $this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));

    // Create a new field.
    $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->drupalPost('admin/structure/types/manage/article/comment/fields', $edit, t('Save'));
    $edit = array('field[settings][uri_scheme]' => 'private');
    $this->drupalPost(NULL, $edit, t('Save field settings'));
    $this->drupalPost(NULL, array(), t('Save settings'));

    // Create node.
    $text_file = $this->getTestFile('text');
    $edit = array(
      'title' => $this->randomName(),
    );
    $this->drupalPost('node/add/article', $edit, t('Save'));
    $node = $this->drupalGetNodeByTitle($edit['title']);

    // Add a comment with a file.
    $text_file = $this->getTestFile('text');
    $edit = array(
      'files[field_' . $name . '_' . LANGUAGE_NONE . '_' . 0 . ']' => drupal_realpath($text_file->uri),
      'comment_body[' . LANGUAGE_NONE . '][0][value]' => $comment_body = $this->randomName(),
    );
    $this->drupalPost(NULL, $edit, t('Save'));

    // Get the comment ID.
    preg_match('/comment-([0-9]+)/', $this->getUrl(), $matches);
    $cid = $matches[1];

    // Log in as normal user.
    $this->drupalLogin($user);

    $comment = comment_load($cid);
    $comment_file = (object) $comment->{'field_' . $name}[LANGUAGE_NONE][0];
    $this->assertFileExists($comment_file, 'New file saved to disk on node creation.');
    // Test authenticated file download.
    $url = file_create_url($comment_file->uri);
    $this->assertNotEqual($url, NULL, 'Confirmed that the URL is valid');
    $this->drupalGet(file_create_url($comment_file->uri));
    $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');

    // Test anonymous file download.
    $this->drupalLogout();
    $this->drupalGet(file_create_url($comment_file->uri));
    $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');

    // Unpublishes node.
    $this->drupalLogin($this->admin_user);
    $edit = array(
      'status' => FALSE,
    );
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));

    // Ensures normal user can no longer download the file.
    $this->drupalLogin($user);
    $this->drupalGet(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 FileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'File field revision test',
      'description' => 'Test creating and deleting revisions with files attached.',
      'group' => 'File',
    );
  }

  /**
   * 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 = 'article';
    $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);

    // Attach the same fields to users.
    $this->attachFileField($field_name, 'user', 'user');

    $test_file = $this->getTestFile('text');

    // Create a new node with the uploaded file.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);

    // Check that the file exists on disk and in the database.
    $node = 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.');

    // Upload another file to the same node in a new revision.
    $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.');

    // Check that the original file is still in place on the first revision.
    $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.');

    // Save a new version of the node without any changes.
    // Check that the file is still the same as the previous revision.
    $this->drupalPost('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.');

    // Revert to the first revision and check that the original file is active.
    $this->drupalPost('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.');

    // Delete the second revision and check that the file is kept (since it is
    // still being used by the third revision).
    $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r2 . '/delete', array(), t('Delete'));
    $this->assertFileExists($node_file_r3, 'Second file is still available after deleting second revision, since it is being used by the third revision.');
    $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting second revision, since it is being used by the third revision.');
    $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting second revision, since it is being used by the third revision.');

    // Attach the second file to a user.
    $user = $this->drupalCreateUser();
    $edit = (array) $user;
    $edit[$field_name][LANGUAGE_NONE][0] = (array) $node_file_r3;
    user_save($user, $edit);
    $this->drupalGet('user/' . $user->uid . '/edit');

    // Delete the third revision and check that the file is not deleted yet.
    $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r3 . '/delete', array(), t('Delete'));
    $this->assertFileExists($node_file_r3, 'Second file is still available after deleting third revision, since it is being used by the user.');
    $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting third revision, since it is being used by the user.');
    $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting third revision, since it is being used by the user.');

    // Delete the user and check that the file is also deleted.
    user_delete($user->uid);
    // TODO: This seems like a bug in File API. Clearing the stat cache should
    // not be necessary here. The file really is deleted, but stream wrappers
    // doesn't seem to think so unless we clear the PHP file stat() cache.
    clearstatcache();
    $this->assertFileNotExists($node_file_r3, 'Second file is now deleted after deleting third revision, since it is no longer being used by any other nodes.');
    $this->assertFileEntryNotExists($node_file_r3, 'Second file entry is now deleted after deleting third revision, since it is no longer being used by any other nodes.');

    // Delete the entire node and check that the original file is deleted.
    $this->drupalPost('node/' . $nid . '/delete', array(), t('Delete'));
    $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 FileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'File field display tests',
      'description' => 'Test the display of file fields in node and views.',
      'group' => 'File',
    );
  }

  /**
   * Tests normal formatter display on node display.
   */
  function testNodeDisplay() {
    $field_name = strtolower($this->randomName());
    $type_name = 'article';
    $field_settings = array(
      'display_field' => '1',
      'display_default' => '1',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    );
    $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);

    // Create a new node *without* the file field set, and check that the field
    // is not shown for each node display.
    $node = $this->drupalCreateNode(array('type' => $type_name));
    $file_formatters = array('file_default', 'file_table', 'file_url_plain', 'hidden');
    foreach ($file_formatters as $formatter) {
      $edit = array(
        "fields[$field_name][type]" => $formatter,
      );
      $this->drupalPost("admin/structure/types/manage/$type_name/display", $edit, t('Save'));
      $this->drupalGet('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');

    // Create a new node with the uploaded file.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
    $this->drupalGet('node/' . $nid . '/edit');

    // Check that the default formatter is displaying with the file name.
    $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.');

    // Turn the "display" option off and check that the file is no longer displayed.
    $edit = array($field_name . '[' . LANGUAGE_NONE . '][0][display]' => FALSE);
    $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));

    $this->assertNoRaw($default_output, 'Field is hidden when "display" option is unchecked.');

    // Test that fields appear as expected during the preview.
    // Add a second file.
    $name = 'files[' . $field_name . '_' . LANGUAGE_NONE . '_1]';
    $edit[$name] = drupal_realpath($test_file->uri);

    // Uncheck the display checkboxes and go to the preview.
    $edit[$field_name . '[' . LANGUAGE_NONE . '][0][display]'] = FALSE;
    $edit[$field_name . '[' . LANGUAGE_NONE . '][1][display]'] = FALSE;
    $this->drupalPost('node/' . $nid . '/edit', $edit, t('Preview'));
    $this->assertRaw($field_name . '[' . LANGUAGE_NONE . '][0][display]', 'First file appears as expected.');
    $this->assertRaw($field_name . '[' . LANGUAGE_NONE . '][1][display]', 'Second file appears as expected.');
  }

  /**
   * Tests default display of File Field.
   */
  function testDefaultFileFieldDisplay() {
    $field_name = strtolower($this->randomName());
    $type_name = 'article';
    $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');

    // Create a new node with the uploaded file.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);

    $this->drupalGet('node/' . $nid . '/edit');
    $this->assertFieldByXPath('//input[@type="checkbox" and @name="' . $field_name . '[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 various validations.
 */
class FileFieldValidateTestCase extends FileFieldTestCase {
  protected $field;
  protected $node_type;

  public static function getInfo() {
    return array(
      'name' => 'File field validation tests',
      'description' => 'Tests validation functions such as file type, max file size, max size per node, and required.',
      'group' => 'File',
    );
  }

  /**
   * Tests the required property on file fields.
   */
  function testRequired() {
    $type_name = 'article';
    $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');

    // Try to post a new node without uploading a file.
    $langcode = LANGUAGE_NONE;
    $edit = array("title" => $this->randomName());
    $this->drupalPost('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.');

    // Create a new node with the uploaded file.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
    $this->assertTrue($nid !== FALSE, format_string('uploadNodeFile(@test_file, @field_name, @type_name) succeeded', array('@test_file' => $test_file->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.');

    // Try again with a multiple value field.
    field_delete_field($field_name);
    $this->createFileField($field_name, $type_name, array('cardinality' => FIELD_CARDINALITY_UNLIMITED), array('required' => '1'));

    // Try to post a new node without uploading a file in the multivalue field.
    $edit = array('title' => $this->randomName());
    $this->drupalPost('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.');

    // Create a new node with the uploaded file into the multivalue field.
    $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 multipel value field.');

    // Remove our file field.
    field_delete_field($field_name);
  }

  /**
   * Tests the max file size validator.
   */
  function testFileMaxSize() {
    $type_name = 'article';
    $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); // 128KB.
    $large_file = $this->getTestFile('text', 1310720); // 1.2MB

    // Test uploading both a large and small file with different increments.
    $sizes = array(
      '1M' => 1048576,
      '1024K' => 1048576,
      '1048576' => 1048576,
    );

    foreach ($sizes as $max_filesize => $file_limit) {
      // Set the max file upload size.
      $this->updateFileField($field_name, $type_name, array('max_filesize' => $max_filesize));
      $instance = field_info_instance('node', $field_name, $type_name);

      // Create a new node with the small file, which should pass.
      $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)));

      // Check that uploading the large file fails (1M limit).
      $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)));
    }

    // Turn off the max filesize.
    $this->updateFileField($field_name, $type_name, array('max_filesize' => ''));

    // Upload the big file successfully.
    $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
    $node = 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))));

    // Remove our file field.
    field_delete_field($field_name);
  }

  /**
   * Tests file extension checking.
   */
  function testFileExtension() {
    $type_name = 'article';
    $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);

    // Disable extension checking.
    $this->updateFileField($field_name, $type_name, array('file_extensions' => ''));

    // Check that the file can be uploaded with no extension checking.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
    $node = 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.');

    // Enable extension checking for text files.
    $this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt'));

    // Check that the file with the wrong extension cannot be uploaded.
    $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.');

    // Enable extension checking for text and image files.
    $this->updateFileField($field_name, $type_name, array('file_extensions' => "txt $test_file_extension"));

    // Check that the file can be uploaded with extension checking.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
    $node = 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.');

    // Remove our file field.
    field_delete_field($field_name);
  }
}

/**
 * Tests that files are uploaded to proper locations.
 */
class FileFieldPathTestCase extends FileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'File field file path tests',
      'description' => 'Test that files are uploaded to the proper location with token support.',
      'group' => 'File',
    );
  }

  /**
   * Tests the normal formatter display on node display.
   */
  function testUploadPath() {
    $field_name = strtolower($this->randomName());
    $type_name = 'article';
    $field = $this->createFileField($field_name, $type_name);
    $test_file = $this->getTestFile('text');

    // Create a new node.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);

    // Check that the file was uploaded to the file root.
    $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)));

    // Change the path to contain multiple subdirectories.
    $field = $this->updateFileField($field_name, $type_name, array('file_directory' => 'foo/bar/baz'));

    // Upload a new file into the subdirectories.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);

    // Check that the file was uploaded into the subdirectory.
    $node = 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)));

    // Check the path when used with tokens.
    // Change the path to contain multiple token directories.
    $field = $this->updateFileField($field_name, $type_name, array('file_directory' => '[current-user:uid]/[current-user:name]'));

    // Upload a new file into the token subdirectories.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);

    // Check that the file was uploaded into the subdirectory.
    $node = node_load($nid, NULL, TRUE);
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
    // Do token replacement using the same user which uploaded the file, not
    // the user running the test case.
    $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) {
    // Strip off the extension of the expected path to allow for _0, _1, etc.
    // suffixes when the file hits a duplicate name.
    $pos = strrpos($expected_path, '.');
    $base_path = substr($expected_path, 0, $pos);
    $extension = substr($expected_path, $pos + 1);

    $result = preg_match('/' . preg_quote($base_path, '/') . '(_[0-9]+)?\.' . preg_quote($extension, '/') . '/', $actual_path);
    $this->assertTrue($result, $message);
  }
}

/**
 * Tests the file token replacement in strings.
 */
class FileTokenReplaceTestCase extends FileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'File token replacement',
      'description' => 'Generates text using placeholders for dummy content to check file token replacement.',
      'group' => 'File',
    );
  }

  /**
   * Creates a file, then tests the tokens generated from it.
   */
  function testFileTokenReplacement() {
    global $language;
    $url_options = array(
      'absolute' => TRUE,
      'language' => $language,
    );

    // Create file field.
    $type_name = 'article';
    $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');
    // Coping a file to test uploads with non-latin filenames.
    $filename = drupal_dirname($test_file->uri) . '/текстовый файл.txt';
    $test_file = file_copy($test_file, $filename);

    // Create a new node with the uploaded file.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);

    // Load the node and the file.
    $node = node_load($nid, NULL, TRUE);
    $file = file_load($node->{$field_name}[LANGUAGE_NONE][0]['fid']);

    // Generate and test sanitized tokens.
    $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->language);
    $tests['[file:timestamp:short]'] = format_date($file->timestamp, 'short', '', NULL, $language->language);
    $tests['[file:owner]'] = check_plain(format_username($this->admin_user));
    $tests['[file:owner:uid]'] = $file->uid;

    // Test to make sure that we generated something for each token.
    $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');

    foreach ($tests as $input => $expected) {
      $output = token_replace($input, array('file' => $file), array('language' => $language));
      $this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', array('%token' => $input)));
    }

    // Generate and test unsanitized tokens.
    $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 FileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Private file test',
      'description' => 'Uploads a test to a private node and checks access.',
      'group' => 'File',
    );
  }

  function setUp() {
    parent::setUp(array('node_access_test', 'field_test'));
    node_access_rebuild();
    variable_set('node_access_test_private', TRUE);
  }

  /**
   * Tests file access for file uploaded to a private node.
   */
  function testPrivateFile() {
    // Use 'page' instead of 'article', so that the 'article' image field does
    // not conflict with this test. If in the future the 'page' type gets its
    // own default file or image field, this test can be made more robust by
    // using a custom node type.
    $type_name = 'page';
    $field_name = strtolower($this->randomName());
    $this->createFileField($field_name, $type_name, array('uri_scheme' => 'private'));

    // Create a field with no view access - see field_test_field_access().
    $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];
    // Ensure the file can be downloaded.
    $this->drupalGet(file_create_url($node_file->uri));
    $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
    $this->drupalLogOut();
    $this->drupalGet(file_create_url($node_file->uri));
    $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');

    // Test with the field that should deny access through field access.
    $this->drupalLogin($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];
    // Ensure the file cannot be downloaded.
    $this->drupalGet(file_create_url($node_file->uri));
    $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.');

    // Attempt to reuse the existing file when creating a new node, and confirm
    // that access is still denied.
    $edit = array();
    $edit['title'] = $this->randomName(8);
    $edit[$field_name . '[' . LANGUAGE_NONE . '][0][fid]'] = $node_file->fid;
    $this->drupalPost('node/add/page', $edit, t('Save'));
    $new_node = $this->drupalGetNodeByTitle($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->drupalGet(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.');
  }
}

/**
 * Confirm that file field submissions work correctly for anonymous visitors.
 */
class FileFieldAnonymousSubmission extends FileFieldTestCase {

  public static function getInfo() {
    return array(
      'name' => 'File form anonymous submission',
      'description' => 'Test anonymous form submission.',
      'group' => 'File',
    );
  }

  function setUp() {
    parent::setUp();

    // Allow node submissions by anonymous users.
    user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array(
      'create article content',
      'access content',
    ));
  }

  /**
   * Tests the basic node submission for an anonymous visitor.
   */
  function testAnonymousNode() {
    $bundle_label = 'Article';
    $node_title = 'Test page';

    // Load the node form.
    $this->drupalGet('node/add/article');
    $this->assertResponse(200, 'Loaded the article node form.');
    $this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));

    $edit = array(
      'title' => $node_title,
      'body[und][0][value]' => 'Test article',
      'body[und][0][format]' => 'filtered_html',
    );
    $this->drupalPost(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() {
    $bundle_label = 'Article';
    $node_title = 'Test page';

    // Load the node form.
    $this->drupalGet('node/add/article');
    $this->assertResponse(200, 'Loaded the article node form.');
    $this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));

    // Generate an image file.
    $image = $this->getTestImage();

    // Submit the form.
    $edit = array(
      'title' => $node_title,
      'body[und][0][value]' => 'Test article',
      'body[und][0][format]' => 'filtered_html',
      'files[field_image_und_0]' => drupal_realpath($image->uri),
    );
    $this->drupalPost(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_image[LANGUAGE_NONE][0]['filename'], $image->filename, 'The image was uploaded successfully.');
    }
  }

  /**
   * Tests file submission for an anonymous visitor with a missing node title.
   */
  function testAnonymousNodeWithFileWithoutTitle() {
    $this->drupalLogout();
    $this->_testNodeWithFileWithoutTitle();
  }

  /**
   * Tests file submission for an authenticated user with a missing node title.
   */
  function testAuthenticatedNodeWithFileWithoutTitle() {
    $admin_user = $this->drupalCreateUser(array(
      'bypass node access',
      'access content overview',
      'administer nodes',
    ));
    $this->drupalLogin($admin_user);
    $this->_testNodeWithFileWithoutTitle();
  }

  /**
   * Helper method to test file submissions with missing node titles.
   */
  protected function _testNodeWithFileWithoutTitle() {
    $bundle_label = 'Article';
    $node_title = 'Test page';

    // Load the node form.
    $this->drupalGet('node/add/article');
    $this->assertResponse(200, 'Loaded the article node form.');
    $this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));

    // Generate an image file.
    $image = $this->getTestImage();

    // Submit the form but exclude the title field.
    $edit = array(
      'body[und][0][value]' => 'Test article',
      'body[und][0][format]' => 'filtered_html',
      'files[field_image_und_0]' => drupal_realpath($image->uri),
    );
    $this->drupalPost(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'))));

    // Submit the form again but this time with the missing title field. This
    // should still work.
    $edit = array(
      'title' => $node_title,
    );
    $this->drupalPost(NULL, $edit, t('Save'));

    // Confirm the final submission actually worked.
    $t_args = array('@type' => $bundle_label, '%title' => $node_title);
    $this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
    $matches = array();
    if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) {
      $nid = end($matches);
      $this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.');
      $node = node_load($nid);
      $this->assertNotEqual($node, NULL, 'The node was loaded successfully.');
      $this->assertEqual($node->field_image[LANGUAGE_NONE][0]['filename'], $image->filename, 'The image was uploaded successfully.');
    }
  }

  /**
   * Generates a test image.
   *
   * @return stdClass
   *   A file object.
   */
  function getTestImage() {
    // Get a file to upload.
    $file = current($this->drupalGetTestFiles('image'));

    // Add a filesize property to files as would be read by file_load().
    $file->filesize = filesize($file->uri);

    return $file;
  }

}
