Projet

Général

Profil

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

root / drupal7 / modules / file / tests / file.test @ 134c7813

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
   * Creates a temporary file, for a specific user.
224
   *
225
   * @param string $data
226
   *   A string containing the contents of the file.
227
   * @param int $uid
228
   *   The user ID of the file owner.
229
   *
230
   * @return object
231
   *   A file object, or FALSE on error.
232
   */
233
  function createTemporaryFile($data, $uid = NULL) {
234
    $file = file_save_data($data, NULL, NULL);
235

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

    
243
    return $file;
244
  }
245
}
246

    
247
/**
248
 * Tests adding a file to a non-node entity.
249
 */
250
class FileTaxonomyTermTestCase extends DrupalWebTestCase {
251
  protected $admin_user;
252

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

    
261
  public function setUp() {
262
    $modules[] = 'file';
263
    $modules[] = 'taxonomy';
264
    parent::setUp($modules);
265
    $this->admin_user = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer taxonomy'));
266
    $this->drupalLogin($this->admin_user);
267
  }
268

    
269
  /**
270
   * Creates a file field and attaches it to the "Tags" taxonomy vocabulary.
271
   *
272
   * @param $name
273
   *   The field name of the file field to create.
274
   * @param $uri_scheme
275
   *   The URI scheme to use for the file field (for example, "private" to
276
   *   create a field that stores private files or "public" to create a field
277
   *   that stores public files).
278
   */
279
  protected function createAttachFileField($name, $uri_scheme) {
280
    $field = array(
281
      'field_name' => $name,
282
      'type' => 'file',
283
      'settings' => array(
284
        'uri_scheme' => $uri_scheme,
285
      ),
286
      'cardinality' => 1,
287
    );
288
    field_create_field($field);
289
    // Attach an instance of it.
290
    $instance = array(
291
      'field_name' => $name,
292
      'label' => 'File',
293
      'entity_type' => 'taxonomy_term',
294
      'bundle' => 'tags',
295
      'required' => FALSE,
296
      'settings' => array(),
297
      'widget' => array(
298
        'type' => 'file_generic',
299
        'settings' => array(),
300
      ),
301
    );
302
    field_create_instance($instance);
303
  }
304

    
305
  /**
306
   * Tests that a public file can be attached to a taxonomy term.
307
   *
308
   * This is a regression test for https://www.drupal.org/node/2305017.
309
   */
310
  public function testTermFilePublic() {
311
    $this->_testTermFile('public');
312
  }
313

    
314
  /**
315
   * Tests that a private file can be attached to a taxonomy term.
316
   *
317
   * This is a regression test for https://www.drupal.org/node/2305017.
318
   */
319
  public function testTermFilePrivate() {
320
    $this->_testTermFile('private');
321
  }
322

    
323
  /**
324
   * Runs tests for attaching a file field to a taxonomy term.
325
   *
326
   * @param $uri_scheme
327
   *   The URI scheme to use for the file field, either "public" or "private".
328
   */
329
  protected function _testTermFile($uri_scheme) {
330
    $field_name = strtolower($this->randomName());
331
    $this->createAttachFileField($field_name, $uri_scheme);
332
    // Get a file to upload.
333
    $file = current($this->drupalGetTestFiles('text'));
334
    // Add a filesize property to files as would be read by file_load().
335
    $file->filesize = filesize($file->uri);
336
    $langcode = LANGUAGE_NONE;
337
    $edit = array(
338
      "name" => $this->randomName(),
339
    );
340
    // Attach a file to the term.
341
    $edit['files[' . $field_name . '_' . $langcode . '_0]'] = drupal_realpath($file->uri);
342
    $this->drupalPost("admin/structure/taxonomy/tags/add", $edit, t('Save'));
343
    // Find the term ID we just created.
344
    $tid = db_query_range('SELECT tid FROM {taxonomy_term_data} ORDER BY tid DESC', 0, 1)->fetchField();
345
    $terms = entity_load('taxonomy_term', array($tid));
346
    $term = $terms[$tid];
347
    $fid = $term->{$field_name}[LANGUAGE_NONE][0]['fid'];
348
    // Check that the uploaded file is present on the edit form.
349
    $this->drupalGet("taxonomy/term/$tid/edit");
350
    $file_input_name = $field_name . '[' . LANGUAGE_NONE . '][0][fid]';
351
    $this->assertFieldByXpath('//input[@type="hidden" and @name="' . $file_input_name . '"]', $fid, 'File is attached on edit form.');
352
    // Edit the term and change name without changing the file.
353
    $edit = array(
354
      "name" => $this->randomName(),
355
    );
356
    $this->drupalPost("taxonomy/term/$tid/edit", $edit, t('Save'));
357
    // Check that the uploaded file is still present on the edit form.
358
    $this->drupalGet("taxonomy/term/$tid/edit");
359
    $file_input_name = $field_name . '[' . LANGUAGE_NONE . '][0][fid]';
360
    $this->assertFieldByXpath('//input[@type="hidden" and @name="' . $file_input_name . '"]', $fid, 'File is attached on edit form.');
361
    // Load term while resetting the cache.
362
    $terms = entity_load('taxonomy_term', array($tid), array(), TRUE);
363
    $term = $terms[$tid];
364
    $this->assertTrue(!empty($term->{$field_name}[LANGUAGE_NONE]), 'Term has attached files.');
365
    $this->assertEqual($term->{$field_name}[LANGUAGE_NONE][0]['fid'], $fid, 'Same File ID is attached to the term.');
366
  }
367
}
368

    
369
/**
370
 * Tests the 'managed_file' element type.
371
 *
372
 * @todo Create a FileTestCase base class and move FileFieldTestCase methods
373
 *   that aren't related to fields into it.
374
 */
375
class FileManagedFileElementTestCase extends FileFieldTestCase {
376
  public static function getInfo() {
377
    return array(
378
      'name' => 'Managed file element test',
379
      'description' => 'Tests the managed_file element type.',
380
      'group' => 'File',
381
    );
382
  }
383

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

    
392
    // Perform the tests with all permutations of $form['#tree'] and
393
    // $element['#extended'].
394
    foreach (array(0, 1) as $tree) {
395
      foreach (array(0, 1) as $extended) {
396
        $test_file = $this->getTestFile('text');
397
        $path = 'file/test/' . $tree . '/' . $extended;
398
        $input_base_name = $tree ? 'nested_file' : 'file';
399

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

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

    
416
        // Submit a new file, without using the Upload button.
417
        $last_fid_prior = $this->getLastFileId();
418
        $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
419
        $this->drupalPost($path, $edit, t('Save'));
420
        $last_fid = $this->getLastFileId();
421
        $this->assertTrue($last_fid > $last_fid_prior, 'New file got saved.');
422
        $this->assertRaw(t('The file id is %fid.', array('%fid' => $last_fid)), 'Submit handler has correct file info.');
423

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

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

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

    
456
          // Upload, then Remove, then Submit.
457
          $this->drupalGet($path);
458
          $edit = array('files[' . $input_base_name . ']' => drupal_realpath($test_file->uri));
459
          if ($ajax) {
460
            $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_upload_button');
461
            $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
462
          }
463
          else {
464
            $this->drupalPost(NULL, $edit, t('Upload'));
465
            $this->drupalPost(NULL, array(), t('Remove'));
466
          }
467
          $this->drupalPost(NULL, array(), t('Save'));
468
          $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submission after file upload and removal was successful.');
469
        }
470
      }
471
    }
472
  }
473
}
474

    
475
/**
476
 * Tests file field widget.
477
 */
478
class FileFieldWidgetTestCase extends FileFieldTestCase {
479
  public static function getInfo() {
480
    return array(
481
      'name' => 'File field widget test',
482
      'description' => 'Tests the file field widget, single and multi-valued, with and without AJAX, with public and private files.',
483
      'group' => 'File',
484
    );
485
  }
486

    
487
  /**
488
   * Tests upload and remove buttons for a single-valued File field.
489
   */
490
  function testSingleValuedWidget() {
491
    // Use 'page' instead of 'article', so that the 'article' image field does
492
    // not conflict with this test. If in the future the 'page' type gets its
493
    // own default file or image field, this test can be made more robust by
494
    // using a custom node type.
495
    $type_name = 'page';
496
    $field_name = strtolower($this->randomName());
497
    $this->createFileField($field_name, $type_name);
498
    $field = field_info_field($field_name);
499
    $instance = field_info_instance('node', $field_name, $type_name);
500

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

    
503
    foreach (array('nojs', 'js') as $type) {
504
      // Create a new node with the uploaded file and ensure it got uploaded
505
      // successfully.
506
      // @todo This only tests a 'nojs' submission, because drupalPostAJAX()
507
      //   does not yet support file uploads.
508
      $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
509
      $node = node_load($nid, NULL, TRUE);
510
      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
511
      $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
512

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

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

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

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

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

    
546
      // Save the node and ensure it does not have the file.
547
      $this->drupalPost(NULL, array(), t('Save'));
548
      $node = node_load($nid, NULL, TRUE);
549
      $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'File was successfully removed from the node.');
550
    }
551
  }
552

    
553
  /**
554
   * Tests exploiting the temporary file removal of another user using fid.
555
   */
556
  function testTemporaryFileRemovalExploit() {
557
    // Create a victim user.
558
    $victim_user = $this->drupalCreateUser();
559

    
560
    // Create an attacker user.
561
    $attacker_user = $this->drupalCreateUser(array(
562
      'access content',
563
      'create page content',
564
      'edit any page content',
565
    ));
566

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

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

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

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

    
584
    // Set up permissions for anonymous attacker user.
585
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
586
      'access content' => TRUE,
587
      'create page content' => TRUE,
588
      'edit any page content' => TRUE,
589
    ));
590

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

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

    
599
  /**
600
   * Helper for testing exploiting the temporary file removal using fid.
601
   *
602
   * @param int $victim_uid
603
   *   The victim user ID.
604
   * @param int $attacker_uid
605
   *   The attacker user ID.
606
   */
607
  protected function doTestTemporaryFileRemovalExploit($victim_uid, $attacker_uid) {
608
    // Use 'page' instead of 'article', so that the 'article' image field does
609
    // not conflict with this test. If in the future the 'page' type gets its
610
    // own default file or image field, this test can be made more robust by
611
    // using a custom node type.
612
    $type_name = 'page';
613
    $field_name = 'test_file_field';
614
    $this->createFileField($field_name, $type_name);
615

    
616
    $test_file = $this->getTestFile('text');
617
    foreach (array('nojs', 'js') as $type) {
618
      // Create a temporary file owned by the anonymous victim user. This will be
619
      // as if they had uploaded the file, but not saved the node they were
620
      // editing or creating.
621
      $victim_tmp_file = $this->createTemporaryFile('some text', $victim_uid);
622
      $victim_tmp_file = file_load($victim_tmp_file->fid);
623
      $this->assertTrue($victim_tmp_file->status != FILE_STATUS_PERMANENT, 'New file saved to disk is temporary.');
624
      $this->assertFalse(empty($victim_tmp_file->fid), 'New file has a fid');
625
      $this->assertEqual($victim_uid, $victim_tmp_file->uid, 'New file belongs to the victim user');
626

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

    
634
      // Attach a file to a node.
635
      $langcode = LANGUAGE_NONE;
636
      $edit['files[' . $field_name . '_' . $langcode . '_0]'] = drupal_realpath($test_file->uri);
637
      $this->drupalPost("node/add/$type_name", $edit, 'Save');
638
      $node = $this->drupalGetNodeByTitle($edit['title']);
639
      $node_file = file_load($node->{$field_name}[$langcode][0]['fid']);
640
      $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
641
      $this->assertEqual($attacker_uid, $node_file->uid, 'New file belongs to the attacker.');
642

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

    
647
      // "Click" the remove button (emulating either a nojs or js submission).
648
      // In this POST request, the attacker "guesses" the fid of the victim's
649
      // temporary file and uses that to remove this file.
650
      $this->drupalGet('node/' . $node->nid . '/edit');
651
      switch ($type) {
652
        case 'nojs':
653
          $this->drupalPost(NULL, array("{$field_name}[$langcode][0][fid]" => (string) $victim_tmp_file->fid), 'Remove');
654
          break;
655
        case 'js':
656
          $button = $this->xpath('//input[@type="submit" and @value="Remove"]');
657
          $this->drupalPostAJAX(NULL, array("{$field_name}[$langcode][0][fid]" => (string) $victim_tmp_file->fid), array((string) $button[0]['name'] => (string) $button[0]['value']));
658
          break;
659
      }
660

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

    
667
  /**
668
   * Tests upload and remove buttons for multiple multi-valued File fields.
669
   */
670
  function testMultiValuedWidget() {
671
    // Use 'page' instead of 'article', so that the 'article' image field does
672
    // not conflict with this test. If in the future the 'page' type gets its
673
    // own default file or image field, this test can be made more robust by
674
    // using a custom node type.
675
    $type_name = 'page';
676
    $field_name = strtolower($this->randomName());
677
    $field_name2 = strtolower($this->randomName());
678
    $this->createFileField($field_name, $type_name, array('cardinality' => 3));
679
    $this->createFileField($field_name2, $type_name, array('cardinality' => 3));
680

    
681
    $field = field_info_field($field_name);
682
    $instance = field_info_instance('node', $field_name, $type_name);
683

    
684
    $field2 = field_info_field($field_name2);
685
    $instance2 = field_info_instance('node', $field_name2, $type_name);
686

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

    
689
    foreach (array('nojs', 'js') as $type) {
690
      // Visit the node creation form, and upload 3 files for each field. Since
691
      // the field has cardinality of 3, ensure the "Upload" button is displayed
692
      // until after the 3rd file, and after that, isn't displayed. Because
693
      // SimpleTest triggers the last button with a given name, so upload to the
694
      // second field first.
695
      // @todo This is only testing a non-Ajax upload, because drupalPostAJAX()
696
      //   does not yet emulate jQuery's file upload.
697
      //
698
      $this->drupalGet("node/add/$type_name");
699
      foreach (array($field_name2, $field_name) as $each_field_name) {
700
        for ($delta = 0; $delta < 3; $delta++) {
701
          $edit = array('files[' . $each_field_name . '_' . LANGUAGE_NONE . '_' . $delta . ']' => drupal_realpath($test_file->uri));
702
          // If the Upload button doesn't exist, drupalPost() will automatically
703
          // fail with an assertion message.
704
          $this->drupalPost(NULL, $edit, t('Upload'));
705
        }
706
      }
707
      $this->assertNoFieldByXpath('//input[@type="submit"]', t('Upload'), 'After uploading 3 files for each field, the "Upload" button is no longer displayed.');
708

    
709
      $num_expected_remove_buttons = 6;
710

    
711
      foreach (array($field_name, $field_name2) as $current_field_name) {
712
        // How many uploaded files for the current field are remaining.
713
        $remaining = 3;
714
        // Test clicking each "Remove" button. For extra robustness, test them out
715
        // of sequential order. They are 0-indexed, and get renumbered after each
716
        // iteration, so array(1, 1, 0) means:
717
        // - First remove the 2nd file.
718
        // - Then remove what is then the 2nd file (was originally the 3rd file).
719
        // - Then remove the first file.
720
        foreach (array(1,1,0) as $delta) {
721
          // Ensure we have the expected number of Remove buttons, and that they
722
          // are numbered sequentially.
723
          $buttons = $this->xpath('//input[@type="submit" and @value="Remove"]');
724
          $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)));
725
          foreach ($buttons as $i => $button) {
726
            $key = $i >= $remaining ? $i - $remaining : $i;
727
            $check_field_name = $field_name2;
728
            if ($current_field_name == $field_name && $i < $remaining) {
729
              $check_field_name = $field_name;
730
            }
731

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

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

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

    
768
          // Ensure only at most one button per field is displayed.
769
          $buttons = $this->xpath('//input[@type="submit" and @value="Upload"]');
770
          $expected = $current_field_name == $field_name ? 1 : 2;
771
          $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)));
772
        }
773
      }
774

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

    
778
      // Save the node and ensure it does not have any files.
779
      $this->drupalPost(NULL, array('title' => $this->randomName()), t('Save'));
780
      $matches = array();
781
      preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
782
      $nid = $matches[1];
783
      $node = node_load($nid, NULL, TRUE);
784
      $this->assertTrue(empty($node->{$field_name}[LANGUAGE_NONE][0]['fid']), 'Node was successfully saved without any files.');
785
    }
786
  }
787

    
788
  /**
789
   * Tests a file field with a "Private files" upload destination setting.
790
   */
791
  function testPrivateFileSetting() {
792
    // Use 'page' instead of 'article', so that the 'article' image field does
793
    // not conflict with this test. If in the future the 'page' type gets its
794
    // own default file or image field, this test can be made more robust by
795
    // using a custom node type.
796
    $type_name = 'page';
797
    $field_name = strtolower($this->randomName());
798
    $this->createFileField($field_name, $type_name);
799
    $field = field_info_field($field_name);
800
    $instance = field_info_instance('node', $field_name, $type_name);
801

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

    
804
    // Change the field setting to make its files private, and upload a file.
805
    $edit = array('field[settings][uri_scheme]' => 'private');
806
    $this->drupalPost("admin/structure/types/manage/$type_name/fields/$field_name", $edit, t('Save settings'));
807
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
808
    $node = node_load($nid, NULL, TRUE);
809
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
810
    $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
811

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

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

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

    
827
  /**
828
   * Tests that download restrictions on private files work on comments.
829
   */
830
  function testPrivateFileComment() {
831
    $user = $this->drupalCreateUser(array('access comments'));
832

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

    
839
    // Create a new field.
840
    $edit = array(
841
      'fields[_add_new_field][label]' => $label = $this->randomName(),
842
      'fields[_add_new_field][field_name]' => $name = strtolower($this->randomName()),
843
      'fields[_add_new_field][type]' => 'file',
844
      'fields[_add_new_field][widget_type]' => 'file_generic',
845
    );
846
    $this->drupalPost('admin/structure/types/manage/article/comment/fields', $edit, t('Save'));
847
    $edit = array('field[settings][uri_scheme]' => 'private');
848
    $this->drupalPost(NULL, $edit, t('Save field settings'));
849
    $this->drupalPost(NULL, array(), t('Save settings'));
850

    
851
    // Create node.
852
    $text_file = $this->getTestFile('text');
853
    $edit = array(
854
      'title' => $this->randomName(),
855
    );
856
    $this->drupalPost('node/add/article', $edit, t('Save'));
857
    $node = $this->drupalGetNodeByTitle($edit['title']);
858

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

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

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

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

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

    
888
    // Unpublishes node.
889
    $this->drupalLogin($this->admin_user);
890
    $edit = array(
891
      'status' => FALSE,
892
    );
893
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
894

    
895
    // Ensures normal user can no longer download the file.
896
    $this->drupalLogin($user);
897
    $this->drupalGet(file_create_url($comment_file->uri));
898
    $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
899
  }
900

    
901
}
902

    
903
/**
904
 * Tests file handling with node revisions.
905
 */
906
class FileFieldRevisionTestCase extends FileFieldTestCase {
907
  public static function getInfo() {
908
    return array(
909
      'name' => 'File field revision test',
910
      'description' => 'Test creating and deleting revisions with files attached.',
911
      'group' => 'File',
912
    );
913
  }
914

    
915
  /**
916
   * Tests creating multiple revisions of a node and managing attached files.
917
   *
918
   * Expected behaviors:
919
   *  - Adding a new revision will make another entry in the field table, but
920
   *    the original file will not be duplicated.
921
   *  - Deleting a revision should not delete the original file if the file
922
   *    is in use by another revision.
923
   *  - When the last revision that uses a file is deleted, the original file
924
   *    should be deleted also.
925
   */
926
  function testRevisions() {
927
    $type_name = 'article';
928
    $field_name = strtolower($this->randomName());
929
    $this->createFileField($field_name, $type_name);
930
    $field = field_info_field($field_name);
931
    $instance = field_info_instance('node', $field_name, $type_name);
932

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

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

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

    
941
    // Check that the file exists on disk and in the database.
942
    $node = node_load($nid, NULL, TRUE);
943
    $node_file_r1 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
944
    $node_vid_r1 = $node->vid;
945
    $this->assertFileExists($node_file_r1, 'New file saved to disk on node creation.');
946
    $this->assertFileEntryExists($node_file_r1, 'File entry exists in database on node creation.');
947
    $this->assertFileIsPermanent($node_file_r1, 'File is permanent.');
948

    
949
    // Upload another file to the same node in a new revision.
950
    $this->replaceNodeFile($test_file, $field_name, $nid);
951
    $node = node_load($nid, NULL, TRUE);
952
    $node_file_r2 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
953
    $node_vid_r2 = $node->vid;
954
    $this->assertFileExists($node_file_r2, 'Replacement file exists on disk after creating new revision.');
955
    $this->assertFileEntryExists($node_file_r2, 'Replacement file entry exists in database after creating new revision.');
956
    $this->assertFileIsPermanent($node_file_r2, 'Replacement file is permanent.');
957

    
958
    // Check that the original file is still in place on the first revision.
959
    $node = node_load($nid, $node_vid_r1, TRUE);
960
    $this->assertEqual($node_file_r1, (object) $node->{$field_name}[LANGUAGE_NONE][0], 'Original file still in place after replacing file in new revision.');
961
    $this->assertFileExists($node_file_r1, 'Original file still in place after replacing file in new revision.');
962
    $this->assertFileEntryExists($node_file_r1, 'Original file entry still in place after replacing file in new revision');
963
    $this->assertFileIsPermanent($node_file_r1, 'Original file is still permanent.');
964

    
965
    // Save a new version of the node without any changes.
966
    // Check that the file is still the same as the previous revision.
967
    $this->drupalPost('node/' . $nid . '/edit', array('revision' => '1'), t('Save'));
968
    $node = node_load($nid, NULL, TRUE);
969
    $node_file_r3 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
970
    $node_vid_r3 = $node->vid;
971
    $this->assertEqual($node_file_r2, $node_file_r3, 'Previous revision file still in place after creating a new revision without a new file.');
972
    $this->assertFileIsPermanent($node_file_r3, 'New revision file is permanent.');
973

    
974
    // Revert to the first revision and check that the original file is active.
975
    $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert'));
976
    $node = node_load($nid, NULL, TRUE);
977
    $node_file_r4 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
978
    $node_vid_r4 = $node->vid;
979
    $this->assertEqual($node_file_r1, $node_file_r4, 'Original revision file still in place after reverting to the original revision.');
980
    $this->assertFileIsPermanent($node_file_r4, 'Original revision file still permanent after reverting to the original revision.');
981

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

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

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

    
1002
    // Delete the user and check that the file is also deleted.
1003
    user_delete($user->uid);
1004
    // TODO: This seems like a bug in File API. Clearing the stat cache should
1005
    // not be necessary here. The file really is deleted, but stream wrappers
1006
    // doesn't seem to think so unless we clear the PHP file stat() cache.
1007
    clearstatcache();
1008
    $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.');
1009
    $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.');
1010

    
1011
    // Delete the entire node and check that the original file is deleted.
1012
    $this->drupalPost('node/' . $nid . '/delete', array(), t('Delete'));
1013
    $this->assertFileNotExists($node_file_r1, 'Original file is deleted after deleting the entire node with two revisions remaining.');
1014
    $this->assertFileEntryNotExists($node_file_r1, 'Original file entry is deleted after deleting the entire node with two revisions remaining.');
1015
  }
1016
}
1017

    
1018
/**
1019
 * Tests that formatters are working properly.
1020
 */
1021
class FileFieldDisplayTestCase extends FileFieldTestCase {
1022
  public static function getInfo() {
1023
    return array(
1024
      'name' => 'File field display tests',
1025
      'description' => 'Test the display of file fields in node and views.',
1026
      'group' => 'File',
1027
    );
1028
  }
1029

    
1030
  /**
1031
   * Tests normal formatter display on node display.
1032
   */
1033
  function testNodeDisplay() {
1034
    $field_name = strtolower($this->randomName());
1035
    $type_name = 'article';
1036
    $field_settings = array(
1037
      'display_field' => '1',
1038
      'display_default' => '1',
1039
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
1040
    );
1041
    $instance_settings = array(
1042
      'description_field' => '1',
1043
    );
1044
    $widget_settings = array();
1045
    $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
1046
    $field = field_info_field($field_name);
1047
    $instance = field_info_instance('node', $field_name, $type_name);
1048

    
1049
    // Create a new node *without* the file field set, and check that the field
1050
    // is not shown for each node display.
1051
    $node = $this->drupalCreateNode(array('type' => $type_name));
1052
    $file_formatters = array('file_default', 'file_table', 'file_url_plain', 'hidden');
1053
    foreach ($file_formatters as $formatter) {
1054
      $edit = array(
1055
        "fields[$field_name][type]" => $formatter,
1056
      );
1057
      $this->drupalPost("admin/structure/types/manage/$type_name/display", $edit, t('Save'));
1058
      $this->drupalGet('node/' . $node->nid);
1059
      $this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter)));
1060
    }
1061

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

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

    
1068
    // Check that the default formatter is displaying with the file name.
1069
    $node = node_load($nid, NULL, TRUE);
1070
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1071
    $default_output = theme('file_link', array('file' => $node_file));
1072
    $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
1073

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

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

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

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

    
1093
  /**
1094
   * Tests default display of File Field.
1095
   */
1096
  function testDefaultFileFieldDisplay() {
1097
    $field_name = strtolower($this->randomName());
1098
    $type_name = 'article';
1099
    $field_settings = array(
1100
      'display_field' => '1',
1101
      'display_default' => '0',
1102
    );
1103
    $instance_settings = array(
1104
      'description_field' => '1',
1105
    );
1106
    $widget_settings = array();
1107
    $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
1108
    $field = field_info_field($field_name);
1109
    $instance = field_info_instance('node', $field_name, $type_name);
1110

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

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

    
1116
    $this->drupalGet('node/' . $nid . '/edit');
1117
    $this->assertFieldByXPath('//input[@type="checkbox" and @name="' . $field_name . '[und][0][display]"]', NULL, 'Default file display checkbox field exists.');
1118
    $this->assertFieldByXPath('//input[@type="checkbox" and @name="' . $field_name . '[und][0][display]" and not(@checked)]', NULL, 'Default file display is off.');
1119
  }
1120
}
1121

    
1122
/**
1123
 * Tests various validations.
1124
 */
1125
class FileFieldValidateTestCase extends FileFieldTestCase {
1126
  protected $field;
1127
  protected $node_type;
1128

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

    
1137
  /**
1138
   * Tests the required property on file fields.
1139
   */
1140
  function testRequired() {
1141
    $type_name = 'article';
1142
    $field_name = strtolower($this->randomName());
1143
    $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
1144
    $field = field_info_field($field_name);
1145
    $instance = field_info_instance('node', $field_name, $type_name);
1146

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

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

    
1155
    // Create a new node with the uploaded file.
1156
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1157
    $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)));
1158

    
1159
    $node = node_load($nid, NULL, TRUE);
1160

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

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

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

    
1174
    // Create a new node with the uploaded file into the multivalue field.
1175
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1176
    $node = node_load($nid, NULL, TRUE);
1177
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1178
    $this->assertFileExists($node_file, 'File exists after uploading to the required multiple value field.');
1179
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required multipel value field.');
1180

    
1181
    // Remove our file field.
1182
    field_delete_field($field_name);
1183
  }
1184

    
1185
  /**
1186
   * Tests the max file size validator.
1187
   */
1188
  function testFileMaxSize() {
1189
    $type_name = 'article';
1190
    $field_name = strtolower($this->randomName());
1191
    $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
1192
    $field = field_info_field($field_name);
1193
    $instance = field_info_instance('node', $field_name, $type_name);
1194

    
1195
    $small_file = $this->getTestFile('text', 131072); // 128KB.
1196
    $large_file = $this->getTestFile('text', 1310720); // 1.2MB
1197

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

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

    
1210
      // Create a new node with the small file, which should pass.
1211
      $nid = $this->uploadNodeFile($small_file, $field_name, $type_name);
1212
      $node = node_load($nid, NULL, TRUE);
1213
      $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1214
      $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)));
1215
      $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)));
1216

    
1217
      // Check that uploading the large file fails (1M limit).
1218
      $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
1219
      $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)));
1220
      $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)));
1221
    }
1222

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

    
1226
    // Upload the big file successfully.
1227
    $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
1228
    $node = node_load($nid, NULL, TRUE);
1229
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1230
    $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) with no max limit.', array('%filesize' => format_size($large_file->filesize))));
1231
    $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))));
1232

    
1233
    // Remove our file field.
1234
    field_delete_field($field_name);
1235
  }
1236

    
1237
  /**
1238
   * Tests file extension checking.
1239
   */
1240
  function testFileExtension() {
1241
    $type_name = 'article';
1242
    $field_name = strtolower($this->randomName());
1243
    $this->createFileField($field_name, $type_name);
1244
    $field = field_info_field($field_name);
1245
    $instance = field_info_instance('node', $field_name, $type_name);
1246

    
1247
    $test_file = $this->getTestFile('image');
1248
    list(, $test_file_extension) = explode('.', $test_file->filename);
1249

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

    
1253
    // Check that the file can be uploaded with no extension checking.
1254
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1255
    $node = node_load($nid, NULL, TRUE);
1256
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1257
    $this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.');
1258
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.');
1259

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

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

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

    
1271
    // Check that the file can be uploaded with extension checking.
1272
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
1273
    $node = node_load($nid, NULL, TRUE);
1274
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1275
    $this->assertFileExists($node_file, 'File exists after uploading a file with extension checking.');
1276
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with extension checking.');
1277

    
1278
    // Remove our file field.
1279
    field_delete_field($field_name);
1280
  }
1281
}
1282

    
1283
/**
1284
 * Tests that files are uploaded to proper locations.
1285
 */
1286
class FileFieldPathTestCase extends FileFieldTestCase {
1287
  public static function getInfo() {
1288
    return array(
1289
      'name' => 'File field file path tests',
1290
      'description' => 'Test that files are uploaded to the proper location with token support.',
1291
      'group' => 'File',
1292
    );
1293
  }
1294

    
1295
  /**
1296
   * Tests the normal formatter display on node display.
1297
   */
1298
  function testUploadPath() {
1299
    $field_name = strtolower($this->randomName());
1300
    $type_name = 'article';
1301
    $field = $this->createFileField($field_name, $type_name);
1302
    $test_file = $this->getTestFile('text');
1303

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

    
1307
    // Check that the file was uploaded to the file root.
1308
    $node = node_load($nid, NULL, TRUE);
1309
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1310
    $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)));
1311

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

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

    
1318
    // Check that the file was uploaded into the subdirectory.
1319
    $node = node_load($nid, NULL, TRUE);
1320
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1321
    $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)));
1322

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

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

    
1330
    // Check that the file was uploaded into the subdirectory.
1331
    $node = node_load($nid, NULL, TRUE);
1332
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1333
    // Do token replacement using the same user which uploaded the file, not
1334
    // the user running the test case.
1335
    $data = array('user' => $this->admin_user);
1336
    $subdirectory = token_replace('[user:uid]/[user:name]', $data);
1337
    $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)));
1338
  }
1339

    
1340
  /**
1341
   * Asserts that a file is uploaded to the right location.
1342
   *
1343
   * @param $expected_path
1344
   *   The location where the file is expected to be uploaded. Duplicate file
1345
   *   names to not need to be taken into account.
1346
   * @param $actual_path
1347
   *   Where the file was actually uploaded.
1348
   * @param $message
1349
   *   The message to display with this assertion.
1350
   */
1351
  function assertPathMatch($expected_path, $actual_path, $message) {
1352
    // Strip off the extension of the expected path to allow for _0, _1, etc.
1353
    // suffixes when the file hits a duplicate name.
1354
    $pos = strrpos($expected_path, '.');
1355
    $base_path = substr($expected_path, 0, $pos);
1356
    $extension = substr($expected_path, $pos + 1);
1357

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

    
1363
/**
1364
 * Tests the file token replacement in strings.
1365
 */
1366
class FileTokenReplaceTestCase extends FileFieldTestCase {
1367
  public static function getInfo() {
1368
    return array(
1369
      'name' => 'File token replacement',
1370
      'description' => 'Generates text using placeholders for dummy content to check file token replacement.',
1371
      'group' => 'File',
1372
    );
1373
  }
1374

    
1375
  /**
1376
   * Creates a file, then tests the tokens generated from it.
1377
   */
1378
  function testFileTokenReplacement() {
1379
    global $language;
1380
    $url_options = array(
1381
      'absolute' => TRUE,
1382
      'language' => $language,
1383
    );
1384

    
1385
    // Create file field.
1386
    $type_name = 'article';
1387
    $field_name = 'field_' . strtolower($this->randomName());
1388
    $this->createFileField($field_name, $type_name);
1389
    $field = field_info_field($field_name);
1390
    $instance = field_info_instance('node', $field_name, $type_name);
1391

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

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

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

    
1404
    // Generate and test sanitized tokens.
1405
    $tests = array();
1406
    $tests['[file:fid]'] = $file->fid;
1407
    $tests['[file:name]'] = check_plain($file->filename);
1408
    $tests['[file:path]'] = check_plain($file->uri);
1409
    $tests['[file:mime]'] = check_plain($file->filemime);
1410
    $tests['[file:size]'] = format_size($file->filesize);
1411
    $tests['[file:url]'] = check_plain(file_create_url($file->uri));
1412
    $tests['[file:timestamp]'] = format_date($file->timestamp, 'medium', '', NULL, $language->language);
1413
    $tests['[file:timestamp:short]'] = format_date($file->timestamp, 'short', '', NULL, $language->language);
1414
    $tests['[file:owner]'] = check_plain(format_username($this->admin_user));
1415
    $tests['[file:owner:uid]'] = $file->uid;
1416

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

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

    
1425
    // Generate and test unsanitized tokens.
1426
    $tests['[file:name]'] = $file->filename;
1427
    $tests['[file:path]'] = $file->uri;
1428
    $tests['[file:mime]'] = $file->filemime;
1429
    $tests['[file:size]'] = format_size($file->filesize);
1430

    
1431
    foreach ($tests as $input => $expected) {
1432
      $output = token_replace($input, array('file' => $file), array('language' => $language, 'sanitize' => FALSE));
1433
      $this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input)));
1434
    }
1435
  }
1436
}
1437

    
1438
/**
1439
 * Tests file access on private nodes.
1440
 */
1441
class FilePrivateTestCase extends FileFieldTestCase {
1442
  public static function getInfo() {
1443
    return array(
1444
      'name' => 'Private file test',
1445
      'description' => 'Uploads a test to a private node and checks access.',
1446
      'group' => 'File',
1447
    );
1448
  }
1449

    
1450
  function setUp() {
1451
    parent::setUp(array('node_access_test', 'field_test'));
1452
    node_access_rebuild();
1453
    variable_set('node_access_test_private', TRUE);
1454
  }
1455

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

    
1468
    // Create a field with no view access - see field_test_field_access().
1469
    $no_access_field_name = 'field_no_view_access';
1470
    $this->createFileField($no_access_field_name, $type_name, array('uri_scheme' => 'private'));
1471

    
1472
    $test_file = $this->getTestFile('text');
1473
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name, TRUE, array('private' => TRUE));
1474
    $node = node_load($nid, NULL, TRUE);
1475
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
1476
    // Ensure the file can be downloaded.
1477
    $this->drupalGet(file_create_url($node_file->uri));
1478
    $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
1479
    $this->drupalLogOut();
1480
    $this->drupalGet(file_create_url($node_file->uri));
1481
    $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
1482

    
1483
    // Test with the field that should deny access through field access.
1484
    $this->drupalLogin($this->admin_user);
1485
    $nid = $this->uploadNodeFile($test_file, $no_access_field_name, $type_name, TRUE, array('private' => TRUE));
1486
    $node = node_load($nid, NULL, TRUE);
1487
    $node_file = (object) $node->{$no_access_field_name}[LANGUAGE_NONE][0];
1488
    // Ensure the file cannot be downloaded.
1489
    $this->drupalGet(file_create_url($node_file->uri));
1490
    $this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission.');
1491

    
1492
    // Attempt to reuse the existing file when creating a new node, and confirm
1493
    // that access is still denied.
1494
    $edit = array();
1495
    $edit['title'] = $this->randomName(8);
1496
    $edit[$field_name . '[' . LANGUAGE_NONE . '][0][fid]'] = $node_file->fid;
1497
    $this->drupalPost('node/add/page', $edit, t('Save'));
1498
    $new_node = $this->drupalGetNodeByTitle($edit['title']);
1499
    $this->assertTrue(!empty($new_node), 'Node was created.');
1500
    $this->assertUrl('node/' . $new_node->nid);
1501
    $this->assertNoRaw($node_file->filename, 'File without view field access permission does not appear after attempting to attach it to a new node.');
1502
    $this->drupalGet(file_create_url($node_file->uri));
1503
    $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.');
1504
  }
1505
}