Drupal PHP Cross Reference Content Management Systems

Source: /modules/file/tests/file.test - 1171 lines - 54093 bytes - Summary - Text - Print

   1  <?php
   2  
   3  /**
   4   * @file
   5   * Tests for file.module.
   6   */
   7  
   8  /**
   9   * Provides methods specifically for testing File module's field handling.
  10   */
  11  class FileFieldTestCase extends DrupalWebTestCase {
  12    protected $admin_user;
  13  
  14    function setUp() {
  15      // Since this is a base class for many test cases, support the same
  16      // flexibility that DrupalWebTestCase::setUp() has for the modules to be
  17      // passed in as either an array or a variable number of string arguments.
  18      $modules = func_get_args();
  19      if (isset($modules[0]) && is_array($modules[0])) {
  20        $modules = $modules[0];
  21      }
  22      $modules[] = 'file';
  23      $modules[] = 'file_module_test';
  24      parent::setUp($modules);
  25      $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'));
  26      $this->drupalLogin($this->admin_user);
  27    }
  28  
  29    /**
  30     * Retrieves a sample file of the specified type.
  31     */
  32    function getTestFile($type_name, $size = NULL) {
  33      // Get a file to upload.
  34      $file = current($this->drupalGetTestFiles($type_name, $size));
  35  
  36      // Add a filesize property to files as would be read by file_load().
  37      $file->filesize = filesize($file->uri);
  38  
  39      return $file;
  40    }
  41  
  42    /**
  43     * Retrieves the fid of the last inserted file.
  44     */
  45    function getLastFileId() {
  46      return (int) db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField();
  47    }
  48  
  49    /**
  50     * Creates a new file field.
  51     *
  52     * @param $name
  53     *   The name of the new field (all lowercase), exclude the "field_" prefix.
  54     * @param $type_name
  55     *   The node type that this field will be added to.
  56     * @param $field_settings
  57     *   A list of field settings that will be added to the defaults.
  58     * @param $instance_settings
  59     *   A list of instance settings that will be added to the instance defaults.
  60     * @param $widget_settings
  61     *   A list of widget settings that will be added to the widget defaults.
  62     */
  63    function createFileField($name, $type_name, $field_settings = array(), $instance_settings = array(), $widget_settings = array()) {
  64      $field = array(
  65        'field_name' => $name,
  66        'type' => 'file',
  67        'settings' => array(),
  68        'cardinality' => !empty($field_settings['cardinality']) ? $field_settings['cardinality'] : 1,
  69      );
  70      $field['settings'] = array_merge($field['settings'], $field_settings);
  71      field_create_field($field);
  72  
  73      $this->attachFileField($name, 'node', $type_name, $instance_settings, $widget_settings);
  74    }
  75  
  76    /**
  77     * Attaches a file field to an entity.
  78     *
  79     * @param $name
  80     *   The name of the new field (all lowercase), exclude the "field_" prefix.
  81     * @param $entity_type
  82     *   The entity type this field will be added to.
  83     * @param $bundle
  84     *   The bundle this field will be added to.
  85     * @param $field_settings
  86     *   A list of field settings that will be added to the defaults.
  87     * @param $instance_settings
  88     *   A list of instance settings that will be added to the instance defaults.
  89     * @param $widget_settings
  90     *   A list of widget settings that will be added to the widget defaults.
  91     */
  92    function attachFileField($name, $entity_type, $bundle, $instance_settings = array(), $widget_settings = array()) {
  93      $instance = array(
  94        'field_name' => $name,
  95        'label' => $name,
  96        'entity_type' => $entity_type,
  97        'bundle' => $bundle,
  98        'required' => !empty($instance_settings['required']),
  99        'settings' => array(),
 100        'widget' => array(
 101          'type' => 'file_generic',
 102          'settings' => array(),
 103        ),
 104      );
 105      $instance['settings'] = array_merge($instance['settings'], $instance_settings);
 106      $instance['widget']['settings'] = array_merge($instance['widget']['settings'], $widget_settings);
 107      field_create_instance($instance);
 108    }
 109  
 110    /**
 111     * Updates an existing file field with new settings.
 112     */
 113    function updateFileField($name, $type_name, $instance_settings = array(), $widget_settings = array()) {
 114      $instance = field_info_instance('node', $name, $type_name);
 115      $instance['settings'] = array_merge($instance['settings'], $instance_settings);
 116      $instance['widget']['settings'] = array_merge($instance['widget']['settings'], $widget_settings);
 117  
 118      field_update_instance($instance);
 119    }
 120  
 121    /**
 122     * Uploads a file to a node.
 123     */
 124    function uploadNodeFile($file, $field_name, $nid_or_type, $new_revision = TRUE, $extras = array()) {
 125      $langcode = LANGUAGE_NONE;
 126      $edit = array(
 127        "title" => $this->randomName(),
 128        'revision' => (string) (int) $new_revision,
 129      );
 130  
 131      if (is_numeric($nid_or_type)) {
 132        $nid = $nid_or_type;
 133      }
 134      else {
 135        // Add a new node.
 136        $extras['type'] = $nid_or_type;
 137        $node = $this->drupalCreateNode($extras);
 138        $nid = $node->nid;
 139        // Save at least one revision to better simulate a real site.
 140        $this->drupalCreateNode(get_object_vars($node));
 141        $node = node_load($nid, NULL, TRUE);
 142        $this->assertNotEqual($nid, $node->vid, t('Node revision exists.'));
 143      }
 144  
 145      // Attach a file to the node.
 146      $edit['files[' . $field_name . '_' . $langcode . '_0]'] = drupal_realpath($file->uri);
 147      $this->drupalPost("node/$nid/edit", $edit, t('Save'));
 148  
 149      return $nid;
 150    }
 151  
 152    /**
 153     * Removes a file from a node.
 154     *
 155     * Note that if replacing a file, it must first be removed then added again.
 156     */
 157    function removeNodeFile($nid, $new_revision = TRUE) {
 158      $edit = array(
 159        'revision' => (string) (int) $new_revision,
 160      );
 161  
 162      $this->drupalPost('node/' . $nid . '/edit', array(), t('Remove'));
 163      $this->drupalPost(NULL, $edit, t('Save'));
 164    }
 165  
 166    /**
 167     * Replaces a file within a node.
 168     */
 169    function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
 170      $edit = array(
 171        'files[' . $field_name . '_' . LANGUAGE_NONE . '_0]' => drupal_realpath($file->uri),
 172        'revision' => (string) (int) $new_revision,
 173      );
 174  
 175      $this->drupalPost('node/' . $nid . '/edit', array(), t('Remove'));
 176      $this->drupalPost(NULL, $edit, t('Save'));
 177    }
 178  
 179    /**
 180     * Asserts that a file exists physically on disk.
 181     */
 182    function assertFileExists($file, $message = NULL) {
 183      $message = isset($message) ? $message : t('File %file exists on the disk.', array('%file' => $file->uri));
 184      $this->assertTrue(is_file($file->uri), $message);
 185    }
 186  
 187    /**
 188     * Asserts that a file exists in the database.
 189     */
 190    function assertFileEntryExists($file, $message = NULL) {
 191      entity_get_controller('file')->resetCache();
 192      $db_file = file_load($file->fid);
 193      $message = isset($message) ? $message : t('File %file exists in database at the correct path.', array('%file' => $file->uri));
 194      $this->assertEqual($db_file->uri, $file->uri, $message);
 195    }
 196  
 197    /**
 198     * Asserts that a file does not exist on disk.
 199     */
 200    function assertFileNotExists($file, $message = NULL) {
 201      $message = isset($message) ? $message : t('File %file exists on the disk.', array('%file' => $file->uri));
 202      $this->assertFalse(is_file($file->uri), $message);
 203    }
 204  
 205    /**
 206     * Asserts that a file does not exist in the database.
 207     */
 208    function assertFileEntryNotExists($file, $message) {
 209      entity_get_controller('file')->resetCache();
 210      $message = isset($message) ? $message : t('File %file exists in database at the correct path.', array('%file' => $file->uri));
 211      $this->assertFalse(file_load($file->fid), $message);
 212    }
 213  
 214    /**
 215     * Asserts that a file's status is set to permanent in the database.
 216     */
 217    function assertFileIsPermanent($file, $message = NULL) {
 218      $message = isset($message) ? $message : t('File %file is permanent.', array('%file' => $file->uri));
 219      $this->assertTrue($file->status == FILE_STATUS_PERMANENT, $message);
 220    }
 221  }
 222  
 223  /**
 224   * Tests the 'managed_file' element type.
 225   *
 226   * @todo Create a FileTestCase base class and move FileFieldTestCase methods
 227   *   that aren't related to fields into it.
 228   */
 229  class FileManagedFileElementTestCase extends FileFieldTestCase {
 230    public static function getInfo() {
 231      return array(
 232        'name' => 'Managed file element test',
 233        'description' => 'Tests the managed_file element type.',
 234        'group' => 'File',
 235      );
 236    }
 237  
 238    /**
 239     * Tests the managed_file element type.
 240     */
 241    function testManagedFile() {
 242      // Check that $element['#size'] is passed to the child upload element.
 243      $this->drupalGet('file/test');
 244      $this->assertFieldByXpath('//input[@name="files[nested_file]" and @size="13"]', NULL, 'The custom #size attribute is passed to the child upload element.');
 245  
 246      // Perform the tests with all permutations of $form['#tree'] and
 247      // $element['#extended'].
 248      foreach (array(0, 1) as $tree) {
 249        foreach (array(0, 1) as $extended) {
 250          $test_file = $this->getTestFile('text');
 251          $path = 'file/test/' . $tree . '/' . $extended;
 252          $input_base_name = $tree ? 'nested_file' : 'file';
 253  
 254          // Submit without a file.
 255          $this->drupalPost($path, array(), t('Save'));
 256          $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), t('Submitted without a file.'));
 257  
 258          // Submit a new file, without using the Upload button.
 259          $last_fid_prior = $this->getLastFileId();
 260          $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
 261          $this->drupalPost($path, $edit, t('Save'));
 262          $last_fid = $this->getLastFileId();
 263          $this->assertTrue($last_fid > $last_fid_prior, t('New file got saved.'));
 264          $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), t('Submit handler has correct file info.'));
 265  
 266          // Submit no new input, but with a default file.
 267          $this->drupalPost($path . '/' . $last_fid, array(), t('Save'));
 268          $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), t('Empty submission did not change an existing file.'));
 269  
 270          // Now, test the Upload and Remove buttons, with and without Ajax.
 271          foreach (array(FALSE, TRUE) as $ajax) {
 272            // Upload, then Submit.
 273            $last_fid_prior = $this->getLastFileId();
 274            $this->drupalGet($path);
 275            $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
 276            if ($ajax) {
 277              $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
 278            }
 279            else {
 280              $this->drupalPost(NULL, $edit, t('Upload'));
 281            }
 282            $last_fid = $this->getLastFileId();
 283            $this->assertTrue($last_fid > $last_fid_prior, t('New file got uploaded.'));
 284            $this->drupalPost(NULL, array(), t('Save'));
 285            $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), t('Submit handler has correct file info.'));
 286  
 287            // Remove, then Submit.
 288            $this->drupalGet($path . '/' . $last_fid);
 289            if ($ajax) {
 290              $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
 291            }
 292            else {
 293              $this->drupalPost(NULL, array(), t('Remove'));
 294            }
 295            $this->drupalPost(NULL, array(), t('Save'));
 296            $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), t('Submission after file removal was successful.'));
 297  
 298            // Upload, then Remove, then Submit.
 299            $this->drupalGet($path);
 300            $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
 301            if ($ajax) {
 302              $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
 303              $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
 304            }
 305            else {
 306              $this->drupalPost(NULL, $edit, t('Upload'));
 307              $this->drupalPost(NULL, array(), t('Remove'));
 308            }
 309            $this->drupalPost(NULL, array(), t('Save'));
 310            $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), t('Submission after file upload and removal was successful.'));
 311          }
 312        }
 313      }
 314    }
 315  }
 316  
 317  /**
 318   * Tests file field widget.
 319   */
 320  class FileFieldWidgetTestCase extends FileFieldTestCase {
 321    public static function getInfo() {
 322      return array(
 323        'name' => 'File field widget test',
 324        'description' => 'Tests the file field widget, single and multi-valued, with and without AJAX, with public and private files.',
 325        'group' => 'File',
 326      );
 327    }
 328  
 329    /**
 330     * Tests upload and remove buttons for a single-valued File field.
 331     */
 332    function testSingleValuedWidget() {
 333      // Use 'page' instead of 'article', so that the 'article' image field does
 334      // not conflict with this test. If in the future the 'page' type gets its
 335      // own default file or image field, this test can be made more robust by
 336      // using a custom node type.
 337      $type_name = 'page';
 338      $field_name = strtolower($this->randomName());
 339      $this->createFileField($field_name, $type_name);
 340      $field = field_info_field($field_name);
 341      $instance = field_info_instance('node', $field_name, $type_name);
 342  
 343      $test_file = $this->getTestFile('text');
 344  
 345      foreach (array('nojs', 'js') as $type) {
 346        // Create a new node with the uploaded file and ensure it got uploaded
 347        // successfully.
 348        // @todo This only tests a 'nojs' submission, because drupalPostAJAX()
 349        //   does not yet support file uploads.
 350        $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
 351        $node = node_load($nid, NULL, TRUE);
 352        $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 353        $this->assertFileExists($node_file, t('New file saved to disk on node creation.'));
 354  
 355        // Ensure the file can be downloaded.
 356        $this->drupalGet(file_create_url($node_file->uri));
 357        $this->assertResponse(200, t('Confirmed that the generated URL is correct by downloading the shipped file.'));
 358  
 359        // Ensure the edit page has a remove button instead of an upload button.
 360        $this->drupalGet("node/$nid/edit");
 361        $this->assertNoFieldByXPath('//input[@type="submit"]', t('Upload'), t('Node with file does not display the "Upload" button.'));
 362        $this->assertFieldByXpath('//input[@type="submit"]', t('Remove'), t('Node with file displays the "Remove" button.'));
 363  
 364        // "Click" the remove button (emulating either a nojs or js submission).
 365        switch ($type) {
 366          case 'nojs':
 367            $this->drupalPost(NULL, array(), t('Remove'));
 368            break;
 369          case 'js':
 370            $button = $this->xpath('//input[@type="submit" and @value="' . t('Remove') . '"]');
 371            $this->drupalPostAJAX(NULL, array(), array((string) $button[0]['name'] => (string) $button[0]['value']));
 372            break;
 373        }
 374  
 375        // Ensure the page now has an upload button instead of a remove button.
 376        $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), t('After clicking the "Remove" button, it is no longer displayed.'));
 377        $this->assertFieldByXpath('//input[@type="submit"]', t('Upload'), t('After clicking the "Remove" button, the "Upload" button is displayed.'));
 378  
 379        // Save the node and ensure it does not have the file.
 380        $this->drupalPost(NULL, array(), t('Save'));
 381        $node = node_load($nid, NULL, TRUE);
 382        $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), t('File was successfully removed from the node.'));
 383      }
 384    }
 385  
 386    /**
 387     * Tests upload and remove buttons for multiple multi-valued File fields.
 388     */
 389    function testMultiValuedWidget() {
 390      // Use 'page' instead of 'article', so that the 'article' image field does
 391      // not conflict with this test. If in the future the 'page' type gets its
 392      // own default file or image field, this test can be made more robust by
 393      // using a custom node type.
 394      $type_name = 'page';
 395      $field_name = strtolower($this->randomName());
 396      $field_name2 = strtolower($this->randomName());
 397      $this->createFileField($field_name, $type_name, array('cardinality' => 3));
 398      $this->createFileField($field_name2, $type_name, array('cardinality' => 3));
 399  
 400      $field = field_info_field($field_name);
 401      $instance = field_info_instance('node', $field_name, $type_name);
 402  
 403      $field2 = field_info_field($field_name2);
 404      $instance2 = field_info_instance('node', $field_name2, $type_name);
 405  
 406      $test_file = $this->getTestFile('text');
 407  
 408      foreach (array('nojs', 'js') as $type) {
 409        // Visit the node creation form, and upload 3 files for each field. Since
 410        // the field has cardinality of 3, ensure the "Upload" button is displayed
 411        // until after the 3rd file, and after that, isn't displayed. Because
 412        // SimpleTest triggers the last button with a given name, so upload to the
 413        // second field first.
 414        // @todo This is only testing a non-Ajax upload, because drupalPostAJAX()
 415        //   does not yet emulate jQuery's file upload.
 416        //
 417        $this->drupalGet("node/add/$type_name");
 418        foreach (array($field_name2, $field_name) as $each_field_name) {
 419          for ($delta = 0; $delta < 3; $delta++) {
 420            $edit = array('files[' . $each_field_name . '_' . LANGUAGE_NONE . '_' . $delta . ']' => drupal_realpath($test_file->uri));
 421            // If the Upload button doesn't exist, drupalPost() will automatically
 422            // fail with an assertion message.
 423            $this->drupalPost(NULL, $edit, t('Upload'));
 424          }
 425        }
 426        $this->assertNoFieldByXpath('//input[@type="submit"]', t('Upload'), t('After uploading 3 files for each field, the "Upload" button is no longer displayed.'));
 427  
 428        $num_expected_remove_buttons = 6;
 429  
 430        foreach (array($field_name, $field_name2) as $current_field_name) {
 431          // How many uploaded files for the current field are remaining.
 432          $remaining = 3;
 433          // Test clicking each "Remove" button. For extra robustness, test them out
 434          // of sequential order. They are 0-indexed, and get renumbered after each
 435          // iteration, so array(1, 1, 0) means:
 436          // - First remove the 2nd file.
 437          // - Then remove what is then the 2nd file (was originally the 3rd file).
 438          // - Then remove the first file.
 439          foreach (array(1,1,0) as $delta) {
 440            // Ensure we have the expected number of Remove buttons, and that they
 441            // are numbered sequentially.
 442            $buttons = $this->xpath('//input[@type="submit" and @value="Remove"]');
 443            $this->assertTrue(is_array($buttons) && count($buttons) === $num_expected_remove_buttons, t('There are %n "Remove" buttons displayed (JSMode=%type).', array('%n' => $num_expected_remove_buttons, '%type' => $type)));
 444            foreach ($buttons as $i => $button) {
 445              $key = $i >= $remaining ? $i - $remaining : $i;
 446              $check_field_name = $field_name2;
 447              if ($current_field_name == $field_name && $i < $remaining) {
 448                $check_field_name = $field_name;
 449              }
 450  
 451              $this->assertIdentical((string) $button['name'], $check_field_name . '_' . LANGUAGE_NONE . '_' . $key. '_remove_button');
 452            }
 453  
 454            // "Click" the remove button (emulating either a nojs or js submission).
 455            $button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $delta . '_remove_button';
 456            switch ($type) {
 457              case 'nojs':
 458                // drupalPost() takes a $submit parameter that is the value of the
 459                // button whose click we want to emulate. Since we have multiple
 460                // buttons with the value "Remove", and want to control which one we
 461                // use, we change the value of the other ones to something else.
 462                // Since non-clicked buttons aren't included in the submitted POST
 463                // data, and since drupalPost() will result in $this being updated
 464                // with a newly rebuilt form, this doesn't cause problems.
 465                foreach ($buttons as $button) {
 466                  if ($button['name'] != $button_name) {
 467                    $button['value'] = 'DUMMY';
 468                  }
 469                }
 470                $this->drupalPost(NULL, array(), t('Remove'));
 471                break;
 472              case 'js':
 473                // drupalPostAJAX() lets us target the button precisely, so we don't
 474                // require the workaround used above for nojs.
 475                $this->drupalPostAJAX(NULL, array(), array($button_name => t('Remove')));
 476                break;
 477            }
 478            $num_expected_remove_buttons--;
 479            $remaining--;
 480  
 481            // Ensure an "Upload" button for the current field is displayed with the
 482            // correct name.
 483            $upload_button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $remaining . '_upload_button';
 484            $buttons = $this->xpath('//input[@type="submit" and @value="Upload" and @name=:name]', array(':name' => $upload_button_name));
 485            $this->assertTrue(is_array($buttons) && count($buttons) == 1, t('The upload button is displayed with the correct name (JSMode=%type).', array('%type' => $type)));
 486  
 487            // Ensure only at most one button per field is displayed.
 488            $buttons = $this->xpath('//input[@type="submit" and @value="Upload"]');
 489            $expected = $current_field_name == $field_name ? 1 : 2;
 490            $this->assertTrue(is_array($buttons) && count($buttons) == $expected, t('After removing a file, only one "Upload" button for each possible field is displayed (JSMode=%type).', array('%type' => $type)));
 491          }
 492        }
 493  
 494        // Ensure the page now has no Remove buttons.
 495        $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), t('After removing all files, there is no "Remove" button displayed (JSMode=%type).', array('%type' => $type)));
 496  
 497        // Save the node and ensure it does not have any files.
 498        $this->drupalPost(NULL, array('title' => $this->randomName()), t('Save'));
 499        $matches = array();
 500        preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
 501        $nid = $matches[1];
 502        $node = node_load($nid, NULL, TRUE);
 503        $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), t('Node was successfully saved without any files.'));
 504      }
 505    }
 506  
 507    /**
 508     * Tests a file field with a "Private files" upload destination setting.
 509     */
 510    function testPrivateFileSetting() {
 511      // Use 'page' instead of 'article', so that the 'article' image field does
 512      // not conflict with this test. If in the future the 'page' type gets its
 513      // own default file or image field, this test can be made more robust by
 514      // using a custom node type.
 515      $type_name = 'page';
 516      $field_name = strtolower($this->randomName());
 517      $this->createFileField($field_name, $type_name);
 518      $field = field_info_field($field_name);
 519      $instance = field_info_instance('node', $field_name, $type_name);
 520  
 521      $test_file = $this->getTestFile('text');
 522  
 523      // Change the field setting to make its files private, and upload a file.
 524      $edit = array('field[settings][uri_scheme]' => 'private');
 525      $this->drupalPost("admin/structure/types/manage/$type_name/fields/$field_name", $edit, t('Save settings'));
 526      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
 527      $node = node_load($nid, NULL, TRUE);
 528      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 529      $this->assertFileExists($node_file, t('New file saved to disk on node creation.'));
 530  
 531      // Ensure the private file is available to the user who uploaded it.
 532      $this->drupalGet(file_create_url($node_file->uri));
 533      $this->assertResponse(200, t('Confirmed that the generated URL is correct by downloading the shipped file.'));
 534  
 535      // Ensure we can't change 'uri_scheme' field settings while there are some
 536      // entities with uploaded files.
 537      $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_name");
 538      $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and @disabled="disabled"]', 'public', t('Upload destination setting disabled.'));
 539  
 540      // Delete node and confirm that setting could be changed.
 541      node_delete($nid);
 542      $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_name");
 543      $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and not(@disabled)]', 'public', t('Upload destination setting enabled.'));
 544    }
 545  
 546    /**
 547     * Tests that download restrictions on private files work on comments.
 548     */
 549    function testPrivateFileComment() {
 550      $user = $this->drupalCreateUser(array('access comments'));
 551  
 552      // Remove access comments permission from anon user.
 553      $edit = array(
 554        DRUPAL_ANONYMOUS_RID . '[access comments]' => FALSE,
 555      );
 556      $this->drupalPost('admin/people/permissions', $edit, t('Save permissions'));
 557  
 558      // Create a new field.
 559      $edit = array(
 560        'fields[_add_new_field][label]' => $label = $this->randomName(),
 561        'fields[_add_new_field][field_name]' => $name = strtolower($this->randomName()),
 562        'fields[_add_new_field][type]' => 'file',
 563        'fields[_add_new_field][widget_type]' => 'file_generic',
 564      );
 565      $this->drupalPost('admin/structure/types/manage/article/comment/fields', $edit, t('Save'));
 566      $edit = array('field[settings][uri_scheme]' => 'private');
 567      $this->drupalPost(NULL, $edit, t('Save field settings'));
 568      $this->drupalPost(NULL, array(), t('Save settings'));
 569  
 570      // Create node.
 571      $text_file = $this->getTestFile('text');
 572      $edit = array(
 573        'title' => $this->randomName(),
 574      );
 575      $this->drupalPost('node/add/article', $edit, t('Save'));
 576      $node = $this->drupalGetNodeByTitle($edit['title']);
 577  
 578      // Add a comment with a file.
 579      $text_file = $this->getTestFile('text');
 580      $edit = array(
 581        'files[field_' . $name . '_' . LANGUAGE_NONE . '_' . 0 . ']' => drupal_realpath($text_file->uri),
 582        'comment_body[' . LANGUAGE_NONE . '][0][value]' => $comment_body = $this->randomName(),
 583      );
 584      $this->drupalPost(NULL, $edit, t('Save'));
 585  
 586      // Get the comment ID.
 587      preg_match('/comment-([0-9]+)/', $this->getUrl(), $matches);
 588      $cid = $matches[1];
 589  
 590      // Log in as normal user.
 591      $this->drupalLogin($user);
 592  
 593      $comment = comment_load($cid);
 594      $comment_file = (object) $comment->{'field_' . $name}[LANGUAGE_NONE][0];
 595      $this->assertFileExists($comment_file, t('New file saved to disk on node creation.'));
 596      // Test authenticated file download.
 597      $url = file_create_url($comment_file->uri);
 598      $this->assertNotEqual($url, NULL, t('Confirmed that the URL is valid'));
 599      $this->drupalGet(file_create_url($comment_file->uri));
 600      $this->assertResponse(200, t('Confirmed that the generated URL is correct by downloading the shipped file.'));
 601  
 602      // Test anonymous file download.
 603      $this->drupalLogout();
 604      $this->drupalGet(file_create_url($comment_file->uri));
 605      $this->assertResponse(403, t('Confirmed that access is denied for the file without the needed permission.'));
 606  
 607      // Unpublishes node.
 608      $this->drupalLogin($this->admin_user);
 609      $edit = array(
 610        'status' => FALSE,
 611      );
 612      $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
 613  
 614      // Ensures normal user can no longer download the file.
 615      $this->drupalLogin($user);
 616      $this->drupalGet(file_create_url($comment_file->uri));
 617      $this->assertResponse(403, t('Confirmed that access is denied for the file without the needed permission.'));
 618    }
 619  
 620  }
 621  
 622  /**
 623   * Tests file handling with node revisions.
 624   */
 625  class FileFieldRevisionTestCase extends FileFieldTestCase {
 626    public static function getInfo() {
 627      return array(
 628        'name' => 'File field revision test',
 629        'description' => 'Test creating and deleting revisions with files attached.',
 630        'group' => 'File',
 631      );
 632    }
 633  
 634    /**
 635     * Tests creating multiple revisions of a node and managing attached files.
 636     *
 637     * Expected behaviors:
 638     *  - Adding a new revision will make another entry in the field table, but
 639     *    the original file will not be duplicated.
 640     *  - Deleting a revision should not delete the original file if the file
 641     *    is in use by another revision.
 642     *  - When the last revision that uses a file is deleted, the original file
 643     *    should be deleted also.
 644     */
 645    function testRevisions() {
 646      $type_name = 'article';
 647      $field_name = strtolower($this->randomName());
 648      $this->createFileField($field_name, $type_name);
 649      $field = field_info_field($field_name);
 650      $instance = field_info_instance('node', $field_name, $type_name);
 651  
 652      // Attach the same fields to users.
 653      $this->attachFileField($field_name, 'user', 'user');
 654  
 655      $test_file = $this->getTestFile('text');
 656  
 657      // Create a new node with the uploaded file.
 658      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
 659  
 660      // Check that the file exists on disk and in the database.
 661      $node = node_load($nid, NULL, TRUE);
 662      $node_file_r1 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 663      $node_vid_r1 = $node->vid;
 664      $this->assertFileExists($node_file_r1, t('New file saved to disk on node creation.'));
 665      $this->assertFileEntryExists($node_file_r1, t('File entry exists in database on node creation.'));
 666      $this->assertFileIsPermanent($node_file_r1, t('File is permanent.'));
 667  
 668      // Upload another file to the same node in a new revision.
 669      $this->replaceNodeFile($test_file, $field_name, $nid);
 670      $node = node_load($nid, NULL, TRUE);
 671      $node_file_r2 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 672      $node_vid_r2 = $node->vid;
 673      $this->assertFileExists($node_file_r2, t('Replacement file exists on disk after creating new revision.'));
 674      $this->assertFileEntryExists($node_file_r2, t('Replacement file entry exists in database after creating new revision.'));
 675      $this->assertFileIsPermanent($node_file_r2, t('Replacement file is permanent.'));
 676  
 677      // Check that the original file is still in place on the first revision.
 678      $node = node_load($nid, $node_vid_r1, TRUE);
 679      $this->assertEqual($node_file_r1, (object) $node->{$field_name}[LANGUAGE_NONE][0], t('Original file still in place after replacing file in new revision.'));
 680      $this->assertFileExists($node_file_r1, t('Original file still in place after replacing file in new revision.'));
 681      $this->assertFileEntryExists($node_file_r1, t('Original file entry still in place after replacing file in new revision'));
 682      $this->assertFileIsPermanent($node_file_r1, t('Original file is still permanent.'));
 683  
 684      // Save a new version of the node without any changes.
 685      // Check that the file is still the same as the previous revision.
 686      $this->drupalPost('node/' . $nid . '/edit', array('revision' => '1'), t('Save'));
 687      $node = node_load($nid, NULL, TRUE);
 688      $node_file_r3 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 689      $node_vid_r3 = $node->vid;
 690      $this->assertEqual($node_file_r2, $node_file_r3, t('Previous revision file still in place after creating a new revision without a new file.'));
 691      $this->assertFileIsPermanent($node_file_r3, t('New revision file is permanent.'));
 692  
 693      // Revert to the first revision and check that the original file is active.
 694      $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert'));
 695      $node = node_load($nid, NULL, TRUE);
 696      $node_file_r4 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 697      $node_vid_r4 = $node->vid;
 698      $this->assertEqual($node_file_r1, $node_file_r4, t('Original revision file still in place after reverting to the original revision.'));
 699      $this->assertFileIsPermanent($node_file_r4, t('Original revision file still permanent after reverting to the original revision.'));
 700  
 701      // Delete the second revision and check that the file is kept (since it is
 702      // still being used by the third revision).
 703      $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r2 . '/delete', array(), t('Delete'));
 704      $this->assertFileExists($node_file_r3, t('Second file is still available after deleting second revision, since it is being used by the third revision.'));
 705      $this->assertFileEntryExists($node_file_r3, t('Second file entry is still available after deleting second revision, since it is being used by the third revision.'));
 706      $this->assertFileIsPermanent($node_file_r3, t('Second file entry is still permanent after deleting second revision, since it is being used by the third revision.'));
 707  
 708      // Attach the second file to a user.
 709      $user = $this->drupalCreateUser();
 710      $edit = (array) $user;
 711      $edit[$field_name][LANGUAGE_NONE][0] = (array) $node_file_r3;
 712      user_save($user, $edit);
 713      $this->drupalGet('user/' . $user->uid . '/edit');
 714  
 715      // Delete the third revision and check that the file is not deleted yet.
 716      $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r3 . '/delete', array(), t('Delete'));
 717      $this->assertFileExists($node_file_r3, t('Second file is still available after deleting third revision, since it is being used by the user.'));
 718      $this->assertFileEntryExists($node_file_r3, t('Second file entry is still available after deleting third revision, since it is being used by the user.'));
 719      $this->assertFileIsPermanent($node_file_r3, t('Second file entry is still permanent after deleting third revision, since it is being used by the user.'));
 720  
 721      // Delete the user and check that the file is also deleted.
 722      user_delete($user->uid);
 723      // TODO: This seems like a bug in File API. Clearing the stat cache should
 724      // not be necessary here. The file really is deleted, but stream wrappers
 725      // doesn't seem to think so unless we clear the PHP file stat() cache.
 726      clearstatcache();
 727      $this->assertFileNotExists($node_file_r3, t('Second file is now deleted after deleting third revision, since it is no longer being used by any other nodes.'));
 728      $this->assertFileEntryNotExists($node_file_r3, t('Second file entry is now deleted after deleting third revision, since it is no longer being used by any other nodes.'));
 729  
 730      // Delete the entire node and check that the original file is deleted.
 731      $this->drupalPost('node/' . $nid . '/delete', array(), t('Delete'));
 732      $this->assertFileNotExists($node_file_r1, t('Original file is deleted after deleting the entire node with two revisions remaining.'));
 733      $this->assertFileEntryNotExists($node_file_r1, t('Original file entry is deleted after deleting the entire node with two revisions remaining.'));
 734    }
 735  }
 736  
 737  /**
 738   * Tests that formatters are working properly.
 739   */
 740  class FileFieldDisplayTestCase extends FileFieldTestCase {
 741    public static function getInfo() {
 742      return array(
 743        'name' => 'File field display tests',
 744        'description' => 'Test the display of file fields in node and views.',
 745        'group' => 'File',
 746      );
 747    }
 748  
 749    /**
 750     * Tests normal formatter display on node display.
 751     */
 752    function testNodeDisplay() {
 753      $field_name = strtolower($this->randomName());
 754      $type_name = 'article';
 755      $field_settings = array(
 756        'display_field' => '1',
 757        'display_default' => '1',
 758      );
 759      $instance_settings = array(
 760        'description_field' => '1',
 761      );
 762      $widget_settings = array();
 763      $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
 764      $field = field_info_field($field_name);
 765      $instance = field_info_instance('node', $field_name, $type_name);
 766  
 767      // Create a new node *without* the file field set, and check that the field
 768      // is not shown for each node display.
 769      $node = $this->drupalCreateNode(array('type' => $type_name));
 770      $file_formatters = array('file_default', 'file_table', 'file_url_plain', 'hidden');
 771      foreach ($file_formatters as $formatter) {
 772        $edit = array(
 773          "fields[$field_name][type]" => $formatter,
 774        );
 775        $this->drupalPost("admin/structure/types/manage/$type_name/display", $edit, t('Save'));
 776        $this->drupalGet('node/' . $node->nid);
 777        $this->assertNoText($field_name, t('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter)));
 778      }
 779  
 780      $test_file = $this->getTestFile('text');
 781  
 782      // Create a new node with the uploaded file.
 783      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
 784      $this->drupalGet('node/' . $nid . '/edit');
 785  
 786      // Check that the default formatter is displaying with the file name.
 787      $node = node_load($nid, NULL, TRUE);
 788      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 789      $default_output = theme('file_link', array('file' => $node_file));
 790      $this->assertRaw($default_output, t('Default formatter displaying correctly on full node view.'));
 791  
 792      // Turn the "display" option off and check that the file is no longer displayed.
 793      $edit = array($field_name . '[' . LANGUAGE_NONE . '][0][display]' => FALSE);
 794      $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
 795  
 796      $this->assertNoRaw($default_output, t('Field is hidden when "display" option is unchecked.'));
 797  
 798    }
 799  }
 800  
 801  /**
 802   * Tests various validations.
 803   */
 804  class FileFieldValidateTestCase extends FileFieldTestCase {
 805    protected $field;
 806    protected $node_type;
 807  
 808    public static function getInfo() {
 809      return array(
 810        'name' => 'File field validation tests',
 811        'description' => 'Tests validation functions such as file type, max file size, max size per node, and required.',
 812        'group' => 'File',
 813      );
 814    }
 815  
 816    /**
 817     * Tests the required property on file fields.
 818     */
 819    function testRequired() {
 820      $type_name = 'article';
 821      $field_name = strtolower($this->randomName());
 822      $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
 823      $field = field_info_field($field_name);
 824      $instance = field_info_instance('node', $field_name, $type_name);
 825  
 826      $test_file = $this->getTestFile('text');
 827  
 828      // Try to post a new node without uploading a file.
 829      $langcode = LANGUAGE_NONE;
 830      $edit = array("title" => $this->randomName());
 831      $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
 832      $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), t('Node save failed when required file field was empty.'));
 833  
 834      // Create a new node with the uploaded file.
 835      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
 836      $this->assertTrue($nid !== FALSE, t('uploadNodeFile(@test_file, @field_name, @type_name) succeeded', array('@test_file' => $test_file->uri, '@field_name' => $field_name, '@type_name' => $type_name)));
 837  
 838      $node = node_load($nid, NULL, TRUE);
 839  
 840      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 841      $this->assertFileExists($node_file, t('File exists after uploading to the required field.'));
 842      $this->assertFileEntryExists($node_file, t('File entry exists after uploading to the required field.'));
 843  
 844      // Try again with a multiple value field.
 845      field_delete_field($field_name);
 846      $this->createFileField($field_name, $type_name, array('cardinality' => FIELD_CARDINALITY_UNLIMITED), array('required' => '1'));
 847  
 848      // Try to post a new node without uploading a file in the multivalue field.
 849      $edit = array('title' => $this->randomName());
 850      $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
 851      $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), t('Node save failed when required multiple value file field was empty.'));
 852  
 853      // Create a new node with the uploaded file into the multivalue field.
 854      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
 855      $node = node_load($nid, NULL, TRUE);
 856      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 857      $this->assertFileExists($node_file, t('File exists after uploading to the required multiple value field.'));
 858      $this->assertFileEntryExists($node_file, t('File entry exists after uploading to the required multipel value field.'));
 859  
 860      // Remove our file field.
 861      field_delete_field($field_name);
 862    }
 863  
 864    /**
 865     * Tests the max file size validator.
 866     */
 867    function testFileMaxSize() {
 868      $type_name = 'article';
 869      $field_name = strtolower($this->randomName());
 870      $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
 871      $field = field_info_field($field_name);
 872      $instance = field_info_instance('node', $field_name, $type_name);
 873  
 874      $small_file = $this->getTestFile('text', 131072); // 128KB.
 875      $large_file = $this->getTestFile('text', 1310720); // 1.2MB
 876  
 877      // Test uploading both a large and small file with different increments.
 878      $sizes = array(
 879        '1M' => 1048576,
 880        '1024K' => 1048576,
 881        '1048576' => 1048576,
 882      );
 883  
 884      foreach ($sizes as $max_filesize => $file_limit) {
 885        // Set the max file upload size.
 886        $this->updateFileField($field_name, $type_name, array('max_filesize' => $max_filesize));
 887        $instance = field_info_instance('node', $field_name, $type_name);
 888  
 889        // Create a new node with the small file, which should pass.
 890        $nid = $this->uploadNodeFile($small_file, $field_name, $type_name);
 891        $node = node_load($nid, NULL, TRUE);
 892        $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 893        $this->assertFileExists($node_file, t('File exists after uploading a file (%filesize) under the max limit (%maxsize).', array('%filesize' => format_size($small_file->filesize), '%maxsize' => $max_filesize)));
 894        $this->assertFileEntryExists($node_file, t('File entry exists after uploading a file (%filesize) under the max limit (%maxsize).', array('%filesize' => format_size($small_file->filesize), '%maxsize' => $max_filesize)));
 895  
 896        // Check that uploading the large file fails (1M limit).
 897        $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
 898        $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)));
 899        $this->assertRaw($error_message, t('Node save failed when file (%filesize) exceeded the max upload size (%maxsize).', array('%filesize' => format_size($large_file->filesize), '%maxsize' => $max_filesize)));
 900      }
 901  
 902      // Turn off the max filesize.
 903      $this->updateFileField($field_name, $type_name, array('max_filesize' => ''));
 904  
 905      // Upload the big file successfully.
 906      $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
 907      $node = node_load($nid, NULL, TRUE);
 908      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 909      $this->assertFileExists($node_file, t('File exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->filesize))));
 910      $this->assertFileEntryExists($node_file, t('File entry exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->filesize))));
 911  
 912      // Remove our file field.
 913      field_delete_field($field_name);
 914    }
 915  
 916    /**
 917     * Tests file extension checking.
 918     */
 919    function testFileExtension() {
 920      $type_name = 'article';
 921      $field_name = strtolower($this->randomName());
 922      $this->createFileField($field_name, $type_name);
 923      $field = field_info_field($field_name);
 924      $instance = field_info_instance('node', $field_name, $type_name);
 925  
 926      $test_file = $this->getTestFile('image');
 927      list(, $test_file_extension) = explode('.', $test_file->filename);
 928  
 929      // Disable extension checking.
 930      $this->updateFileField($field_name, $type_name, array('file_extensions' => ''));
 931  
 932      // Check that the file can be uploaded with no extension checking.
 933      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
 934      $node = node_load($nid, NULL, TRUE);
 935      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 936      $this->assertFileExists($node_file, t('File exists after uploading a file with no extension checking.'));
 937      $this->assertFileEntryExists($node_file, t('File entry exists after uploading a file with no extension checking.'));
 938  
 939      // Enable extension checking for text files.
 940      $this->updateFileField($field_name, $type_name, array('file_extensions' => 'txt'));
 941  
 942      // Check that the file with the wrong extension cannot be uploaded.
 943      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
 944      $error_message = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => 'txt'));
 945      $this->assertRaw($error_message, t('Node save failed when file uploaded with the wrong extension.'));
 946  
 947      // Enable extension checking for text and image files.
 948      $this->updateFileField($field_name, $type_name, array('file_extensions' => "txt $test_file_extension"));
 949  
 950      // Check that the file can be uploaded with extension checking.
 951      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
 952      $node = node_load($nid, NULL, TRUE);
 953      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 954      $this->assertFileExists($node_file, t('File exists after uploading a file with extension checking.'));
 955      $this->assertFileEntryExists($node_file, t('File entry exists after uploading a file with extension checking.'));
 956  
 957      // Remove our file field.
 958      field_delete_field($field_name);
 959    }
 960  }
 961  
 962  /**
 963   * Tests that files are uploaded to proper locations.
 964   */
 965  class FileFieldPathTestCase extends FileFieldTestCase {
 966    public static function getInfo() {
 967      return array(
 968        'name' => 'File field file path tests',
 969        'description' => 'Test that files are uploaded to the proper location with token support.',
 970        'group' => 'File',
 971      );
 972    }
 973  
 974    /**
 975     * Tests the normal formatter display on node display.
 976     */
 977    function testUploadPath() {
 978      $field_name = strtolower($this->randomName());
 979      $type_name = 'article';
 980      $field = $this->createFileField($field_name, $type_name);
 981      $test_file = $this->getTestFile('text');
 982  
 983      // Create a new node.
 984      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
 985  
 986      // Check that the file was uploaded to the file root.
 987      $node = node_load($nid, NULL, TRUE);
 988      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
 989      $this->assertPathMatch('public://' . $test_file->filename, $node_file->uri, t('The file %file was uploaded to the correct path.', array('%file' => $node_file->uri)));
 990  
 991      // Change the path to contain multiple subdirectories.
 992      $field = $this->updateFileField($field_name, $type_name, array('file_directory' => 'foo/bar/baz'));
 993  
 994      // Upload a new file into the subdirectories.
 995      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
 996  
 997      // Check that the file was uploaded into the subdirectory.
 998      $node = node_load($nid, NULL, TRUE);
 999      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1000      $this->assertPathMatch('public://foo/bar/baz/' . $test_file->filename, $node_file->uri, t('The file %file was uploaded to the correct path.', array('%file' => $node_file->uri)));
1001  
1002      // Check the path when used with tokens.
1003      // Change the path to contain multiple token directories.
1004      $field = $this->updateFileField($field_name, $type_name, array('file_directory' => '[current-user:uid]/[current-user:name]'));
1005  
1006      // Upload a new file into the token subdirectories.
1007      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1008  
1009      // Check that the file was uploaded into the subdirectory.
1010      $node = node_load($nid, NULL, TRUE);
1011      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1012      // Do token replacement using the same user which uploaded the file, not
1013      // the user running the test case.
1014      $data = array('user' => $this->admin_user);
1015      $subdirectory = token_replace('[user:uid]/[user:name]', $data);
1016      $this->assertPathMatch('public://' . $subdirectory . '/' . $test_file->filename, $node_file->uri, t('The file %file was uploaded to the correct path with token replacements.', array('%file' => $node_file->uri)));
1017    }
1018  
1019    /**
1020     * Asserts that a file is uploaded to the right location.
1021     *
1022     * @param $expected_path
1023     *   The location where the file is expected to be uploaded. Duplicate file
1024     *   names to not need to be taken into account.
1025     * @param $actual_path
1026     *   Where the file was actually uploaded.
1027     * @param $message
1028     *   The message to display with this assertion.
1029     */
1030    function assertPathMatch($expected_path, $actual_path, $message) {
1031      // Strip off the extension of the expected path to allow for _0, _1, etc.
1032      // suffixes when the file hits a duplicate name.
1033      $pos = strrpos($expected_path, '.');
1034      $base_path = substr($expected_path, 0, $pos);
1035      $extension = substr($expected_path, $pos + 1);
1036  
1037      $result = preg_match('/' . preg_quote($base_path, '/') . '(_[0-9]+)?\.' . preg_quote($extension, '/') . '/', $actual_path);
1038      $this->assertTrue($result, $message);
1039    }
1040  }
1041  
1042  /**
1043   * Tests the file token replacement in strings.
1044   */
1045  class FileTokenReplaceTestCase extends FileFieldTestCase {
1046    public static function getInfo() {
1047      return array(
1048        'name' => 'File token replacement',
1049        'description' => 'Generates text using placeholders for dummy content to check file token replacement.',
1050        'group' => 'File',
1051      );
1052    }
1053  
1054    /**
1055     * Creates a file, then tests the tokens generated from it.
1056     */
1057    function testFileTokenReplacement() {
1058      global $language;
1059      $url_options = array(
1060        'absolute' => TRUE,
1061        'language' => $language,
1062      );
1063  
1064      // Create file field.
1065      $type_name = 'article';
1066      $field_name = 'field_' . strtolower($this->randomName());
1067      $this->createFileField($field_name, $type_name);
1068      $field = field_info_field($field_name);
1069      $instance = field_info_instance('node', $field_name, $type_name);
1070  
1071      $test_file = $this->getTestFile('text');
1072      // Coping a file to test uploads with non-latin filenames.
1073      $filename = drupal_dirname($test_file->uri) . '/текстовый файл.txt';
1074      $test_file = file_copy($test_file, $filename);
1075  
1076      // Create a new node with the uploaded file.
1077      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1078  
1079      // Load the node and the file.
1080      $node = node_load($nid, NULL, TRUE);
1081      $file = file_load($node->{$field_name}[LANGUAGE_NONE][0]['fid']);
1082  
1083      // Generate and test sanitized tokens.
1084      $tests = array();
1085      $tests['[file:fid]'] = $file->fid;
1086      $tests['[file:name]'] = check_plain($file->filename);
1087      $tests['[file:path]'] = check_plain($file->uri);
1088      $tests['[file:mime]'] = check_plain($file->filemime);
1089      $tests['[file:size]'] = format_size($file->filesize);
1090      $tests['[file:url]'] = check_plain(file_create_url($file->uri));
1091      $tests['[file:timestamp]'] = format_date($file->timestamp, 'medium', '', NULL, $language->language);
1092      $tests['[file:timestamp:short]'] = format_date($file->timestamp, 'short', '', NULL, $language->language);
1093      $tests['[file:owner]'] = check_plain(format_username($this->admin_user));
1094      $tests['[file:owner:uid]'] = $file->uid;
1095  
1096      // Test to make sure that we generated something for each token.
1097      $this->assertFalse(in_array(0, array_map('strlen', $tests)), t('No empty tokens generated.'));
1098  
1099      foreach ($tests as $input => $expected) {
1100        $output = token_replace($input, array('file' => $file), array('language' => $language));
1101        $this->assertEqual($output, $expected, t('Sanitized file token %token replaced.', array('%token' => $input)));
1102      }
1103  
1104      // Generate and test unsanitized tokens.
1105      $tests['[file:name]'] = $file->filename;
1106      $tests['[file:path]'] = $file->uri;
1107      $tests['[file:mime]'] = $file->filemime;
1108      $tests['[file:size]'] = format_size($file->filesize);
1109  
1110      foreach ($tests as $input => $expected) {
1111        $output = token_replace($input, array('file' => $file), array('language' => $language, 'sanitize' => FALSE));
1112        $this->assertEqual($output, $expected, t('Unsanitized file token %token replaced.', array('%token' => $input)));
1113      }
1114    }
1115  }
1116  
1117  /**
1118   * Tests file access on private nodes.
1119   */
1120  class FilePrivateTestCase extends FileFieldTestCase {
1121    public static function getInfo() {
1122      return array(
1123        'name' => 'Private file test',
1124        'description' => 'Uploads a test to a private node and checks access.',
1125        'group' => 'File',
1126      );
1127    }
1128  
1129    function setUp() {
1130      parent::setUp(array('node_access_test', 'field_test'));
1131      node_access_rebuild();
1132      variable_set('node_access_test_private', TRUE);
1133    }
1134  
1135    /**
1136     * Tests file access for file uploaded to a private node.
1137     */
1138    function testPrivateFile() {
1139      // Use 'page' instead of 'article', so that the 'article' image field does
1140      // not conflict with this test. If in the future the 'page' type gets its
1141      // own default file or image field, this test can be made more robust by
1142      // using a custom node type.
1143      $type_name = 'page';
1144      $field_name = strtolower($this->randomName());
1145      $this->createFileField($field_name, $type_name, array('uri_scheme' => 'private'));
1146  
1147      // Create a field with no view access - see field_test_field_access().
1148      $no_access_field_name = 'field_no_view_access';
1149      $this->createFileField($no_access_field_name, $type_name, array('uri_scheme' => 'private'));
1150  
1151      $test_file = $this->getTestFile('text');
1152      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE));
1153      $node = node_load($nid, NULL, TRUE);
1154      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1155      // Ensure the file can be downloaded.
1156      $this->drupalGet(file_create_url($node_file->uri));
1157      $this->assertResponse(200, t('Confirmed that the generated URL is correct by downloading the shipped file.'));
1158      $this->drupalLogOut();
1159      $this->drupalGet(file_create_url($node_file->uri));
1160      $this->assertResponse(403, t('Confirmed that access is denied for the file without the needed permission.'));
1161  
1162      // Test with the field that should deny access through field access.
1163      $this->drupalLogin($this->admin_user);
1164      $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE));
1165      $node = node_load($nid, NULL, TRUE);
1166      $node_file = (object) $node->{$no_access_field_name}[LANGUAGE_NONE][0];
1167      // Ensure the file cannot be downloaded.
1168      $this->drupalGet(file_create_url($node_file->uri));
1169      $this->assertResponse(403, t('Confirmed that access is denied for the file without view field access permission.'));
1170    }
1171  }

title

Description

title

Description

title

Description

title

title

Body