Projet

Général

Profil

Paste
Télécharger (61 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / file / tests / file.test @ 582db59d

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 with a file, but with an invalid form token. Ensure the file
381
        // was not saved.
382
        $last_fid_prior = $this->getLastFileId();
383
        $edit = array(
384
          'files[' . $input_base_name . ']' => drupal_realpath($test_file->uri),
385
          'form_token' => 'invalid token',
386
        );
387
        $this->drupalPost($path, $edit, t('Save'));
388
        $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
389
        $last_fid = $this->getLastFileId();
390
        $this->assertEqual($last_fid_prior, $last_fid, 'File was not saved when uploaded with an invalid form token.');
391

    
392
        // Submit a new file, without using the Upload button.
393
        $last_fid_prior = $this->getLastFileId();
394
        $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
395
        $this->drupalPost($path, $edit, t('Save'));
396
        $last_fid = $this->getLastFileId();
397
        $this->assertTrue($last_fid > $last_fid_prior, 'New file got saved.');
398
        $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Submit handler has correct file info.');
399

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

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

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

    
432
          // Upload, then Remove, then Submit.
433
          $this->drupalGet($path);
434
          $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
435
          if ($ajax) {
436
            $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
437
            $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
438
          }
439
          else {
440
            $this->drupalPost(NULL, $edit, t('Upload'));
441
            $this->drupalPost(NULL, array(), t('Remove'));
442
          }
443
          $this->drupalPost(NULL, array(), t('Save'));
444
          $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submission after file upload and removal was successful.');
445
        }
446
      }
447
    }
448
  }
449
}
450

    
451
/**
452
 * Tests file field widget.
453
 */
454
class FileFieldWidgetTestCase extends FileFieldTestCase {
455
  public static function getInfo() {
456
    return array(
457
      'name' => 'File field widget test',
458
      'description' => 'Tests the file field widget, single and multi-valued, with and without AJAX, with public and private files.',
459
      'group' => 'File',
460
    );
461
  }
462

    
463
  /**
464
   * Tests upload and remove buttons for a single-valued File field.
465
   */
466
  function testSingleValuedWidget() {
467
    // Use 'page' instead of 'article', so that the 'article' image field does
468
    // not conflict with this test. If in the future the 'page' type gets its
469
    // own default file or image field, this test can be made more robust by
470
    // using a custom node type.
471
    $type_name = 'page';
472
    $field_name = strtolower($this->randomName());
473
    $this->createFileField($field_name, $type_name);
474
    $field = field_info_field($field_name);
475
    $instance = field_info_instance('node', $field_name, $type_name);
476

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

    
479
    foreach (array('nojs', 'js') as $type) {
480
      // Create a new node with the uploaded file and ensure it got uploaded
481
      // successfully.
482
      // @todo This only tests a 'nojs' submission, because drupalPostAJAX()
483
      //   does not yet support file uploads.
484
      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
485
      $node = node_load($nid, NULL, TRUE);
486
      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
487
      $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
488

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

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

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

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

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

    
522
      // Save the node and ensure it does not have the file.
523
      $this->drupalPost(NULL, array(), t('Save'));
524
      $node = node_load($nid, NULL, TRUE);
525
      $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'File was successfully removed from the node.');
526
    }
527
  }
528

    
529
  /**
530
   * Tests upload and remove buttons for multiple multi-valued File fields.
531
   */
532
  function testMultiValuedWidget() {
533
    // Use 'page' instead of 'article', so that the 'article' image field does
534
    // not conflict with this test. If in the future the 'page' type gets its
535
    // own default file or image field, this test can be made more robust by
536
    // using a custom node type.
537
    $type_name = 'page';
538
    $field_name = strtolower($this->randomName());
539
    $field_name2 = strtolower($this->randomName());
540
    $this->createFileField($field_name, $type_name, array('cardinality' => 3));
541
    $this->createFileField($field_name2, $type_name, array('cardinality' => 3));
542

    
543
    $field = field_info_field($field_name);
544
    $instance = field_info_instance('node', $field_name, $type_name);
545

    
546
    $field2 = field_info_field($field_name2);
547
    $instance2 = field_info_instance('node', $field_name2, $type_name);
548

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

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

    
571
      $num_expected_remove_buttons = 6;
572

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

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

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

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

    
630
          // Ensure only at most one button per field is displayed.
631
          $buttons = $this->xpath('//input[@type="submit" and @value="Upload"]');
632
          $expected = $current_field_name == $field_name ? 1 : 2;
633
          $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)));
634
        }
635
      }
636

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

    
640
      // Save the node and ensure it does not have any files.
641
      $this->drupalPost(NULL, array('title' => $this->randomName()), t('Save'));
642
      $matches = array();
643
      preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
644
      $nid = $matches[1];
645
      $node = node_load($nid, NULL, TRUE);
646
      $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'Node was successfully saved without any files.');
647
    }
648
  }
649

    
650
  /**
651
   * Tests a file field with a "Private files" upload destination setting.
652
   */
653
  function testPrivateFileSetting() {
654
    // Use 'page' instead of 'article', so that the 'article' image field does
655
    // not conflict with this test. If in the future the 'page' type gets its
656
    // own default file or image field, this test can be made more robust by
657
    // using a custom node type.
658
    $type_name = 'page';
659
    $field_name = strtolower($this->randomName());
660
    $this->createFileField($field_name, $type_name);
661
    $field = field_info_field($field_name);
662
    $instance = field_info_instance('node', $field_name, $type_name);
663

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

    
666
    // Change the field setting to make its files private, and upload a file.
667
    $edit = array('field[settings][uri_scheme]' => 'private');
668
    $this->drupalPost("admin/structure/types/manage/$type_name/fields/$field_name", $edit, t('Save settings'));
669
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
670
    $node = node_load($nid, NULL, TRUE);
671
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
672
    $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
673

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

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

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

    
689
  /**
690
   * Tests that download restrictions on private files work on comments.
691
   */
692
  function testPrivateFileComment() {
693
    $user = $this->drupalCreateUser(array('access comments'));
694

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

    
701
    // Create a new field.
702
    $edit = array(
703
      'fields[_add_new_field][label]' => $label = $this->randomName(),
704
      'fields[_add_new_field][field_name]' => $name = strtolower($this->randomName()),
705
      'fields[_add_new_field][type]' => 'file',
706
      'fields[_add_new_field][widget_type]' => 'file_generic',
707
    );
708
    $this->drupalPost('admin/structure/types/manage/article/comment/fields', $edit, t('Save'));
709
    $edit = array('field[settings][uri_scheme]' => 'private');
710
    $this->drupalPost(NULL, $edit, t('Save field settings'));
711
    $this->drupalPost(NULL, array(), t('Save settings'));
712

    
713
    // Create node.
714
    $text_file = $this->getTestFile('text');
715
    $edit = array(
716
      'title' => $this->randomName(),
717
    );
718
    $this->drupalPost('node/add/article', $edit, t('Save'));
719
    $node = $this->drupalGetNodeByTitle($edit['title']);
720

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

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

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

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

    
745
    // Test anonymous file download.
746
    $this->drupalLogout();
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
    // Unpublishes node.
751
    $this->drupalLogin($this->admin_user);
752
    $edit = array(
753
      'status' => FALSE,
754
    );
755
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
756

    
757
    // Ensures normal user can no longer download the file.
758
    $this->drupalLogin($user);
759
    $this->drupalGet(file_create_url($comment_file->uri));
760
    $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
761
  }
762

    
763
}
764

    
765
/**
766
 * Tests file handling with node revisions.
767
 */
768
class FileFieldRevisionTestCase extends FileFieldTestCase {
769
  public static function getInfo() {
770
    return array(
771
      'name' => 'File field revision test',
772
      'description' => 'Test creating and deleting revisions with files attached.',
773
      'group' => 'File',
774
    );
775
  }
776

    
777
  /**
778
   * Tests creating multiple revisions of a node and managing attached files.
779
   *
780
   * Expected behaviors:
781
   *  - Adding a new revision will make another entry in the field table, but
782
   *    the original file will not be duplicated.
783
   *  - Deleting a revision should not delete the original file if the file
784
   *    is in use by another revision.
785
   *  - When the last revision that uses a file is deleted, the original file
786
   *    should be deleted also.
787
   */
788
  function testRevisions() {
789
    $type_name = 'article';
790
    $field_name = strtolower($this->randomName());
791
    $this->createFileField($field_name, $type_name);
792
    $field = field_info_field($field_name);
793
    $instance = field_info_instance('node', $field_name, $type_name);
794

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

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

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

    
803
    // Check that the file exists on disk and in the database.
804
    $node = node_load($nid, NULL, TRUE);
805
    $node_file_r1 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
806
    $node_vid_r1 = $node->vid;
807
    $this->assertFileExists($node_file_r1, 'New file saved to disk on node creation.');
808
    $this->assertFileEntryExists($node_file_r1, 'File entry exists in database on node creation.');
809
    $this->assertFileIsPermanent($node_file_r1, 'File is permanent.');
810

    
811
    // Upload another file to the same node in a new revision.
812
    $this->replaceNodeFile($test_file, $field_name, $nid);
813
    $node = node_load($nid, NULL, TRUE);
814
    $node_file_r2 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
815
    $node_vid_r2 = $node->vid;
816
    $this->assertFileExists($node_file_r2, 'Replacement file exists on disk after creating new revision.');
817
    $this->assertFileEntryExists($node_file_r2, 'Replacement file entry exists in database after creating new revision.');
818
    $this->assertFileIsPermanent($node_file_r2, 'Replacement file is permanent.');
819

    
820
    // Check that the original file is still in place on the first revision.
821
    $node = node_load($nid, $node_vid_r1, TRUE);
822
    $this->assertEqual($node_file_r1, (object) $node->{$field_name}[LANGUAGE_NONE][0], 'Original file still in place after replacing file in new revision.');
823
    $this->assertFileExists($node_file_r1, 'Original file still in place after replacing file in new revision.');
824
    $this->assertFileEntryExists($node_file_r1, 'Original file entry still in place after replacing file in new revision');
825
    $this->assertFileIsPermanent($node_file_r1, 'Original file is still permanent.');
826

    
827
    // Save a new version of the node without any changes.
828
    // Check that the file is still the same as the previous revision.
829
    $this->drupalPost('node/' . $nid . '/edit', array('revision' => '1'), t('Save'));
830
    $node = node_load($nid, NULL, TRUE);
831
    $node_file_r3 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
832
    $node_vid_r3 = $node->vid;
833
    $this->assertEqual($node_file_r2, $node_file_r3, 'Previous revision file still in place after creating a new revision without a new file.');
834
    $this->assertFileIsPermanent($node_file_r3, 'New revision file is permanent.');
835

    
836
    // Revert to the first revision and check that the original file is active.
837
    $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert'));
838
    $node = node_load($nid, NULL, TRUE);
839
    $node_file_r4 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
840
    $node_vid_r4 = $node->vid;
841
    $this->assertEqual($node_file_r1, $node_file_r4, 'Original revision file still in place after reverting to the original revision.');
842
    $this->assertFileIsPermanent($node_file_r4, 'Original revision file still permanent after reverting to the original revision.');
843

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

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

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

    
864
    // Delete the user and check that the file is also deleted.
865
    user_delete($user->uid);
866
    // TODO: This seems like a bug in File API. Clearing the stat cache should
867
    // not be necessary here. The file really is deleted, but stream wrappers
868
    // doesn't seem to think so unless we clear the PHP file stat() cache.
869
    clearstatcache();
870
    $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.');
871
    $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.');
872

    
873
    // Delete the entire node and check that the original file is deleted.
874
    $this->drupalPost('node/' . $nid . '/delete', array(), t('Delete'));
875
    $this->assertFileNotExists($node_file_r1, 'Original file is deleted after deleting the entire node with two revisions remaining.');
876
    $this->assertFileEntryNotExists($node_file_r1, 'Original file entry is deleted after deleting the entire node with two revisions remaining.');
877
  }
878
}
879

    
880
/**
881
 * Tests that formatters are working properly.
882
 */
883
class FileFieldDisplayTestCase extends FileFieldTestCase {
884
  public static function getInfo() {
885
    return array(
886
      'name' => 'File field display tests',
887
      'description' => 'Test the display of file fields in node and views.',
888
      'group' => 'File',
889
    );
890
  }
891

    
892
  /**
893
   * Tests normal formatter display on node display.
894
   */
895
  function testNodeDisplay() {
896
    $field_name = strtolower($this->randomName());
897
    $type_name = 'article';
898
    $field_settings = array(
899
      'display_field' => '1',
900
      'display_default' => '1',
901
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
902
    );
903
    $instance_settings = array(
904
      'description_field' => '1',
905
    );
906
    $widget_settings = array();
907
    $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
908
    $field = field_info_field($field_name);
909
    $instance = field_info_instance('node', $field_name, $type_name);
910

    
911
    // Create a new node *without* the file field set, and check that the field
912
    // is not shown for each node display.
913
    $node = $this->drupalCreateNode(array('type' => $type_name));
914
    $file_formatters = array('file_default', 'file_table', 'file_url_plain', 'hidden');
915
    foreach ($file_formatters as $formatter) {
916
      $edit = array(
917
        "fields[$field_name][type]" => $formatter,
918
      );
919
      $this->drupalPost("admin/structure/types/manage/$type_name/display", $edit, t('Save'));
920
      $this->drupalGet('node/' . $node->nid);
921
      $this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter)));
922
    }
923

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

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

    
930
    // Check that the default formatter is displaying with the file name.
931
    $node = node_load($nid, NULL, TRUE);
932
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
933
    $default_output = theme('file_link', array('file' => $node_file));
934
    $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
935

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

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

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

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

    
955
  /**
956
   * Tests default display of File Field.
957
   */
958
  function testDefaultFileFieldDisplay() {
959
    $field_name = strtolower($this->randomName());
960
    $type_name = 'article';
961
    $field_settings = array(
962
      'display_field' => '1',
963
      'display_default' => '0',
964
    );
965
    $instance_settings = array(
966
      'description_field' => '1',
967
    );
968
    $widget_settings = array();
969
    $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
970
    $field = field_info_field($field_name);
971
    $instance = field_info_instance('node', $field_name, $type_name);
972

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

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

    
978
    $this->drupalGet('node/' . $nid . '/edit');
979
    $this->assertFieldByXPath('//input[@type="checkbox" and @name="' . $field_name . '[und][0][display]"]', NULL, 'Default file display checkbox field exists.');
980
    $this->assertFieldByXPath('//input[@type="checkbox" and @name="' . $field_name . '[und][0][display]" and not(@checked)]', NULL, 'Default file display is off.');
981
  }
982
}
983

    
984
/**
985
 * Tests various validations.
986
 */
987
class FileFieldValidateTestCase extends FileFieldTestCase {
988
  protected $field;
989
  protected $node_type;
990

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

    
999
  /**
1000
   * Tests the required property on file fields.
1001
   */
1002
  function testRequired() {
1003
    $type_name = 'article';
1004
    $field_name = strtolower($this->randomName());
1005
    $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
1006
    $field = field_info_field($field_name);
1007
    $instance = field_info_instance('node', $field_name, $type_name);
1008

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

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

    
1017
    // Create a new node with the uploaded file.
1018
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1019
    $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)));
1020

    
1021
    $node = node_load($nid, NULL, TRUE);
1022

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

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

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

    
1036
    // Create a new node with the uploaded file into the multivalue field.
1037
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1038
    $node = node_load($nid, NULL, TRUE);
1039
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1040
    $this->assertFileExists($node_file, 'File exists after uploading to the required multiple value field.');
1041
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required multipel value field.');
1042

    
1043
    // Remove our file field.
1044
    field_delete_field($field_name);
1045
  }
1046

    
1047
  /**
1048
   * Tests the max file size validator.
1049
   */
1050
  function testFileMaxSize() {
1051
    $type_name = 'article';
1052
    $field_name = strtolower($this->randomName());
1053
    $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
1054
    $field = field_info_field($field_name);
1055
    $instance = field_info_instance('node', $field_name, $type_name);
1056

    
1057
    $small_file = $this->getTestFile('text', 131072); // 128KB.
1058
    $large_file = $this->getTestFile('text', 1310720); // 1.2MB
1059

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

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

    
1072
      // Create a new node with the small file, which should pass.
1073
      $nid = $this->uploadNodeFile($small_file, $field_name, $type_name);
1074
      $node = node_load($nid, NULL, TRUE);
1075
      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1076
      $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)));
1077
      $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)));
1078

    
1079
      // Check that uploading the large file fails (1M limit).
1080
      $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
1081
      $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)));
1082
      $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)));
1083
    }
1084

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

    
1088
    // Upload the big file successfully.
1089
    $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
1090
    $node = node_load($nid, NULL, TRUE);
1091
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1092
    $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->filesize))));
1093
    $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))));
1094

    
1095
    // Remove our file field.
1096
    field_delete_field($field_name);
1097
  }
1098

    
1099
  /**
1100
   * Tests file extension checking.
1101
   */
1102
  function testFileExtension() {
1103
    $type_name = 'article';
1104
    $field_name = strtolower($this->randomName());
1105
    $this->createFileField($field_name, $type_name);
1106
    $field = field_info_field($field_name);
1107
    $instance = field_info_instance('node', $field_name, $type_name);
1108

    
1109
    $test_file = $this->getTestFile('image');
1110
    list(, $test_file_extension) = explode('.', $test_file->filename);
1111

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

    
1115
    // Check that the file can be uploaded with no extension checking.
1116
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1117
    $node = node_load($nid, NULL, TRUE);
1118
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1119
    $this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.');
1120
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.');
1121

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

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

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

    
1133
    // Check that the file can be uploaded with extension checking.
1134
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1135
    $node = node_load($nid, NULL, TRUE);
1136
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1137
    $this->assertFileExists($node_file, 'File exists after uploading a file with extension checking.');
1138
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with extension checking.');
1139

    
1140
    // Remove our file field.
1141
    field_delete_field($field_name);
1142
  }
1143
}
1144

    
1145
/**
1146
 * Tests that files are uploaded to proper locations.
1147
 */
1148
class FileFieldPathTestCase extends FileFieldTestCase {
1149
  public static function getInfo() {
1150
    return array(
1151
      'name' => 'File field file path tests',
1152
      'description' => 'Test that files are uploaded to the proper location with token support.',
1153
      'group' => 'File',
1154
    );
1155
  }
1156

    
1157
  /**
1158
   * Tests the normal formatter display on node display.
1159
   */
1160
  function testUploadPath() {
1161
    $field_name = strtolower($this->randomName());
1162
    $type_name = 'article';
1163
    $field = $this->createFileField($field_name, $type_name);
1164
    $test_file = $this->getTestFile('text');
1165

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

    
1169
    // Check that the file was uploaded to the file root.
1170
    $node = node_load($nid, NULL, TRUE);
1171
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1172
    $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)));
1173

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

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

    
1180
    // Check that the file was uploaded into the subdirectory.
1181
    $node = node_load($nid, NULL, TRUE);
1182
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1183
    $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)));
1184

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

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

    
1192
    // Check that the file was uploaded into the subdirectory.
1193
    $node = node_load($nid, NULL, TRUE);
1194
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1195
    // Do token replacement using the same user which uploaded the file, not
1196
    // the user running the test case.
1197
    $data = array('user' => $this->admin_user);
1198
    $subdirectory = token_replace('[user:uid]/[user:name]', $data);
1199
    $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)));
1200
  }
1201

    
1202
  /**
1203
   * Asserts that a file is uploaded to the right location.
1204
   *
1205
   * @param $expected_path
1206
   *   The location where the file is expected to be uploaded. Duplicate file
1207
   *   names to not need to be taken into account.
1208
   * @param $actual_path
1209
   *   Where the file was actually uploaded.
1210
   * @param $message
1211
   *   The message to display with this assertion.
1212
   */
1213
  function assertPathMatch($expected_path, $actual_path, $message) {
1214
    // Strip off the extension of the expected path to allow for _0, _1, etc.
1215
    // suffixes when the file hits a duplicate name.
1216
    $pos = strrpos($expected_path, '.');
1217
    $base_path = substr($expected_path, 0, $pos);
1218
    $extension = substr($expected_path, $pos + 1);
1219

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

    
1225
/**
1226
 * Tests the file token replacement in strings.
1227
 */
1228
class FileTokenReplaceTestCase extends FileFieldTestCase {
1229
  public static function getInfo() {
1230
    return array(
1231
      'name' => 'File token replacement',
1232
      'description' => 'Generates text using placeholders for dummy content to check file token replacement.',
1233
      'group' => 'File',
1234
    );
1235
  }
1236

    
1237
  /**
1238
   * Creates a file, then tests the tokens generated from it.
1239
   */
1240
  function testFileTokenReplacement() {
1241
    global $language;
1242
    $url_options = array(
1243
      'absolute' => TRUE,
1244
      'language' => $language,
1245
    );
1246

    
1247
    // Create file field.
1248
    $type_name = 'article';
1249
    $field_name = 'field_' . strtolower($this->randomName());
1250
    $this->createFileField($field_name, $type_name);
1251
    $field = field_info_field($field_name);
1252
    $instance = field_info_instance('node', $field_name, $type_name);
1253

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

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

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

    
1266
    // Generate and test sanitized tokens.
1267
    $tests = array();
1268
    $tests['[file:fid]'] = $file->fid;
1269
    $tests['[file:name]'] = check_plain($file->filename);
1270
    $tests['[file:path]'] = check_plain($file->uri);
1271
    $tests['[file:mime]'] = check_plain($file->filemime);
1272
    $tests['[file:size]'] = format_size($file->filesize);
1273
    $tests['[file:url]'] = check_plain(file_create_url($file->uri));
1274
    $tests['[file:timestamp]'] = format_date($file->timestamp, 'medium', '', NULL, $language->language);
1275
    $tests['[file:timestamp:short]'] = format_date($file->timestamp, 'short', '', NULL, $language->language);
1276
    $tests['[file:owner]'] = check_plain(format_username($this->admin_user));
1277
    $tests['[file:owner:uid]'] = $file->uid;
1278

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

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

    
1287
    // Generate and test unsanitized tokens.
1288
    $tests['[file:name]'] = $file->filename;
1289
    $tests['[file:path]'] = $file->uri;
1290
    $tests['[file:mime]'] = $file->filemime;
1291
    $tests['[file:size]'] = format_size($file->filesize);
1292

    
1293
    foreach ($tests as $input => $expected) {
1294
      $output = token_replace($input, array('file' => $file), array('language' => $language, 'sanitize' => FALSE));
1295
      $this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input)));
1296
    }
1297
  }
1298
}
1299

    
1300
/**
1301
 * Tests file access on private nodes.
1302
 */
1303
class FilePrivateTestCase extends FileFieldTestCase {
1304
  public static function getInfo() {
1305
    return array(
1306
      'name' => 'Private file test',
1307
      'description' => 'Uploads a test to a private node and checks access.',
1308
      'group' => 'File',
1309
    );
1310
  }
1311

    
1312
  function setUp() {
1313
    parent::setUp(array('node_access_test', 'field_test'));
1314
    node_access_rebuild();
1315
    variable_set('node_access_test_private', TRUE);
1316
  }
1317

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

    
1330
    // Create a field with no view access - see field_test_field_access().
1331
    $no_access_field_name = 'field_no_view_access';
1332
    $this->createFileField($no_access_field_name, $type_name, array('uri_scheme' => 'private'));
1333

    
1334
    $test_file = $this->getTestFile('text');
1335
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE));
1336
    $node = node_load($nid, NULL, TRUE);
1337
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1338
    // Ensure the file can be downloaded.
1339
    $this->drupalGet(file_create_url($node_file->uri));
1340
    $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
1341
    $this->drupalLogOut();
1342
    $this->drupalGet(file_create_url($node_file->uri));
1343
    $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
1344

    
1345
    // Test with the field that should deny access through field access.
1346
    $this->drupalLogin($this->admin_user);
1347
    $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE));
1348
    $node = node_load($nid, NULL, TRUE);
1349
    $node_file = (object) $node->{$no_access_field_name}[LANGUAGE_NONE][0];
1350
    // Ensure the file cannot be downloaded.
1351
    $this->drupalGet(file_create_url($node_file->uri));
1352
    $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.');
1353

    
1354
    // Attempt to reuse the existing file when creating a new node, and confirm
1355
    // that access is still denied.
1356
    $edit = array();
1357
    $edit['title'] = $this->randomName(8);
1358
    $edit[$field_name . '[' . LANGUAGE_NONE . '][0][fid]'] = $node_file->fid;
1359
    $this->drupalPost('node/add/page', $edit, t('Save'));
1360
    $new_node = $this->drupalGetNodeByTitle($edit['title']);
1361
    $this->assertTrue(!empty($new_node), 'Node was created.');
1362
    $this->assertUrl('node/' . $new_node->nid);
1363
    $this->assertNoRaw($node_file->filename, 'File without view field access permission does not appear after attempting to attach it to a new node.');
1364
    $this->drupalGet(file_create_url($node_file->uri));
1365
    $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.');
1366
  }
1367
}