Projet

Général

Profil

Paste
Télécharger (59,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / file / tests / file.test @ db2d93dd

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, '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 : format_string('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 : format_string('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 : format_string('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 : format_string('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 : format_string('File %file is permanent.', array('%file' => $file->uri));
219
    $this->assertTrue($file->status == FILE_STATUS_PERMANENT, $message);
220
  }
221
}
222

    
223
/**
224
 * Tests adding a file to a non-node entity.
225
 */
226
class FileTaxonomyTermTestCase extends DrupalWebTestCase {
227
  protected $admin_user;
228

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

    
237
  public function setUp() {
238
    $modules[] = 'file';
239
    $modules[] = 'taxonomy';
240
    parent::setUp($modules);
241
    $this->admin_user = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer taxonomy'));
242
    $this->drupalLogin($this->admin_user);
243
  }
244

    
245
  /**
246
   * Creates a file field and attaches it to the "Tags" taxonomy vocabulary.
247
   *
248
   * @param $name
249
   *   The field name of the file field to create.
250
   * @param $uri_scheme
251
   *   The URI scheme to use for the file field (for example, "private" to
252
   *   create a field that stores private files or "public" to create a field
253
   *   that stores public files).
254
   */
255
  protected function createAttachFileField($name, $uri_scheme) {
256
    $field = array(
257
      'field_name' => $name,
258
      'type' => 'file',
259
      'settings' => array(
260
        'uri_scheme' => $uri_scheme,
261
      ),
262
      'cardinality' => 1,
263
    );
264
    field_create_field($field);
265
    // Attach an instance of it.
266
    $instance = array(
267
      'field_name' => $name,
268
      'label' => 'File',
269
      'entity_type' => 'taxonomy_term',
270
      'bundle' => 'tags',
271
      'required' => FALSE,
272
      'settings' => array(),
273
      'widget' => array(
274
        'type' => 'file_generic',
275
        'settings' => array(),
276
      ),
277
    );
278
    field_create_instance($instance);
279
  }
280

    
281
  /**
282
   * Tests that a public file can be attached to a taxonomy term.
283
   *
284
   * This is a regression test for https://www.drupal.org/node/2305017.
285
   */
286
  public function testTermFilePublic() {
287
    $this->_testTermFile('public');
288
  }
289

    
290
  /**
291
   * Tests that a private file can be attached to a taxonomy term.
292
   *
293
   * This is a regression test for https://www.drupal.org/node/2305017.
294
   */
295
  public function testTermFilePrivate() {
296
    $this->_testTermFile('private');
297
  }
298

    
299
  /**
300
   * Runs tests for attaching a file field to a taxonomy term.
301
   *
302
   * @param $uri_scheme
303
   *   The URI scheme to use for the file field, either "public" or "private".
304
   */
305
  protected function _testTermFile($uri_scheme) {
306
    $field_name = strtolower($this->randomName());
307
    $this->createAttachFileField($field_name, $uri_scheme);
308
    // Get a file to upload.
309
    $file = current($this->drupalGetTestFiles('text'));
310
    // Add a filesize property to files as would be read by file_load().
311
    $file->filesize = filesize($file->uri);
312
    $langcode = LANGUAGE_NONE;
313
    $edit = array(
314
      "name" => $this->randomName(),
315
    );
316
    // Attach a file to the term.
317
    $edit['files[' . $field_name . '_' . $langcode . '_0]'] = drupal_realpath($file->uri);
318
    $this->drupalPost("admin/structure/taxonomy/tags/add", $edit, t('Save'));
319
    // Find the term ID we just created.
320
    $tid = db_query_range('SELECT tid FROM {taxonomy_term_data} ORDER BY tid DESC', 0, 1)->fetchField();
321
    $terms = entity_load('taxonomy_term', array($tid));
322
    $term = $terms[$tid];
323
    $fid = $term->{$field_name}[LANGUAGE_NONE][0]['fid'];
324
    // Check that the uploaded file is present on the edit form.
325
    $this->drupalGet("taxonomy/term/$tid/edit");
326
    $file_input_name = $field_name . '[' . LANGUAGE_NONE . '][0][fid]';
327
    $this->assertFieldByXpath('//input[@type="hidden" and @name="' . $file_input_name . '"]', $fid, 'File is attached on edit form.');
328
    // Edit the term and change name without changing the file.
329
    $edit = array(
330
      "name" => $this->randomName(),
331
    );
332
    $this->drupalPost("taxonomy/term/$tid/edit", $edit, t('Save'));
333
    // Check that the uploaded file is still present on the edit form.
334
    $this->drupalGet("taxonomy/term/$tid/edit");
335
    $file_input_name = $field_name . '[' . LANGUAGE_NONE . '][0][fid]';
336
    $this->assertFieldByXpath('//input[@type="hidden" and @name="' . $file_input_name . '"]', $fid, 'File is attached on edit form.');
337
    // Load term while resetting the cache.
338
    $terms = entity_load('taxonomy_term', array($tid), array(), TRUE);
339
    $term = $terms[$tid];
340
    $this->assertTrue(!empty($term->{$field_name}[LANGUAGE_NONE]), 'Term has attached files.');
341
    $this->assertEqual($term->{$field_name}[LANGUAGE_NONE][0]['fid'], $fid, 'Same File ID is attached to the term.');
342
  }
343
}
344

    
345
/**
346
 * Tests the 'managed_file' element type.
347
 *
348
 * @todo Create a FileTestCase base class and move FileFieldTestCase methods
349
 *   that aren't related to fields into it.
350
 */
351
class FileManagedFileElementTestCase extends FileFieldTestCase {
352
  public static function getInfo() {
353
    return array(
354
      'name' => 'Managed file element test',
355
      'description' => 'Tests the managed_file element type.',
356
      'group' => 'File',
357
    );
358
  }
359

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

    
368
    // Perform the tests with all permutations of $form['#tree'] and
369
    // $element['#extended'].
370
    foreach (array(0, 1) as $tree) {
371
      foreach (array(0, 1) as $extended) {
372
        $test_file = $this->getTestFile('text');
373
        $path = 'file/test/' . $tree . '/' . $extended;
374
        $input_base_name = $tree ? 'nested_file' : 'file';
375

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

    
380
        // Submit a new file, without using the Upload button.
381
        $last_fid_prior = $this->getLastFileId();
382
        $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
383
        $this->drupalPost($path, $edit, t('Save'));
384
        $last_fid = $this->getLastFileId();
385
        $this->assertTrue($last_fid > $last_fid_prior, 'New file got saved.');
386
        $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Submit handler has correct file info.');
387

    
388
        // Submit no new input, but with a default file.
389
        $this->drupalPost($path . '/' . $last_fid, array(), t('Save'));
390
        $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Empty submission did not change an existing file.');
391

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

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

    
420
          // Upload, then Remove, then Submit.
421
          $this->drupalGet($path);
422
          $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
423
          if ($ajax) {
424
            $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
425
            $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
426
          }
427
          else {
428
            $this->drupalPost(NULL, $edit, t('Upload'));
429
            $this->drupalPost(NULL, array(), t('Remove'));
430
          }
431
          $this->drupalPost(NULL, array(), t('Save'));
432
          $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submission after file upload and removal was successful.');
433
        }
434
      }
435
    }
436
  }
437
}
438

    
439
/**
440
 * Tests file field widget.
441
 */
442
class FileFieldWidgetTestCase extends FileFieldTestCase {
443
  public static function getInfo() {
444
    return array(
445
      'name' => 'File field widget test',
446
      'description' => 'Tests the file field widget, single and multi-valued, with and without AJAX, with public and private files.',
447
      'group' => 'File',
448
    );
449
  }
450

    
451
  /**
452
   * Tests upload and remove buttons for a single-valued File field.
453
   */
454
  function testSingleValuedWidget() {
455
    // Use 'page' instead of 'article', so that the 'article' image field does
456
    // not conflict with this test. If in the future the 'page' type gets its
457
    // own default file or image field, this test can be made more robust by
458
    // using a custom node type.
459
    $type_name = 'page';
460
    $field_name = strtolower($this->randomName());
461
    $this->createFileField($field_name, $type_name);
462
    $field = field_info_field($field_name);
463
    $instance = field_info_instance('node', $field_name, $type_name);
464

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

    
467
    foreach (array('nojs', 'js') as $type) {
468
      // Create a new node with the uploaded file and ensure it got uploaded
469
      // successfully.
470
      // @todo This only tests a 'nojs' submission, because drupalPostAJAX()
471
      //   does not yet support file uploads.
472
      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
473
      $node = node_load($nid, NULL, TRUE);
474
      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
475
      $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
476

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

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

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

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

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

    
510
      // Save the node and ensure it does not have the file.
511
      $this->drupalPost(NULL, array(), t('Save'));
512
      $node = node_load($nid, NULL, TRUE);
513
      $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'File was successfully removed from the node.');
514
    }
515
  }
516

    
517
  /**
518
   * Tests upload and remove buttons for multiple multi-valued File fields.
519
   */
520
  function testMultiValuedWidget() {
521
    // Use 'page' instead of 'article', so that the 'article' image field does
522
    // not conflict with this test. If in the future the 'page' type gets its
523
    // own default file or image field, this test can be made more robust by
524
    // using a custom node type.
525
    $type_name = 'page';
526
    $field_name = strtolower($this->randomName());
527
    $field_name2 = strtolower($this->randomName());
528
    $this->createFileField($field_name, $type_name, array('cardinality' => 3));
529
    $this->createFileField($field_name2, $type_name, array('cardinality' => 3));
530

    
531
    $field = field_info_field($field_name);
532
    $instance = field_info_instance('node', $field_name, $type_name);
533

    
534
    $field2 = field_info_field($field_name2);
535
    $instance2 = field_info_instance('node', $field_name2, $type_name);
536

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

    
539
    foreach (array('nojs', 'js') as $type) {
540
      // Visit the node creation form, and upload 3 files for each field. Since
541
      // the field has cardinality of 3, ensure the "Upload" button is displayed
542
      // until after the 3rd file, and after that, isn't displayed. Because
543
      // SimpleTest triggers the last button with a given name, so upload to the
544
      // second field first.
545
      // @todo This is only testing a non-Ajax upload, because drupalPostAJAX()
546
      //   does not yet emulate jQuery's file upload.
547
      //
548
      $this->drupalGet("node/add/$type_name");
549
      foreach (array($field_name2, $field_name) as $each_field_name) {
550
        for ($delta = 0; $delta < 3; $delta++) {
551
          $edit = array('files[' . $each_field_name . '_' . LANGUAGE_NONE . '_' . $delta . ']' => drupal_realpath($test_file->uri));
552
          // If the Upload button doesn't exist, drupalPost() will automatically
553
          // fail with an assertion message.
554
          $this->drupalPost(NULL, $edit, t('Upload'));
555
        }
556
      }
557
      $this->assertNoFieldByXpath('//input[@type="submit"]', t('Upload'), 'After uploading 3 files for each field, the "Upload" button is no longer displayed.');
558

    
559
      $num_expected_remove_buttons = 6;
560

    
561
      foreach (array($field_name, $field_name2) as $current_field_name) {
562
        // How many uploaded files for the current field are remaining.
563
        $remaining = 3;
564
        // Test clicking each "Remove" button. For extra robustness, test them out
565
        // of sequential order. They are 0-indexed, and get renumbered after each
566
        // iteration, so array(1, 1, 0) means:
567
        // - First remove the 2nd file.
568
        // - Then remove what is then the 2nd file (was originally the 3rd file).
569
        // - Then remove the first file.
570
        foreach (array(1,1,0) as $delta) {
571
          // Ensure we have the expected number of Remove buttons, and that they
572
          // are numbered sequentially.
573
          $buttons = $this->xpath('//input[@type="submit" and @value="Remove"]');
574
          $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)));
575
          foreach ($buttons as $i => $button) {
576
            $key = $i >= $remaining ? $i - $remaining : $i;
577
            $check_field_name = $field_name2;
578
            if ($current_field_name == $field_name && $i < $remaining) {
579
              $check_field_name = $field_name;
580
            }
581

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

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

    
612
          // Ensure an "Upload" button for the current field is displayed with the
613
          // correct name.
614
          $upload_button_name = $current_field_name . '_' . LANGUAGE_NONE . '_' . $remaining . '_upload_button';
615
          $buttons = $this->xpath('//input[@type="submit" and @value="Upload" and @name=:name]', array(':name' => $upload_button_name));
616
          $this->assertTrue(is_array($buttons) && count($buttons) == 1, format_string('The upload button is displayed with the correct name (JSMode=%type).', array('%type' => $type)));
617

    
618
          // Ensure only at most one button per field is displayed.
619
          $buttons = $this->xpath('//input[@type="submit" and @value="Upload"]');
620
          $expected = $current_field_name == $field_name ? 1 : 2;
621
          $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)));
622
        }
623
      }
624

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

    
628
      // Save the node and ensure it does not have any files.
629
      $this->drupalPost(NULL, array('title' => $this->randomName()), t('Save'));
630
      $matches = array();
631
      preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
632
      $nid = $matches[1];
633
      $node = node_load($nid, NULL, TRUE);
634
      $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'Node was successfully saved without any files.');
635
    }
636
  }
637

    
638
  /**
639
   * Tests a file field with a "Private files" upload destination setting.
640
   */
641
  function testPrivateFileSetting() {
642
    // Use 'page' instead of 'article', so that the 'article' image field does
643
    // not conflict with this test. If in the future the 'page' type gets its
644
    // own default file or image field, this test can be made more robust by
645
    // using a custom node type.
646
    $type_name = 'page';
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
    $test_file = $this->getTestFile('text');
653

    
654
    // Change the field setting to make its files private, and upload a file.
655
    $edit = array('field[settings][uri_scheme]' => 'private');
656
    $this->drupalPost("admin/structure/types/manage/$type_name/fields/$field_name", $edit, t('Save settings'));
657
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
658
    $node = node_load($nid, NULL, TRUE);
659
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
660
    $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
661

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

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

    
671
    // Delete node and confirm that setting could be changed.
672
    node_delete($nid);
673
    $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_name");
674
    $this->assertFieldByXpath('//input[@id="edit-field-settings-uri-scheme-public" and not(@disabled)]', 'public', 'Upload destination setting enabled.');
675
  }
676

    
677
  /**
678
   * Tests that download restrictions on private files work on comments.
679
   */
680
  function testPrivateFileComment() {
681
    $user = $this->drupalCreateUser(array('access comments'));
682

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

    
689
    // Create a new field.
690
    $edit = array(
691
      'fields[_add_new_field][label]' => $label = $this->randomName(),
692
      'fields[_add_new_field][field_name]' => $name = strtolower($this->randomName()),
693
      'fields[_add_new_field][type]' => 'file',
694
      'fields[_add_new_field][widget_type]' => 'file_generic',
695
    );
696
    $this->drupalPost('admin/structure/types/manage/article/comment/fields', $edit, t('Save'));
697
    $edit = array('field[settings][uri_scheme]' => 'private');
698
    $this->drupalPost(NULL, $edit, t('Save field settings'));
699
    $this->drupalPost(NULL, array(), t('Save settings'));
700

    
701
    // Create node.
702
    $text_file = $this->getTestFile('text');
703
    $edit = array(
704
      'title' => $this->randomName(),
705
    );
706
    $this->drupalPost('node/add/article', $edit, t('Save'));
707
    $node = $this->drupalGetNodeByTitle($edit['title']);
708

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

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

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

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

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

    
738
    // Unpublishes node.
739
    $this->drupalLogin($this->admin_user);
740
    $edit = array(
741
      'status' => FALSE,
742
    );
743
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
744

    
745
    // Ensures normal user can no longer download the file.
746
    $this->drupalLogin($user);
747
    $this->drupalGet(file_create_url($comment_file->uri));
748
    $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
749
  }
750

    
751
}
752

    
753
/**
754
 * Tests file handling with node revisions.
755
 */
756
class FileFieldRevisionTestCase extends FileFieldTestCase {
757
  public static function getInfo() {
758
    return array(
759
      'name' => 'File field revision test',
760
      'description' => 'Test creating and deleting revisions with files attached.',
761
      'group' => 'File',
762
    );
763
  }
764

    
765
  /**
766
   * Tests creating multiple revisions of a node and managing attached files.
767
   *
768
   * Expected behaviors:
769
   *  - Adding a new revision will make another entry in the field table, but
770
   *    the original file will not be duplicated.
771
   *  - Deleting a revision should not delete the original file if the file
772
   *    is in use by another revision.
773
   *  - When the last revision that uses a file is deleted, the original file
774
   *    should be deleted also.
775
   */
776
  function testRevisions() {
777
    $type_name = 'article';
778
    $field_name = strtolower($this->randomName());
779
    $this->createFileField($field_name, $type_name);
780
    $field = field_info_field($field_name);
781
    $instance = field_info_instance('node', $field_name, $type_name);
782

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

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

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

    
791
    // Check that the file exists on disk and in the database.
792
    $node = node_load($nid, NULL, TRUE);
793
    $node_file_r1 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
794
    $node_vid_r1 = $node->vid;
795
    $this->assertFileExists($node_file_r1, 'New file saved to disk on node creation.');
796
    $this->assertFileEntryExists($node_file_r1, 'File entry exists in database on node creation.');
797
    $this->assertFileIsPermanent($node_file_r1, 'File is permanent.');
798

    
799
    // Upload another file to the same node in a new revision.
800
    $this->replaceNodeFile($test_file, $field_name, $nid);
801
    $node = node_load($nid, NULL, TRUE);
802
    $node_file_r2 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
803
    $node_vid_r2 = $node->vid;
804
    $this->assertFileExists($node_file_r2, 'Replacement file exists on disk after creating new revision.');
805
    $this->assertFileEntryExists($node_file_r2, 'Replacement file entry exists in database after creating new revision.');
806
    $this->assertFileIsPermanent($node_file_r2, 'Replacement file is permanent.');
807

    
808
    // Check that the original file is still in place on the first revision.
809
    $node = node_load($nid, $node_vid_r1, TRUE);
810
    $this->assertEqual($node_file_r1, (object) $node->{$field_name}[LANGUAGE_NONE][0], 'Original file still in place after replacing file in new revision.');
811
    $this->assertFileExists($node_file_r1, 'Original file still in place after replacing file in new revision.');
812
    $this->assertFileEntryExists($node_file_r1, 'Original file entry still in place after replacing file in new revision');
813
    $this->assertFileIsPermanent($node_file_r1, 'Original file is still permanent.');
814

    
815
    // Save a new version of the node without any changes.
816
    // Check that the file is still the same as the previous revision.
817
    $this->drupalPost('node/' . $nid . '/edit', array('revision' => '1'), t('Save'));
818
    $node = node_load($nid, NULL, TRUE);
819
    $node_file_r3 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
820
    $node_vid_r3 = $node->vid;
821
    $this->assertEqual($node_file_r2, $node_file_r3, 'Previous revision file still in place after creating a new revision without a new file.');
822
    $this->assertFileIsPermanent($node_file_r3, 'New revision file is permanent.');
823

    
824
    // Revert to the first revision and check that the original file is active.
825
    $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert'));
826
    $node = node_load($nid, NULL, TRUE);
827
    $node_file_r4 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
828
    $node_vid_r4 = $node->vid;
829
    $this->assertEqual($node_file_r1, $node_file_r4, 'Original revision file still in place after reverting to the original revision.');
830
    $this->assertFileIsPermanent($node_file_r4, 'Original revision file still permanent after reverting to the original revision.');
831

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

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

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

    
852
    // Delete the user and check that the file is also deleted.
853
    user_delete($user->uid);
854
    // TODO: This seems like a bug in File API. Clearing the stat cache should
855
    // not be necessary here. The file really is deleted, but stream wrappers
856
    // doesn't seem to think so unless we clear the PHP file stat() cache.
857
    clearstatcache();
858
    $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.');
859
    $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.');
860

    
861
    // Delete the entire node and check that the original file is deleted.
862
    $this->drupalPost('node/' . $nid . '/delete', array(), t('Delete'));
863
    $this->assertFileNotExists($node_file_r1, 'Original file is deleted after deleting the entire node with two revisions remaining.');
864
    $this->assertFileEntryNotExists($node_file_r1, 'Original file entry is deleted after deleting the entire node with two revisions remaining.');
865
  }
866
}
867

    
868
/**
869
 * Tests that formatters are working properly.
870
 */
871
class FileFieldDisplayTestCase extends FileFieldTestCase {
872
  public static function getInfo() {
873
    return array(
874
      'name' => 'File field display tests',
875
      'description' => 'Test the display of file fields in node and views.',
876
      'group' => 'File',
877
    );
878
  }
879

    
880
  /**
881
   * Tests normal formatter display on node display.
882
   */
883
  function testNodeDisplay() {
884
    $field_name = strtolower($this->randomName());
885
    $type_name = 'article';
886
    $field_settings = array(
887
      'display_field' => '1',
888
      'display_default' => '1',
889
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
890
    );
891
    $instance_settings = array(
892
      'description_field' => '1',
893
    );
894
    $widget_settings = array();
895
    $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
896
    $field = field_info_field($field_name);
897
    $instance = field_info_instance('node', $field_name, $type_name);
898

    
899
    // Create a new node *without* the file field set, and check that the field
900
    // is not shown for each node display.
901
    $node = $this->drupalCreateNode(array('type' => $type_name));
902
    $file_formatters = array('file_default', 'file_table', 'file_url_plain', 'hidden');
903
    foreach ($file_formatters as $formatter) {
904
      $edit = array(
905
        "fields[$field_name][type]" => $formatter,
906
      );
907
      $this->drupalPost("admin/structure/types/manage/$type_name/display", $edit, t('Save'));
908
      $this->drupalGet('node/' . $node->nid);
909
      $this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter)));
910
    }
911

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

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

    
918
    // Check that the default formatter is displaying with the file name.
919
    $node = node_load($nid, NULL, TRUE);
920
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
921
    $default_output = theme('file_link', array('file' => $node_file));
922
    $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
923

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

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

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

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

    
944
/**
945
 * Tests various validations.
946
 */
947
class FileFieldValidateTestCase extends FileFieldTestCase {
948
  protected $field;
949
  protected $node_type;
950

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

    
959
  /**
960
   * Tests the required property on file fields.
961
   */
962
  function testRequired() {
963
    $type_name = 'article';
964
    $field_name = strtolower($this->randomName());
965
    $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
966
    $field = field_info_field($field_name);
967
    $instance = field_info_instance('node', $field_name, $type_name);
968

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

    
971
    // Try to post a new node without uploading a file.
972
    $langcode = LANGUAGE_NONE;
973
    $edit = array("title" => $this->randomName());
974
    $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
975
    $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required file field was empty.');
976

    
977
    // Create a new node with the uploaded file.
978
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
979
    $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)));
980

    
981
    $node = node_load($nid, NULL, TRUE);
982

    
983
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
984
    $this->assertFileExists($node_file, 'File exists after uploading to the required field.');
985
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required field.');
986

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

    
991
    // Try to post a new node without uploading a file in the multivalue field.
992
    $edit = array('title' => $this->randomName());
993
    $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
994
    $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required multiple value file field was empty.');
995

    
996
    // Create a new node with the uploaded file into the multivalue field.
997
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
998
    $node = node_load($nid, NULL, TRUE);
999
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1000
    $this->assertFileExists($node_file, 'File exists after uploading to the required multiple value field.');
1001
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required multipel value field.');
1002

    
1003
    // Remove our file field.
1004
    field_delete_field($field_name);
1005
  }
1006

    
1007
  /**
1008
   * Tests the max file size validator.
1009
   */
1010
  function testFileMaxSize() {
1011
    $type_name = 'article';
1012
    $field_name = strtolower($this->randomName());
1013
    $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
1014
    $field = field_info_field($field_name);
1015
    $instance = field_info_instance('node', $field_name, $type_name);
1016

    
1017
    $small_file = $this->getTestFile('text', 131072); // 128KB.
1018
    $large_file = $this->getTestFile('text', 1310720); // 1.2MB
1019

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

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

    
1032
      // Create a new node with the small file, which should pass.
1033
      $nid = $this->uploadNodeFile($small_file, $field_name, $type_name);
1034
      $node = node_load($nid, NULL, TRUE);
1035
      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1036
      $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)));
1037
      $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)));
1038

    
1039
      // Check that uploading the large file fails (1M limit).
1040
      $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
1041
      $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)));
1042
      $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)));
1043
    }
1044

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

    
1048
    // Upload the big file successfully.
1049
    $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
1050
    $node = node_load($nid, NULL, TRUE);
1051
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1052
    $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->filesize))));
1053
    $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))));
1054

    
1055
    // Remove our file field.
1056
    field_delete_field($field_name);
1057
  }
1058

    
1059
  /**
1060
   * Tests file extension checking.
1061
   */
1062
  function testFileExtension() {
1063
    $type_name = 'article';
1064
    $field_name = strtolower($this->randomName());
1065
    $this->createFileField($field_name, $type_name);
1066
    $field = field_info_field($field_name);
1067
    $instance = field_info_instance('node', $field_name, $type_name);
1068

    
1069
    $test_file = $this->getTestFile('image');
1070
    list(, $test_file_extension) = explode('.', $test_file->filename);
1071

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

    
1075
    // Check that the file can be uploaded with no extension checking.
1076
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1077
    $node = node_load($nid, NULL, TRUE);
1078
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1079
    $this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.');
1080
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.');
1081

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

    
1085
    // Check that the file with the wrong extension cannot be uploaded.
1086
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1087
    $error_message = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => 'txt'));
1088
    $this->assertRaw($error_message, 'Node save failed when file uploaded with the wrong extension.');
1089

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

    
1093
    // Check that the file can be uploaded with extension checking.
1094
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1095
    $node = node_load($nid, NULL, TRUE);
1096
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1097
    $this->assertFileExists($node_file, 'File exists after uploading a file with extension checking.');
1098
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with extension checking.');
1099

    
1100
    // Remove our file field.
1101
    field_delete_field($field_name);
1102
  }
1103
}
1104

    
1105
/**
1106
 * Tests that files are uploaded to proper locations.
1107
 */
1108
class FileFieldPathTestCase extends FileFieldTestCase {
1109
  public static function getInfo() {
1110
    return array(
1111
      'name' => 'File field file path tests',
1112
      'description' => 'Test that files are uploaded to the proper location with token support.',
1113
      'group' => 'File',
1114
    );
1115
  }
1116

    
1117
  /**
1118
   * Tests the normal formatter display on node display.
1119
   */
1120
  function testUploadPath() {
1121
    $field_name = strtolower($this->randomName());
1122
    $type_name = 'article';
1123
    $field = $this->createFileField($field_name, $type_name);
1124
    $test_file = $this->getTestFile('text');
1125

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

    
1129
    // Check that the file was uploaded to the file root.
1130
    $node = node_load($nid, NULL, TRUE);
1131
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1132
    $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)));
1133

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

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

    
1140
    // Check that the file was uploaded into the subdirectory.
1141
    $node = node_load($nid, NULL, TRUE);
1142
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1143
    $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)));
1144

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

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

    
1152
    // Check that the file was uploaded into the subdirectory.
1153
    $node = node_load($nid, NULL, TRUE);
1154
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1155
    // Do token replacement using the same user which uploaded the file, not
1156
    // the user running the test case.
1157
    $data = array('user' => $this->admin_user);
1158
    $subdirectory = token_replace('[user:uid]/[user:name]', $data);
1159
    $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)));
1160
  }
1161

    
1162
  /**
1163
   * Asserts that a file is uploaded to the right location.
1164
   *
1165
   * @param $expected_path
1166
   *   The location where the file is expected to be uploaded. Duplicate file
1167
   *   names to not need to be taken into account.
1168
   * @param $actual_path
1169
   *   Where the file was actually uploaded.
1170
   * @param $message
1171
   *   The message to display with this assertion.
1172
   */
1173
  function assertPathMatch($expected_path, $actual_path, $message) {
1174
    // Strip off the extension of the expected path to allow for _0, _1, etc.
1175
    // suffixes when the file hits a duplicate name.
1176
    $pos = strrpos($expected_path, '.');
1177
    $base_path = substr($expected_path, 0, $pos);
1178
    $extension = substr($expected_path, $pos + 1);
1179

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

    
1185
/**
1186
 * Tests the file token replacement in strings.
1187
 */
1188
class FileTokenReplaceTestCase extends FileFieldTestCase {
1189
  public static function getInfo() {
1190
    return array(
1191
      'name' => 'File token replacement',
1192
      'description' => 'Generates text using placeholders for dummy content to check file token replacement.',
1193
      'group' => 'File',
1194
    );
1195
  }
1196

    
1197
  /**
1198
   * Creates a file, then tests the tokens generated from it.
1199
   */
1200
  function testFileTokenReplacement() {
1201
    global $language;
1202
    $url_options = array(
1203
      'absolute' => TRUE,
1204
      'language' => $language,
1205
    );
1206

    
1207
    // Create file field.
1208
    $type_name = 'article';
1209
    $field_name = 'field_' . strtolower($this->randomName());
1210
    $this->createFileField($field_name, $type_name);
1211
    $field = field_info_field($field_name);
1212
    $instance = field_info_instance('node', $field_name, $type_name);
1213

    
1214
    $test_file = $this->getTestFile('text');
1215
    // Coping a file to test uploads with non-latin filenames.
1216
    $filename = drupal_dirname($test_file->uri) . '/текстовый файл.txt';
1217
    $test_file = file_copy($test_file, $filename);
1218

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

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

    
1226
    // Generate and test sanitized tokens.
1227
    $tests = array();
1228
    $tests['[file:fid]'] = $file->fid;
1229
    $tests['[file:name]'] = check_plain($file->filename);
1230
    $tests['[file:path]'] = check_plain($file->uri);
1231
    $tests['[file:mime]'] = check_plain($file->filemime);
1232
    $tests['[file:size]'] = format_size($file->filesize);
1233
    $tests['[file:url]'] = check_plain(file_create_url($file->uri));
1234
    $tests['[file:timestamp]'] = format_date($file->timestamp, 'medium', '', NULL, $language->language);
1235
    $tests['[file:timestamp:short]'] = format_date($file->timestamp, 'short', '', NULL, $language->language);
1236
    $tests['[file:owner]'] = check_plain(format_username($this->admin_user));
1237
    $tests['[file:owner:uid]'] = $file->uid;
1238

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

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

    
1247
    // Generate and test unsanitized tokens.
1248
    $tests['[file:name]'] = $file->filename;
1249
    $tests['[file:path]'] = $file->uri;
1250
    $tests['[file:mime]'] = $file->filemime;
1251
    $tests['[file:size]'] = format_size($file->filesize);
1252

    
1253
    foreach ($tests as $input => $expected) {
1254
      $output = token_replace($input, array('file' => $file), array('language' => $language, 'sanitize' => FALSE));
1255
      $this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input)));
1256
    }
1257
  }
1258
}
1259

    
1260
/**
1261
 * Tests file access on private nodes.
1262
 */
1263
class FilePrivateTestCase extends FileFieldTestCase {
1264
  public static function getInfo() {
1265
    return array(
1266
      'name' => 'Private file test',
1267
      'description' => 'Uploads a test to a private node and checks access.',
1268
      'group' => 'File',
1269
    );
1270
  }
1271

    
1272
  function setUp() {
1273
    parent::setUp(array('node_access_test', 'field_test'));
1274
    node_access_rebuild();
1275
    variable_set('node_access_test_private', TRUE);
1276
  }
1277

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

    
1290
    // Create a field with no view access - see field_test_field_access().
1291
    $no_access_field_name = 'field_no_view_access';
1292
    $this->createFileField($no_access_field_name, $type_name, array('uri_scheme' => 'private'));
1293

    
1294
    $test_file = $this->getTestFile('text');
1295
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE));
1296
    $node = node_load($nid, NULL, TRUE);
1297
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1298
    // Ensure the file can be downloaded.
1299
    $this->drupalGet(file_create_url($node_file->uri));
1300
    $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
1301
    $this->drupalLogOut();
1302
    $this->drupalGet(file_create_url($node_file->uri));
1303
    $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
1304

    
1305
    // Test with the field that should deny access through field access.
1306
    $this->drupalLogin($this->admin_user);
1307
    $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE));
1308
    $node = node_load($nid, NULL, TRUE);
1309
    $node_file = (object) $node->{$no_access_field_name}[LANGUAGE_NONE][0];
1310
    // Ensure the file cannot be downloaded.
1311
    $this->drupalGet(file_create_url($node_file->uri));
1312
    $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.');
1313

    
1314
    // Attempt to reuse the existing file when creating a new node, and confirm
1315
    // that access is still denied.
1316
    $edit = array();
1317
    $edit['title'] = $this->randomName(8);
1318
    $edit[$field_name . '[' . LANGUAGE_NONE . '][0][fid]'] = $node_file->fid;
1319
    $this->drupalPost('node/add/page', $edit, t('Save'));
1320
    $new_node = $this->drupalGetNodeByTitle($edit['title']);
1321
    $this->assertTrue(!empty($new_node), 'Node was created.');
1322
    $this->assertUrl('node/' . $new_node->nid);
1323
    $this->assertNoRaw($node_file->filename, 'File without view field access permission does not appear after attempting to attach it to a new node.');
1324
    $this->drupalGet(file_create_url($node_file->uri));
1325
    $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.');
1326
  }
1327
}