Projet

Général

Profil

Paste
Télécharger (50,8 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / file_entity / file_entity.test @ 74f6bef0

1
<?php
2

    
3
/**
4
 * @file
5
 * Test integration for the file_entity module.
6
 */
7

    
8
class FileEntityTestHelper extends DrupalWebTestCase {
9
  protected $files = array();
10

    
11
  function setUp() {
12
    $modules = func_get_args();
13
    if (isset($modules[0]) && is_array($modules[0])) {
14
      $modules = $modules[0];
15
    }
16
    $modules[] = 'file_entity';
17
    parent::setUp($modules);
18
  }
19

    
20
  protected function setUpFiles() {
21
    $types = array('text', 'image');
22
    foreach ($types as $type) {
23
      foreach ($this->drupalGetTestFiles($type) as $file) {
24
        $this->files[$type][] = file_save($file);
25
      }
26
    }
27
  }
28

    
29
  protected function createFileType($overrides = array()) {
30
    $type = new stdClass();
31
    $type->type = 'test';
32
    $type->label = "Test";
33
    $type->description = '';
34
    $type->mimetypes = array('image/jpeg', 'image/gif', 'image/png', 'image/tiff');
35

    
36
    foreach ($overrides as $k => $v) {
37
      $type->$k = $v;
38
    }
39

    
40
    file_type_save($type);
41
    return $type;
42
  }
43

    
44
  /**
45
   * Helper for testFileEntityPrivateDownloadAccess() test.
46
   *
47
   * Defines several cases for accesing private files.
48
   *
49
   * @return array
50
   *   Array of associative arrays, each one having the next keys:
51
   *   - "message" string with the assertion message.
52
   *   - "permissions" array of permissions or NULL for anonymous user.
53
   *   - "expect" expected HTTP response code.
54
   *   - "owner" Optional boolean indicating if the user is a file owner.
55
   */
56
  protected function getPrivateDownloadAccessCases() {
57
    return array(
58
      array(
59
        'message' => "File owners cannot download their own files unless they are granted the 'view own private files' permission.",
60
        'permissions' => array(),
61
        'expect' => 403,
62
        'owner' => TRUE,
63
      ),
64
      array(
65
        'message' => "File owners can download their own files as they have been granted the 'view own private files' permission.",
66
        'permissions' => array('view own private files'),
67
        'expect' => 200,
68
        'owner' => TRUE,
69
      ),
70
      array(
71
        'message' => "Anonymous users cannot download private files.",
72
        'permissions' => NULL,
73
        'expect' => 403,
74
      ),
75
      array(
76
        'message' => "Authenticated users cannot download each other's private files.",
77
        'permissions' => array(),
78
        'expect' => 403,
79
      ),
80
      array(
81
        'message' => "Users who can view public files are not able to download private files.",
82
        'permissions' => array('view files'),
83
        'expect' => 403,
84
      ),
85
      array(
86
        'message' => "Users who bypass file access can download any file.",
87
        'permissions' => array('bypass file access'),
88
        'expect' => 200,
89
      ),
90
    );
91
  }
92

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

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

    
103
    return $file;
104
  }
105

    
106
  /**
107
   * Get a file from the database based on its filename.
108
   *
109
   * @param $filename
110
   *   A file filename, usually generated by $this->randomName().
111
   * @param $reset
112
   *   (optional) Whether to reset the internal file_load() cache.
113
   *
114
   * @return
115
   *   A file object matching $filename.
116
   */
117
  function getFileByFilename($filename, $reset = FALSE) {
118
    $files = file_load_multiple(array(), array('filename' => $filename), $reset);
119
    // Load the first file returned from the database.
120
    $returned_file = reset($files);
121
    return $returned_file;
122
  }
123

    
124
  protected function createFileEntity($settings = array()) {
125
    $file = new stdClass();
126

    
127
    // Populate defaults array.
128
    $settings += array(
129
      'filepath' => 'Файл для тестирования ' . $this->randomName(), // Prefix with non-latin characters to ensure that all file-related tests work with international filenames.
130
      'filemime' => 'text/plain',
131
      'uid' => 1,
132
      'timestamp' => REQUEST_TIME,
133
      'status' => FILE_STATUS_PERMANENT,
134
      'contents' => "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.",
135
      'scheme' => file_default_scheme(),
136
      'type' => NULL,
137
    );
138

    
139
    $filepath = $settings['scheme'] . '://' . $settings['filepath'];
140

    
141
    file_put_contents($filepath, $settings['contents']);
142
    $this->assertTrue(is_file($filepath), t('The test file exists on the disk.'), 'Create test file');
143

    
144
    $file = new stdClass();
145
    $file->uri = $filepath;
146
    $file->filename = drupal_basename($file->uri);
147
    $file->filemime = $settings['filemime'];
148
    $file->uid = $settings['uid'];
149
    $file->timestamp = $settings['timestamp'];
150
    $file->filesize = filesize($file->uri);
151
    $file->status = $settings['status'];
152
    $file->type = $settings['type'];
153

    
154
    // The file type is used as a bundle key, and therefore, must not be NULL.
155
    if (!isset($file->type)) {
156
      $file->type = FILE_TYPE_NONE;
157
    }
158

    
159
    // If the file isn't already assigned a real type, determine what type should
160
    // be assigned to it.
161
    if ($file->type === FILE_TYPE_NONE) {
162
      $type = file_get_type($file);
163
      if (isset($type)) {
164
        $file->type = $type;
165
      }
166
    }
167

    
168
    // Write the record directly rather than calling file_save() so we don't
169
    // invoke the hooks.
170
    $this->assertNotIdentical(drupal_write_record('file_managed', $file), FALSE, t('The file was added to the database.'), 'Create test file');
171

    
172
    return $file;
173
  }
174

    
175
  /**
176
   * Overrides DrupalWebTestCase::drupalGetToken() to support the hash salt.
177
   *
178
   * @todo Remove when http://drupal.org/node/1555862 is fixed in core.
179
   */
180
  protected function drupalGetToken($value = '') {
181
    $private_key = drupal_get_private_key();
182
    return drupal_hmac_base64($value, $this->session_id . $private_key . drupal_get_hash_salt());
183
  }
184
}
185

    
186
class FileEntityFileTypeClassificationTestCase extends DrupalWebTestCase {
187
  public static function getInfo() {
188
    return array(
189
      'name' => 'File entity classification',
190
      'description' => 'Test existing file entity classification functionality.',
191
      'group' => 'File entity',
192
    );
193
  }
194

    
195
  function setUp() {
196
    parent::setUp();
197
  }
198

    
199
  /**
200
   * Get the file type of a given file.
201
   *
202
   * @param $file
203
   *   A file object.
204
   *
205
   * @return
206
   *   The file's file type as a string.
207
   */
208
  function getFileType($file) {
209
    $type = db_select('file_managed', 'fm')
210
      ->fields('fm', array('type'))
211
      ->condition('fid', $file->fid, '=')
212
      ->execute()
213
      ->fetchAssoc();
214

    
215
    return $type;
216
  }
217

    
218
  /**
219
   * Test that existing files are properly classified by file type.
220
   */
221
  function testFileTypeClassification() {
222
    // Get test text and image files.
223
    $file = current($this->drupalGetTestFiles('text'));
224
    $text_file = file_save($file);
225
    $file = current($this->drupalGetTestFiles('image'));
226
    $image_file = file_save($file);
227

    
228
    // Enable file entity which adds adds a file type property to files and
229
    // queues up existing files for classification.
230
    module_enable(array('file_entity'));
231

    
232
    // Existing files have yet to be classified and should have an undefined
233
    // file type.
234
    $file_type = $this->getFileType($text_file);
235
    $this->assertEqual($file_type['type'], 'undefined', t('The text file has an undefined file type.'));
236
    $file_type = $this->getFileType($image_file);
237
    $this->assertEqual($file_type['type'], 'undefined', t('The image file has an undefined file type.'));
238

    
239
    // The classification queue is processed during cron runs. Run cron to
240
    // trigger the classification process.
241
    $this->cronRun();
242

    
243
    // The classification process should assign a file type to any file whose
244
    // MIME type is assigned to a file type. Check to see if each file was
245
    // assigned a proper file type.
246
    $file_type = $this->getFileType($text_file);
247
    $this->assertEqual($file_type['type'], 'document', t('The text file was properly assigned the Document file type.'));
248
    $file_type = $this->getFileType($image_file);
249
    $this->assertEqual($file_type['type'], 'image', t('The image file was properly assigned the Image file type.'));
250
  }
251
}
252

    
253
class FileEntityUnitTestCase extends FileEntityTestHelper {
254
  public static function getInfo() {
255
    return array(
256
      'name' => 'File entity unit tests',
257
      'description' => 'Test basic file entity functionality.',
258
      'group' => 'File entity',
259
    );
260
  }
261

    
262
  function setUp() {
263
    parent::setUp();
264
    parent::setUpFiles();
265
  }
266

    
267
  /**
268
   * Regression tests for core issue http://drupal.org/node/1239376.
269
   */
270
  function testMimeTypeMappings() {
271
    $tests = array(
272
      'public://test.ogg' => 'audio/ogg',
273
      'public://test.mkv' => 'video/x-m4v',
274
      'public://test.mka' => 'audio/x-matroska',
275
      'public://test.mkv' => 'video/x-matroska',
276
      'public://test.webp' => 'image/webp',
277
    );
278
    foreach ($tests as $input => $expected) {
279
      $this->assertEqual(file_get_mimetype($input), $expected);
280
    }
281
  }
282

    
283
  function testFileEntity() {
284
    $file = reset($this->files['text']);
285

    
286
    // Test entity ID, revision ID, and bundle.
287
    $ids = entity_extract_ids('file', $file);
288
    $this->assertIdentical($ids, array($file->fid, NULL, 'document'));
289

    
290
    // Test the entity URI callback.
291
    $uri = entity_uri('file', $file);
292
    $this->assertEqual($uri['path'], "file/{$file->fid}");
293
  }
294

    
295
  function testImageDimensions() {
296
    $files = array();
297
    $text_fids = array();
298
    // Test hook_file_insert().
299
    // Files have been saved as part of setup (in FileEntityTestHelper::setUpFiles).
300
    foreach ($this->files['image'] as $file) {
301
      $files[$file->fid] = $file->metadata;
302
      $this->assertTrue(isset($file->metadata['height']), 'Image height retrieved on file_save() for an image file.');
303
      $this->assertTrue(isset($file->metadata['width']), 'Image width retrieved on file_save() for an image file.');
304
    }
305
    foreach ($this->files['text'] as $file) {
306
      $text_fids[] = $file->fid;
307
      $this->assertFalse(isset($file->metadata['height']), 'No image height retrieved on file_save() for an text file.');
308
      $this->assertFalse(isset($file->metadata['width']), 'No image width retrieved on file_save() for an text file.');
309
    }
310

    
311
    // Test hook_file_load().
312
    // Clear the cache and load fresh files objects to test file_load behavior.
313
    entity_get_controller('file')->resetCache();
314
    foreach (file_load_multiple(array_keys($files)) as $file) {
315
      $this->assertTrue(isset($file->metadata['height']), 'Image dimensions retrieved on file_load() for an image file.');
316
      $this->assertTrue(isset($file->metadata['width']), 'Image dimensions retrieved on file_load() for an image file.');
317
      $this->assertEqual($file->metadata['height'], $files[$file->fid]['height'], 'Loaded image height is equal to saved image height.');
318
      $this->assertEqual($file->metadata['width'], $files[$file->fid]['width'], 'Loaded image width is equal to saved image width.');
319
    }
320
    foreach (file_load_multiple($text_fids) as $file) {
321
      $this->assertFalse(isset($file->metadata['height']), 'No image height retrieved on file_load() for an text file.');
322
      $this->assertFalse(isset($file->metadata['width']), 'No image width retrieved on file_load() for an text file.');
323
    }
324

    
325
    // Test hook_file_update().
326
    // Load the first image file and resize it.
327
    $image_files = array_keys($files);
328
    $file = file_load(reset($image_files));
329
    $image = image_load($file->uri);
330
    image_resize($image, $file->metadata['width'] / 2, $file->metadata['height'] / 2);
331
    image_save($image);
332
    file_save($file);
333
    $this->assertEqual($file->metadata['height'], $files[$file->fid]['height'] / 2, 'Image file height updated by file_save().');
334
    $this->assertEqual($file->metadata['width'], $files[$file->fid]['width'] / 2, 'Image file width updated by file_save().');
335
    // Clear the cache and reload the file.
336
    entity_get_controller('file')->resetCache();
337
    $file = file_load($file->fid);
338
    $this->assertEqual($file->metadata['height'], $files[$file->fid]['height'] / 2, 'Updated image height retrieved by file_load().');
339
    $this->assertEqual($file->metadata['width'], $files[$file->fid]['width'] / 2, 'Updated image width retrieved by file_load().');
340

    
341
    //Test hook_file_delete().
342
    file_delete($file, TRUE);
343
    $this->assertFalse(db_query('SELECT COUNT(*) FROM {file_metadata} WHERE fid = :fid', array(':fid' => 'fid'))->fetchField(), 'Row deleted in {file_dimensions} on file_delete().');
344
  }
345
}
346

    
347
class FileEntityEditTestCase extends FileEntityTestHelper {
348
  protected $web_user;
349
  protected $admin_user;
350

    
351
  public static function getInfo() {
352
    return array(
353
      'name' => 'File entity edit',
354
      'description' => 'Create a file and test file edit functionality.',
355
      'group' => 'File entity',
356
    );
357
  }
358

    
359
  function setUp() {
360
    parent::setUp();
361

    
362
    $this->web_user = $this->drupalCreateUser(array('edit own document files', 'create files'));
363
    $this->admin_user = $this->drupalCreateUser(array('bypass file access', 'administer files'));
364
  }
365

    
366
  /**
367
   * Check file edit functionality.
368
   */
369
  function testFileEntityEdit() {
370
    $this->drupalLogin($this->web_user);
371

    
372
    $test_file = $this->getTestFile('text');
373
    $name_key = "filename";
374

    
375
    // Create file to edit.
376
    $edit = array();
377
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
378
    $this->drupalPost('file/add', $edit, t('Next'));
379
    if ($this->xpath('//input[@name="scheme"]')) {
380
      $this->drupalPost(NULL, array(), t('Next'));
381
    }
382

    
383
    // Check that the file exists in the database.
384
    $file = $this->getFileByFilename($test_file->filename);
385
    $this->assertTrue($file, t('File found in database.'));
386

    
387
    // Check that "edit" link points to correct page.
388
    $this->clickLink(t('Edit'));
389
    $edit_url = url("file/$file->fid/edit", array('absolute' => TRUE));
390
    $actual_url = $this->getURL();
391
    $this->assertEqual($edit_url, $actual_url, t('On edit page.'));
392

    
393
    // Check that the name field is displayed with the correct value.
394
    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';
395
    $link_text = t('!local-task-title!active', array('!local-task-title' => t('Edit'), '!active' => $active));
396
    $this->assertText(strip_tags($link_text), 0, t('Edit tab found and marked active.'));
397
    $this->assertFieldByName($name_key, $file->filename, t('Name field displayed.'));
398

    
399
    // The user does not have "delete" permissions so no delete button should be found.
400
    $this->assertNoFieldByName('op', t('Delete'), 'Delete button not found.');
401

    
402
    // Edit the content of the file.
403
    $edit = array();
404
    $edit[$name_key] = $this->randomName(8);
405
    // Stay on the current page, without reloading.
406
    $this->drupalPost(NULL, $edit, t('Save'));
407

    
408
    // Check that the name field is displayed with the updated values.
409
    $this->assertText($edit[$name_key], t('Name displayed.'));
410
  }
411

    
412
  /**
413
   * Check changing file associated user fields.
414
   */
415
  function testFileEntityAssociatedUser() {
416
    $this->drupalLogin($this->admin_user);
417

    
418
    // Create file to edit.
419
    $test_file = $this->getTestFile('text');
420
    $name_key = "filename";
421
    $edit = array();
422
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
423
    $this->drupalPost('file/add', $edit, t('Next'));
424

    
425
    // Check that the file was associated with the currently logged in user.
426
    $file = $this->getFileByFilename($test_file->filename);
427
    $this->assertIdentical($file->uid, $this->admin_user->uid, 'File associated with admin user.');
428

    
429
    // Try to change the 'associated user' field to an invalid user name.
430
    $edit = array(
431
      'name' => 'invalid-name',
432
    );
433
    $this->drupalPost('file/' . $file->fid . '/edit', $edit, t('Save'));
434
    $this->assertText('The username invalid-name does not exist.');
435

    
436
    // Change the associated user field to an empty string, which should assign
437
    // association to the anonymous user (uid 0).
438
    $edit['name'] = '';
439
    $this->drupalPost('file/' . $file->fid . '/edit', $edit, t('Save'));
440
    $file = file_load($file->fid);
441
    $this->assertIdentical($file->uid, '0', 'File associated with anonymous user.');
442

    
443
    // Change the associated user field to another user's name (that is not
444
    // logged in).
445
    $edit['name'] = $this->web_user->name;
446
    $this->drupalPost('file/' . $file->fid . '/edit', $edit, t('Save'));
447
    $file = file_load($file->fid);
448
    $this->assertIdentical($file->uid, $this->web_user->uid, 'File associated with normal user.');
449

    
450
    // Check that normal users cannot change the associated user information.
451
    $this->drupalLogin($this->web_user);
452
    $this->drupalGet('file/' . $file->fid . '/edit');
453
    $this->assertNoFieldByName('name');
454
  }
455
}
456

    
457
class FileEntityCreationTestCase extends FileEntityTestHelper {
458
  public static function getInfo() {
459
    return array(
460
      'name' => 'File entity creation',
461
      'description' => 'Create a file and test saving it.',
462
      'group' => 'File entity',
463
    );
464
  }
465

    
466
  function setUp() {
467
    parent::setUp();
468

    
469
    $web_user = $this->drupalCreateUser(array('create files', 'edit own document files'));
470
    $this->drupalLogin($web_user);
471
  }
472

    
473
  /**
474
   * Create a "document" file and verify its consistency in the database.
475
   */
476
  function testFileEntityCreation() {
477
    $test_file = $this->getTestFile('text');
478
    // Create a file.
479
    $edit = array();
480
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
481
    $this->drupalPost('file/add', $edit, t('Next'));
482

    
483
    // Step 2: Scheme selection
484
    if ($this->xpath('//input[@name="scheme"]')) {
485
      $this->drupalPost(NULL, array(), t('Next'));
486
    }
487

    
488
    // Check that the document file has been uploaded.
489
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Document', '%name' => $test_file->filename)), t('Document file uploaded.'));
490

    
491
    // Check that the file exists in the database.
492
    $file = $this->getFileByFilename($test_file->filename);
493
    $this->assertTrue($file, t('File found in database.'));
494
  }
495
}
496

    
497
/**
498
 * Test file administration page functionality.
499
 */
500
class FileEntityAdminTestCase extends FileEntityTestHelper {
501
  public static function getInfo() {
502
    return array(
503
      'name' => 'File administration',
504
      'description' => 'Test file administration page functionality.',
505
      'group' => 'File entity',
506
    );
507
  }
508

    
509
  function setUp() {
510
    parent::setUp();
511

    
512
    // Remove the "view files" permission which is set
513
    // by default for all users so we can test this permission
514
    // correctly.
515
    $roles = user_roles();
516
    foreach ($roles as $rid => $role) {
517
      user_role_revoke_permissions($rid, array('view files'));
518
    }
519

    
520
    $this->admin_user = $this->drupalCreateUser(array('administer files', 'bypass file access'));
521
    $this->base_user_1 = $this->drupalCreateUser(array('administer files'));
522
    $this->base_user_2 = $this->drupalCreateUser(array('administer files', 'view own private files'));
523
    $this->base_user_3 = $this->drupalCreateUser(array('administer files', 'view private files'));
524
    $this->base_user_4 = $this->drupalCreateUser(array('administer files', 'edit any document files', 'delete any document files', 'edit any image files', 'delete any image files'));
525
  }
526

    
527
  /**
528
   * Tests that the table sorting works on the files admin pages.
529
   */
530
  function testFilesAdminSort() {
531
    $this->drupalLogin($this->admin_user);
532
    $i = 0;
533
    foreach (array('dd', 'aa', 'DD', 'bb', 'cc', 'CC', 'AA', 'BB') as $prefix) {
534
      $this->createFileEntity(array('filepath' => $prefix . $this->randomName(6), 'timestamp' => $i));
535
      $i++;
536
    }
537

    
538
    // Test that the default sort by file_managed.timestamp DESC actually fires properly.
539
    $files_query = db_select('file_managed', 'fm')
540
      ->fields('fm', array('fid'))
541
      ->orderBy('timestamp', 'DESC')
542
      ->execute()
543
      ->fetchCol();
544

    
545
    $files_form = array();
546
    $this->drupalGet('admin/content/file');
547
    foreach ($this->xpath('//table/tbody/tr/td/div/input/@value') as $input) {
548
      $files_form[] = $input;
549
    }
550
    $this->assertEqual($files_query, $files_form, 'Files are sorted in the form according to the default query.');
551

    
552
    // Compare the rendered HTML node list to a query for the files ordered by
553
    // filename to account for possible database-dependent sort order.
554
    $files_query = db_select('file_managed', 'fm')
555
      ->fields('fm', array('fid'))
556
      ->orderBy('filename')
557
      ->execute()
558
      ->fetchCol();
559

    
560
    $files_form = array();
561
    $this->drupalGet('admin/content/file', array('query' => array('sort' => 'asc', 'order' => 'Title')));
562
    foreach ($this->xpath('//table/tbody/tr/td/div/input/@value') as $input) {
563
      $files_form[] = $input;
564
    }
565
    $this->assertEqual($files_query, $files_form, 'Files are sorted in the form the same as they are in the query.');
566
  }
567

    
568
  /**
569
   * Tests files overview with different user permissions.
570
   */
571
  function testFilesAdminPages() {
572
    $this->drupalLogin($this->admin_user);
573

    
574
    $files['public_image'] = $this->createFileEntity(array('scheme' => 'public', 'uid' => $this->base_user_1->uid, 'type' => 'image'));
575
    $files['public_document'] = $this->createFileEntity(array('scheme' => 'public', 'uid' => $this->base_user_2->uid, 'type' => 'document'));
576
    $files['private_image'] = $this->createFileEntity(array('scheme' => 'private', 'uid' => $this->base_user_1->uid, 'type' => 'image'));
577
    $files['private_document'] = $this->createFileEntity(array('scheme' => 'private', 'uid' => $this->base_user_2->uid, 'type' => 'document'));
578

    
579
    // Verify view, edit, and delete links for any file.
580
    $this->drupalGet('admin/content/file');
581
    $this->assertResponse(200);
582
    foreach ($files as $file) {
583
      $this->assertLinkByHref('file/' . $file->fid);
584
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
585
      $this->assertLinkByHref('file/' . $file->fid . '/delete');
586
      // Verify tableselect.
587
      $this->assertFieldByName('files[' . $file->fid . ']', '', t('Tableselect found.'));
588
    }
589

    
590
    // Verify no operation links are displayed for regular users.
591
    $this->drupalLogout();
592
    $this->drupalLogin($this->base_user_1);
593
    $this->drupalGet('admin/content/file');
594
    $this->assertResponse(200);
595
    $this->assertLinkByHref('file/' . $files['public_image']->fid);
596
    $this->assertLinkByHref('file/' . $files['public_document']->fid);
597
    $this->assertNoLinkByHref('file/' . $files['public_image']->fid . '/edit');
598
    $this->assertNoLinkByHref('file/' . $files['public_image']->fid . '/delete');
599
    $this->assertNoLinkByHref('file/' . $files['public_document']->fid . '/edit');
600
    $this->assertNoLinkByHref('file/' . $files['public_document']->fid . '/delete');
601

    
602
    // Verify no tableselect.
603
    $this->assertNoFieldByName('files[' . $files['public_image']->fid . ']', '', t('No tableselect found.'));
604

    
605
    // Verify private file is displayed with permission.
606
    $this->drupalLogout();
607
    $this->drupalLogin($this->base_user_2);
608
    $this->drupalGet('admin/content/file');
609
    $this->assertResponse(200);
610
    $this->assertLinkByHref('file/' . $files['private_document']->fid);
611
    // Verify no operation links are displayed.
612
    $this->assertNoLinkByHref('file/' . $files['private_document']->fid . '/edit');
613
    $this->assertNoLinkByHref('file/' . $files['private_document']->fid . '/delete');
614

    
615
    // Verify user cannot see private file of other users.
616
    $this->assertNoLinkByHref('file/' . $files['private_image']->fid);
617
    $this->assertNoLinkByHref('file/' . $files['private_image']->fid . '/edit');
618
    $this->assertNoLinkByHref('file/' . $files['private_image']->fid . '/delete');
619

    
620
    // Verify no tableselect.
621
    $this->assertNoFieldByName('files[' . $files['private_document']->fid . ']', '', t('No tableselect found.'));
622

    
623
    // Verify private file is displayed with permission.
624
    $this->drupalLogout();
625
    $this->drupalLogin($this->base_user_3);
626
    $this->drupalGet('admin/content/file');
627
    $this->assertResponse(200);
628

    
629
    // Verify user can see private file of other users.
630
    $this->assertLinkByHref('file/' . $files['private_document']->fid);
631
    $this->assertLinkByHref('file/' . $files['private_image']->fid);
632

    
633
    // Verify operation links are displayed for users with appropriate permission.
634
    $this->drupalLogout();
635
    $this->drupalLogin($this->base_user_4);
636
    $this->drupalGet('admin/content/file');
637
    $this->assertResponse(200);
638
    foreach ($files as $file) {
639
      $this->assertLinkByHref('file/' . $file->fid);
640
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
641
      $this->assertLinkByHref('file/' . $file->fid . '/delete');
642
    }
643

    
644
    // Verify file access can be bypassed.
645
    $this->drupalLogout();
646
    $this->drupalLogin($this->admin_user);
647
    $this->drupalGet('admin/content/file');
648
    $this->assertResponse(200);
649
    foreach ($files as $file) {
650
      $this->assertLinkByHref('file/' . $file->fid);
651
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
652
      $this->assertLinkByHref('file/' . $file->fid . '/delete');
653
    }
654
  }
655
}
656

    
657
class FileEntityReplaceTestCase extends FileEntityTestHelper {
658
  public static function getInfo() {
659
    return array(
660
      'name' => 'File replacement',
661
      'description' => 'Test file replace functionality.',
662
      'group' => 'File entity',
663
    );
664
  }
665

    
666
  function setUp() {
667
    parent::setUp();
668
    parent::setUpFiles();
669
  }
670

    
671
  /**
672
   * @todo Test image dimensions for an image field are reset when a file is replaced.
673
   * @todo Test image styles are cleared when an image is updated.
674
   */
675
  function testReplaceFile() {
676
    // Select the first text test file to use.
677
    $file = reset($this->files['text']);
678

    
679
    // Create a user with file edit permissions.
680
    $user = $this->drupalCreateUser(array('edit any document files'));
681
    $this->drupalLogin($user);
682

    
683
    // Test that the Upload widget appears for a local file.
684
    $this->drupalGet('file/' . $file->fid . '/edit');
685
    $this->assertFieldByName('files[replace_upload]');
686

    
687
    // Test that file saves without uploading a file.
688
    $this->drupalPost(NULL, array(), t('Save'));
689
    $this->assertText(t('Document @file has been updated.', array('@file' => $file->filename)), 'File was updated without file upload.');
690

    
691
    // Get the next text file to use as a replacement.
692
    $original = clone $file;
693
    $replacement = next($this->files['text']);
694

    
695
    // Test that the file saves when uploading a replacement file.
696
    $edit = array();
697
    $edit['files[replace_upload]'] = drupal_realpath($replacement->uri);
698
    $this->drupalPost('file/' . $file->fid . '/edit', $edit, t('Save'));
699
    $this->assertText(t('Document @file has been updated.', array('@file' => $file->filename)), 'File was updated with file upload.');
700

    
701
    // Re-load the file from the database.
702
    $file = file_load($file->fid);
703

    
704
    // Test how file properties changed after the file has been replaced.
705
    $this->assertEqual($file->filename, $original->filename, 'Updated file name did not change.');
706
    $this->assertNotEqual($file->filesize, $original->filesize, 'Updated file size changed from previous file.');
707
    $this->assertEqual($file->filesize, $replacement->filesize, 'Updated file size matches uploaded file.');
708
    $this->assertEqual(file_get_contents($replacement->uri), file_get_contents($file->uri), 'Updated file contents matches uploaded file.');
709

    
710
    // Get an image file.
711
    $image = reset($this->files['image']);
712
    $edit['files[replace_upload]'] = drupal_realpath($image->uri);
713

    
714
    // Test that validation works by uploading a non-text file as a replacement.
715
    $this->drupalPost('file/' . $file->fid . '/edit', $edit, t('Save'));
716
    $this->assertRaw(t('The specified file %file could not be uploaded. Only files with the following extensions are allowed:', array('%file' => $image->filename)), 'File validation works, upload failed correctly.');
717

    
718
    // Create a non-local file record.
719
    $file2 = new stdClass();
720
    $file2->uri = 'oembed://' . $this->randomName();
721
    $file2->filename = drupal_basename($file2->uri);
722
    $file2->filemime = 'image/oembed';
723
    $file2->type = 'image';
724
    $file2->uid = 1;
725
    $file2->timestamp = REQUEST_TIME;
726
    $file2->filesize = 0;
727
    $file2->status = 0;
728
    // Write the record directly rather than calling file_save() so we don't
729
    // invoke the hooks.
730
    $this->assertTrue(drupal_write_record('file_managed', $file2), 'Non-local file was added to the database.');
731

    
732
    // Test that Upload widget does not appear for non-local file.
733
    $this->drupalGet('file/' . $file2->fid . '/edit');
734
    $this->assertNoFieldByName('files[replace_upload]');
735
  }
736
}
737

    
738
class FileEntityTokenTestCase extends FileEntityTestHelper {
739
  public static function getInfo() {
740
    return array(
741
      'name' => 'File entity tokens',
742
      'description' => 'Test the file entity tokens.',
743
      'group' => 'File entity',
744
    );
745
  }
746

    
747
  function setUp() {
748
    parent::setUp();
749
    parent::setUpFiles();
750
  }
751

    
752
  function testFileEntityTokens() {
753
    $tokens = array(
754
      'type' => 'Document',
755
      'type:name' => 'Document',
756
      'type:machine-name' => 'document',
757
      'type:count' => count($this->files['text']),
758
    );
759
    $this->assertTokens('file', array('file' => $this->files['text'][0]), $tokens);
760

    
761
    $tokens = array(
762
      'type' => 'Image',
763
      'type:name' => 'Image',
764
      'type:machine-name' => 'image',
765
      'type:count' => count($this->files['image']),
766
    );
767
    $this->assertTokens('file', array('file' => $this->files['image'][0]), $tokens);
768
  }
769

    
770
  function assertTokens($type, array $data, array $tokens, array $options = array()) {
771
    $token_input = drupal_map_assoc(array_keys($tokens));
772
    $values = token_generate($type, $token_input, $data, $options);
773
    foreach ($tokens as $token => $expected) {
774
      if (!isset($expected)) {
775
        $this->assertTrue(!isset($values[$token]), t("Token value for [@type:@token] was not generated.", array('@type' => $type, '@token' => $token)));
776
      }
777
      elseif (!isset($values[$token])) {
778
        $this->fail(t("Token value for [@type:@token] was not generated.", array('@type' => $type, '@token' => $token)));
779
      }
780
      elseif (!empty($options['regex'])) {
781
        $this->assertTrue(preg_match('/^' . $expected . '$/', $values[$token]), t("Token value for [@type:@token] was '@actual', matching regular expression pattern '@expected'.", array('@type' => $type, '@token' => $token, '@actual' => $values[$token], '@expected' => $expected)));
782
      }
783
      else {
784
        $this->assertIdentical($values[$token], $expected, t("Token value for [@type:@token] was '@actual', expected value '@expected'.", array('@type' => $type, '@token' => $token, '@actual' => $values[$token], '@expected' => $expected)));
785
      }
786
    }
787

    
788
    return $values;
789
  }
790
}
791

    
792
class FileEntityTypeTestCase extends FileEntityTestHelper {
793
  public static function getInfo() {
794
    return array(
795
      'name' => 'File entity types',
796
      'description' => 'Test the file entity types.',
797
      'group' => 'File entity',
798
    );
799
  }
800

    
801
  function setUp() {
802
    parent::setUp();
803
    parent::setUpFiles();
804
  }
805

    
806
  /**
807
   * Test admin pages access and functionality.
808
   */
809
  function testAdminPages() {
810
    // Create a user with file type administration access.
811
    $user = $this->drupalCreateUser(array('administer file types'));
812
    $this->drupalLogin($user);
813

    
814
    $this->drupalGet('admin/structure/file-types');
815
    $this->assertResponse(200, 'File types admin page is accessible');
816
  }
817

    
818
  /**
819
   * Test creating a new type. Basic CRUD.
820
   */
821
  function testCreate() {
822
    $type_machine_type = 'foo';
823
    $type_machine_label = 'foobar';
824
    $type = $this->createFileType(array('type' => $type_machine_type, 'label' => $type_machine_label));
825
    $loaded_type = file_type_load($type_machine_type);
826
    $this->assertEqual($loaded_type->label, $type_machine_label, "Was able to create a type and retreive it.");
827
  }
828

    
829

    
830
  /**
831
   * Ensures that the weight is respected when types are created.
832
   * @return unknown_type
833
   */
834
  function testOrder() {
835
//    $type = $this->createFileType(array('name' => 'last', 'label' => 'Last', 'weight' => 100));
836
//    $type = $this->createFileType(array('name' => 'first', 'label' => 'First'));
837
//    $types = media_type_get_types();
838
//    $keys = array_keys($types);
839
//    $this->assertTrue(isset($types['last']) && isset($types['first']), "Both types saved");
840
//    $this->assertTrue(array_search('last', $keys) > array_search('first', $keys), 'Type which was supposed to be first came first');
841
  }
842

    
843
  /**
844
   * Test view mode assignment.  Currently fails, don't know why.
845
   * @return unknown_type
846
   */
847
  function testViewModesAssigned() {
848
  }
849

    
850
  /**
851
   * Make sure candidates are presented in the case of multiple
852
   * file types.
853
   */
854
  function testTypeWithCandidates() {
855
    // Create multiple file types with the same mime types.
856
    $types = array(
857
      'image1' => $this->createFileType(array('type' => 'image1', 'label' => 'Image 1')),
858
      'image2' => $this->createFileType(array('type' => 'image2', 'label' => 'Image 2'))
859
    );
860

    
861
    // Attach a text field to one of the file types.
862
    $field = array(
863
      'field_name' => drupal_strtolower($this->randomName()),
864
      'type' => 'text',
865
      'settings' => array(
866
        'max_length' => 255,
867
      )
868
    );
869
    field_create_field($field);
870
    $instance = array(
871
      'field_name' => $field['field_name'],
872
      'entity_type' => 'file',
873
      'bundle' => 'image2',
874
      'widget' => array(
875
        'type' => 'text_textfield',
876
      ),
877
      'display' => array(
878
        'default' => array(
879
          'type' => 'text_default',
880
        ),
881
      ),
882
    );
883
    field_create_instance($instance);
884

    
885
    // Create a user with file creation access.
886
    $user = $this->drupalCreateUser(array('create files'));
887
    $this->drupalLogin($user);
888

    
889
    // Step 1: Upload file
890
    $file = reset($this->files['image']);
891
    $edit = array();
892
    $edit['files[upload]'] = drupal_realpath($file->uri);
893
    $this->drupalPost('file/add', $edit, t('Next'));
894

    
895
    // Step 2: Select file type candidate
896
    $this->assertText('Image 1', 'File type candidate list item found.');
897
    $this->assertText('Image 2', 'File type candidate list item found.');
898
    $edit = array();
899
    $edit['type'] = 'image2';
900
    $this->drupalPost(NULL, $edit, t('Next'));
901

    
902
    // Step 3: Select file scheme candidate
903
    $this->assertText('Public local files served by the webserver.', 'File scheme candidate list item found.');
904
    $this->assertText('Private local files served by Drupal.', 'File scheme candidate list item found.');
905
    $edit = array();
906
    $edit['scheme'] = 'public';
907
    $this->drupalPost(NULL, $edit, t('Next'));
908

    
909
    // Step 4: Complete field widgets
910
    $langcode = LANGUAGE_NONE;
911
    $edit = array();
912
    $edit["{$field['field_name']}[$langcode][0][value]"] = $this->randomName();
913
    $this->drupalPost(NULL, $edit, t('Save'));
914
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Image 2', '%name' => $file->filename)), t('Image 2 file updated.'));
915
    $this->assertText($field['field_name'], 'File text field was found.');
916
  }
917

    
918
  /**
919
   * Make sure no candidates appear when only one mime type is available.
920
   * NOTE: Depends on file_entity.module default 'image' type.
921
   */
922
  function testTypeWithoutCandidates() {
923
    // Attach a text field to the default image file type.
924
    $field = array(
925
      'field_name' => drupal_strtolower($this->randomName()),
926
      'type' => 'text',
927
      'settings' => array(
928
        'max_length' => 255,
929
      )
930
    );
931
    field_create_field($field);
932
    $instance = array(
933
      'field_name' => $field['field_name'],
934
      'entity_type' => 'file',
935
      'bundle' => 'image',
936
      'widget' => array(
937
        'type' => 'text_textfield',
938
      ),
939
      'display' => array(
940
        'default' => array(
941
          'type' => 'text_default',
942
        ),
943
      ),
944
    );
945
    field_create_instance($instance);
946

    
947
    // Create a user with file creation access.
948
    $user = $this->drupalCreateUser(array('create files'));
949
    $this->drupalLogin($user);
950

    
951
    // Step 1: Upload file
952
    $file = reset($this->files['image']);
953
    $edit = array();
954
    $edit['files[upload]'] = drupal_realpath($file->uri);
955
    $this->drupalPost('file/add', $edit, t('Next'));
956

    
957
    // Step 2: Scheme selection
958
    if ($this->xpath('//input[@name="scheme"]')) {
959
      $this->drupalPost(NULL, array(), t('Next'));
960
    }
961

    
962
    // Step 3: Complete field widgets
963
    $langcode = LANGUAGE_NONE;
964
    $edit = array();
965
    $edit["{$field['field_name']}[$langcode][0][value]"] = $this->randomName();
966
    $this->drupalPost(NULL, $edit, t('Save'));
967
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Image', '%name' => $file->filename)), t('Image file uploaded.'));
968
    $this->assertText($field['field_name'], 'File text field was found.');
969
  }
970

    
971
  /**
972
   * Test file types CRUD UI.
973
   */
974
  function testTypesCrudUi() {
975
    $this->drupalGet('admin/structure/file-types');
976
    $this->assertResponse(403, 'File types UI page is not accessible to unauthorized users.');
977

    
978
    $user = $this->drupalCreateUser(array('administer file types'));
979
    $this->drupalLogin($user);
980

    
981
    $this->drupalGet('admin/structure/file-types');
982
    $this->assertResponse(200, 'File types UI page is accessible to users with adequate permission.');
983

    
984
    // Create new file type.
985
    $edit = array(
986
      'label' => t('Test type'),
987
      'type' => 'test_type',
988
      'description' => t('This is dummy file type used just for testing.'),
989
      'mimetypes' => 'image/png',
990
    );
991
    $this->drupalGet('admin/structure/file-types/add');
992
    $this->drupalPost(NULL, $edit, t('Save'));
993
    $this->assertText(t('The file type @type has been updated.', array('@type' => $edit['label'])), 'New file type successfully created.');
994
    $this->assertText($edit['label'], 'New file type created: label found.');
995
    $this->assertText($edit['description'], 'New file type created: description found.');
996
    $this->assertFieldByXPath("//table//tr[1]//td[7]", t('Normal'), 'Newly created file type is stored in DB.');
997
    $this->assertLink(t('disable'), 0, 'Able to disable newly created file type.');
998
    $this->assertLink(t('delete'), 0, 'Able to delete newly created file type.');
999
    $this->assertLinkByHref('admin/structure/file-types/manage/' . $edit['type'] . '/disable', 0, 'Disable link points to disable confirmation page.');
1000
    $this->assertLinkByHref('admin/structure/file-types/manage/' . $edit['type'] . '/delete', 0, 'Delete link points to delete confirmation page.');
1001

    
1002
    // Edit file type.
1003
    $this->drupalGet('admin/structure/file-types/manage/' . $edit['type'] . '/edit');
1004
    $this->assertRaw(t('Save'), 'Save button found on edit page.');
1005
    $this->assertRaw(t('Delete'), 'Delete button found on edit page.');
1006
    $this->assertRaw($edit['label'], 'Label found on file type edit page');
1007
    $this->assertText($edit['description'], 'Description found on file type edit page');
1008
    $this->assertText($edit['mimetypes'], 'Mime-type configuration found on file type edit page');
1009
    $this->assertText(t('Mimetype List'), 'Mimetype list present on edit form.');
1010

    
1011
    // Modify file type.
1012
    $edit['label'] = t('New type label');
1013
    $this->drupalPost(NULL, array('label' => $edit['label']), t('Save'));
1014
    $this->assertText(t('The file type @type has been updated.', array('@type' => $edit['label'])), 'File type was modified.');
1015
    $this->assertText($edit['label'], 'Modified label found on file types list.');
1016

    
1017
    // Disable and re-enable file type.
1018
    $this->drupalGet('admin/structure/file-types/manage/' . $edit['type'] . '/disable');
1019
    $this->assertText(t('Are you sure you want to disable the file type @type?', array('@type' => $edit['label'])), 'Disable confirmation page found.');
1020
    $this->drupalPost(NULL, array(), t('Disable'));
1021
    $this->assertText(t('The file type @type has been disabled.', array('@type' => $edit['label'])), 'Disable confirmation message found.');
1022
    $this->assertFieldByXPath("//table//tr[5]//td[1]", $edit['label'], 'Disabled type moved to the tail of the list.');
1023
    $this->assertLink(t('enable'), 0, 'Able to re-enable newly created file type.');
1024
    $this->assertLinkByHref('admin/structure/file-types/manage/' . $edit['type'] . '/enable', 0, 'Enable link points to enable confirmation page.');
1025
    $this->drupalGet('admin/structure/file-types/manage/' . $edit['type'] . '/enable');
1026
    $this->assertText(t('Are you sure you want to enable the file type @type?', array('@type' => $edit['label'])), 'Enable confirmation page found.');
1027
    $this->drupalPost(NULL, array(), t('Enable'));
1028
    $this->assertText(t('The file type @type has been enabled.', array('@type' => $edit['label'])), 'Enable confirmation message found.');
1029
    $this->assertFieldByXPath("//table//tr[1]//td[1]", $edit['label'], 'Enabled type moved to the top of the list.');
1030

    
1031
    // Delete newly created type.
1032
    $this->drupalGet('admin/structure/file-types/manage/' . $edit['type'] . '/delete');
1033
    $this->assertText(t('Are you sure you want to delete the file type @type?', array('@type' => $edit['label'])), 'Delete confirmation page found.');
1034
    $this->drupalPost(NULL, array(), t('Delete'));
1035
    $this->assertText(t('The file type @type has been deleted.', array('@type' => $edit['label'])), 'Delete confirmation message found.');
1036
    $this->drupalGet('admin/structure/file-types');
1037
    $this->assertNoText($edit['label'], 'File type successfully deleted.');
1038

    
1039
    // Edit exported file type.
1040
    $this->drupalGet('admin/structure/file-types/manage/image/edit');
1041
    $this->assertRaw(t('Image'), 'Label found on file type edit page');
1042
    $this->assertText("image/*", 'Mime-type configuration found on file type edit page');
1043
    $this->drupalPost(NULL, array('label' => t('Funky images')), t('Save'));
1044
    $this->assertText(t('The file type @type has been updated.', array('@type' => t('Funky images'))), 'File type was modified.');
1045
    $this->assertText(t('Funky image'), 'Modified label found on file types list.');
1046
    $this->assertFieldByXPath("//table//tr[1]//td[7]", t('Overridden'), 'Modified type overrides configuration from code.');
1047
    $this->assertLink(t('revert'), 0, 'Able to revert overridden file type.');
1048
    $this->assertLinkByHref('admin/structure/file-types/manage/image/revert', 0, 'Revert link points to revert confirmation page.');
1049

    
1050
    // Revert file type.
1051
    $this->drupalGet('admin/structure/file-types/manage/image/revert');
1052
    $this->assertText(t('Are you sure you want to revert the file type @type?', array('@type' => t('Funky images'))), 'Revert confirmation page found.');
1053
    $this->drupalPost(NULL, array(), t('Revert'));
1054
    $this->assertText(t('The file type @type has been reverted.', array('@type' => t('Funky images'))), 'Revert confirmation message found.');
1055
    $this->assertText(t('Image'), 'Reverted file type found in list.');
1056
    $this->assertFieldByXPath("//table//tr[1]//td[7]", t('Default'), 'Reverted file type shows correct state.');
1057
  }
1058
}
1059

    
1060
class FileEntityAccessTestCase extends FileEntityTestHelper {
1061

    
1062
  public static function getInfo() {
1063
    return array(
1064
      'name' => 'File entity access',
1065
      'description' => 'Test the access aspects of file entity.',
1066
      'group' => 'File entity',
1067
    );
1068
  }
1069

    
1070
  function setUp() {
1071
    parent::setUp();
1072
    parent::setUpFiles();
1073
  }
1074

    
1075
  /**
1076
   * Asserts file_entity_access correctly grants or denies access.
1077
   */
1078
  function assertFileEntityAccess($ops, $file, $account) {
1079
    foreach ($ops as $op => $result) {
1080
      $msg = t("file_entity_access returns @result with operation '@op'.", array('@result' => $result ? 'true' : 'false', '@op' => $op));
1081
      $this->assertEqual($result, file_entity_access($op, $file, $account), $msg);
1082
    }
1083
  }
1084

    
1085
  /**
1086
   * Runs basic tests for file_entity_access function.
1087
   */
1088
  function testFileEntityAccess() {
1089
    $file = reset($this->files['image']);
1090

    
1091
    // Ensures user with 'bypass file access' permission can do everything.
1092
    $web_user = $this->drupalCreateUser(array('bypass file access'));
1093
    $this->assertFileEntityAccess(array('create' => TRUE), NULL, $web_user);
1094
    $this->assertFileEntityAccess(array('view' => TRUE, 'download' => TRUE, 'update' => TRUE, 'delete' => TRUE), $file, $web_user);
1095

    
1096
    // A user with 'administer files' should not access CRUD operations.
1097
    $web_user = $this->drupalCreateUser(array('administer files'));
1098
    $this->assertFileEntityAccess(array('view' => FALSE, 'download' => FALSE, 'update' => FALSE, 'delete' => FALSE), $file, $web_user);
1099

    
1100
    // User cannot 'view files'.
1101
    $web_user = $this->drupalCreateUser(array('create files'));
1102
    $this->assertFileEntityAccess(array('view' => FALSE), $file, $web_user);
1103
    // But can upload new ones.
1104
    $this->assertFileEntityAccess(array('create' => TRUE), NULL, $web_user);
1105

    
1106
    // User can view own files but no other files.
1107
    $web_user = $this->drupalCreateUser(array('create files', 'view own files'));
1108
    $this->assertFileEntityAccess(array('view' => FALSE), $file, $web_user);
1109
    $file->uid = $web_user->uid;
1110
    $file->status = FILE_STATUS_PERMANENT;
1111
    file_save($file);
1112
    $this->assertFileEntityAccess(array('view' => TRUE), $file, $web_user);
1113

    
1114
    // User can download own files but no other files.
1115
    $web_user = $this->drupalCreateUser(array('create files', 'download own image files'));
1116
    $this->assertFileEntityAccess(array('download' => FALSE), $file, $web_user);
1117
    $file->uid = $web_user->uid;
1118
    $file->status = FILE_STATUS_PERMANENT;
1119
    file_save($file);
1120
    $this->assertFileEntityAccess(array('download' => TRUE), $file, $web_user);
1121

    
1122
    // User can update own files but no other files.
1123
    $web_user = $this->drupalCreateUser(array('create files', 'view own files', 'edit own image files'));
1124
    $this->assertFileEntityAccess(array('update' => FALSE), $file, $web_user);
1125
    $file->uid = $web_user->uid;
1126
    $file->status = FILE_STATUS_PERMANENT;
1127
    file_save($file);
1128
    $this->assertFileEntityAccess(array('update' => TRUE), $file, $web_user);
1129

    
1130
    // User can delete own files but no other files.
1131
    $web_user = $this->drupalCreateUser(array('create files', 'view own files', 'edit own image files', 'delete own image files'));
1132
    $this->assertFileEntityAccess(array('delete' => FALSE), $file, $web_user);
1133
    $file->uid = $web_user->uid;
1134
    $file->status = FILE_STATUS_PERMANENT;
1135
    file_save($file);
1136
    $this->assertFileEntityAccess(array('delete' => TRUE), $file, $web_user);
1137

    
1138
    // User can view any file.
1139
    $web_user = $this->drupalCreateUser(array('create files', 'view files'));
1140
    $this->assertFileEntityAccess(array('view' => TRUE), $file, $web_user);
1141

    
1142
    // User can download any file.
1143
    $web_user = $this->drupalCreateUser(array('create files', 'download any image files'));
1144
    $this->assertFileEntityAccess(array('download' => TRUE), $file, $web_user);
1145

    
1146
    // User can edit any file.
1147
    $web_user = $this->drupalCreateUser(array('create files', 'view files', 'edit any image files'));
1148
    $this->assertFileEntityAccess(array('update' => TRUE), $file, $web_user);
1149

    
1150
    // User can delete any file.
1151
    $web_user = $this->drupalCreateUser(array('create files', 'view files', 'edit any image files', 'delete any image files'));
1152
    $this->assertFileEntityAccess(array('delete' => TRUE), $file, $web_user);
1153
  }
1154

    
1155
  /**
1156
   * Test to see if we have access to view files when granted the permissions.
1157
   * In this test we aim to prove the permissions work in the following pages:
1158
   *  file/add
1159
   *  file/%/view
1160
   *  file/%/download
1161
   *  file/%/edit
1162
   *  file/%/delete
1163
   */
1164
  function testFileEntityPageAccess() {
1165
    $web_user = $this->drupalCreateUser(array());
1166
    $this->drupalLogin($web_user);
1167
    $this->drupalGet('file/add');
1168
    $this->assertResponse(403, 'Users without access can not access the file add page');
1169
    $web_user = $this->drupalCreateUser(array('create files'));
1170
    $this->drupalLogin($web_user);
1171
    $this->drupalGet('file/add');
1172
    $this->assertResponse(200, 'Users with access can access the file add page');
1173

    
1174
    $file = reset($this->files['text']);
1175
    $file->status = FILE_STATUS_PERMANENT;
1176
    file_save($file);
1177

    
1178
    // This fails.. No clue why but, tested manually and works as should.
1179
    //$web_user = $this->drupalCreateUser(array('view own files'));
1180
    //$this->drupalLogin($web_user);
1181
    //$this->drupalGet("file/{$file->fid}/view");
1182
    //$this->assertResponse(403, 'Users without access can not access the file view page');
1183
    $web_user = $this->drupalCreateUser(array('view files'));
1184
    $this->drupalLogin($web_user);
1185
    $this->drupalGet("file/{$file->fid}/view");
1186
    $this->assertResponse(200, 'Users with access can access the file view page');
1187

    
1188
    $url = "file/{$file->fid}/download";
1189
    $web_user = $this->drupalCreateUser(array());
1190
    $this->drupalLogin($web_user);
1191
    $this->drupalGet($url, array('query' => array('token' => $this->drupalGetToken($url))));
1192
    $this->assertResponse(403, 'Users without access can not download the file');
1193
    $web_user = $this->drupalCreateUser(array('download any document files'));
1194
    $this->drupalLogin($web_user);
1195
    $this->drupalGet($url, array('query' => array('token' => $this->drupalGetToken($url))));
1196
    $this->assertResponse(200, 'Users with access can download the file');
1197
    $this->drupalGet($url, array('query' => array('token' => 'invalid-token')));
1198
    $this->assertResponse(403, 'Cannot download file with in invalid token.');
1199
    $this->drupalGet($url);
1200
    $this->assertResponse(403, 'Cannot download file without a token.');
1201

    
1202
    $web_user = $this->drupalCreateUser(array());
1203
    $this->drupalLogin($web_user);
1204
    $this->drupalGet("file/{$file->fid}/edit");
1205
    $this->assertResponse(403, 'Users without access can not access the file edit page');
1206
    $web_user = $this->drupalCreateUser(array('edit any document files'));
1207
    $this->drupalLogin($web_user);
1208
    $this->drupalGet("file/{$file->fid}/edit");
1209
    $this->assertResponse(200, 'Users with access can access the file add page');
1210

    
1211
    $web_user = $this->drupalCreateUser(array());
1212
    $this->drupalLogin($web_user);
1213
    $this->drupalGet("file/{$file->fid}/delete");
1214
    $this->assertResponse(403, 'Users without access can not access the file view page');
1215
    $web_user = $this->drupalCreateUser(array('delete any document files'));
1216
    $this->drupalLogin($web_user);
1217
    $this->drupalGet("file/{$file->fid}/delete");
1218
    $this->assertResponse(200, 'Users with access can access the file add page');
1219
  }
1220

    
1221
  /**
1222
   * Test to see if we have access to download private files when granted the permissions.
1223
   */
1224
  function testFileEntityPrivateDownloadAccess() {
1225
    foreach ($this->getPrivateDownloadAccessCases() as $case) {
1226
      // Create users and login only if non-anonymous.
1227
      $authenticated_user = !is_null($case['permissions']);
1228
      if ($authenticated_user) {
1229
        $account = $this->drupalCreateUser($case['permissions']);
1230
        $this->drupalLogin($account);
1231
      }
1232

    
1233
      // Create private, permanent files owned by this user only he's an owner.
1234
      if (!empty($case['owner'])) {
1235
        $file = next($this->files['text']);
1236
        $file->status = FILE_STATUS_PERMANENT;
1237
        $file->uid = $account->uid;
1238
        file_save($file);
1239
        $file = file_move($file, 'private://');
1240

    
1241
        // Check if the physical file is there.
1242
        $arguments = array('%name' => $file->filename, '%username' => $account->name, '%uri' => $file->uri);
1243
        $this->assertTrue(is_file($file->uri), format_string('File %name owned by %username successfully created at %uri.', $arguments));
1244
        $url = file_create_url($file->uri);
1245
        $message_file_info = ' ' . format_string('File %uri was checked.', array('%uri' => $file->uri));
1246
      }
1247

    
1248
      // Try to download the file.
1249
      $this->drupalGet($url);
1250
      $this->assertResponse($case['expect'], $case['message'] . $message_file_info);
1251

    
1252
      // Logout authenticated users.
1253
      if ($authenticated_user) {
1254
        $this->drupalLogout();
1255
      }
1256
    }
1257
  }
1258
}