Projet

Général

Profil

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

root / drupal7 / modules / simpletest / tests / file.test @ cee0424c

1
<?php
2

    
3
/**
4
 *  @file
5
 *  This provides SimpleTests for the core file handling functionality.
6
 *  These include FileValidateTest and FileSaveTest.
7
 */
8

    
9
/**
10
 * Helper validator that returns the $errors parameter.
11
 */
12
function file_test_validator($file, $errors) {
13
  return $errors;
14
}
15

    
16
/**
17
 * Helper function for testing file_scan_directory().
18
 *
19
 * Each time the function is called the file is stored in a static variable.
20
 * When the function is called with no $filepath parameter, the results are
21
 * returned.
22
 *
23
 * @param $filepath
24
 *   File path
25
 * @return
26
 *   If $filepath is NULL, an array of all previous $filepath parameters
27
 */
28
function file_test_file_scan_callback($filepath = NULL) {
29
  $files = &drupal_static(__FUNCTION__, array());
30
  if (isset($filepath)) {
31
    $files[] = $filepath;
32
  }
33
  else {
34
    return $files;
35
  }
36
}
37

    
38
/**
39
 * Reset static variables used by file_test_file_scan_callback().
40
 */
41
function file_test_file_scan_callback_reset() {
42
  drupal_static_reset('file_test_file_scan_callback');
43
}
44

    
45
/**
46
 * Base class for file tests that adds some additional file specific
47
 * assertions and helper functions.
48
 */
49
class FileTestCase extends DrupalWebTestCase {
50
  /**
51
   * Check that two files have the same values for all fields other than the
52
   * timestamp.
53
   *
54
   * @param $before
55
   *   File object to compare.
56
   * @param $after
57
   *   File object to compare.
58
   */
59
  function assertFileUnchanged($before, $after) {
60
    $this->assertEqual($before->fid, $after->fid, format_string('File id is the same: %file1 == %file2.', array('%file1' => $before->fid, '%file2' => $after->fid)), 'File unchanged');
61
    $this->assertEqual($before->uid, $after->uid, format_string('File owner is the same: %file1 == %file2.', array('%file1' => $before->uid, '%file2' => $after->uid)), 'File unchanged');
62
    $this->assertEqual($before->filename, $after->filename, format_string('File name is the same: %file1 == %file2.', array('%file1' => $before->filename, '%file2' => $after->filename)), 'File unchanged');
63
    $this->assertEqual($before->uri, $after->uri, format_string('File path is the same: %file1 == %file2.', array('%file1' => $before->uri, '%file2' => $after->uri)), 'File unchanged');
64
    $this->assertEqual($before->filemime, $after->filemime, format_string('File MIME type is the same: %file1 == %file2.', array('%file1' => $before->filemime, '%file2' => $after->filemime)), 'File unchanged');
65
    $this->assertEqual($before->filesize, $after->filesize, format_string('File size is the same: %file1 == %file2.', array('%file1' => $before->filesize, '%file2' => $after->filesize)), 'File unchanged');
66
    $this->assertEqual($before->status, $after->status, format_string('File status is the same: %file1 == %file2.', array('%file1' => $before->status, '%file2' => $after->status)), 'File unchanged');
67
  }
68

    
69
  /**
70
   * Check that two files are not the same by comparing the fid and filepath.
71
   *
72
   * @param $file1
73
   *   File object to compare.
74
   * @param $file2
75
   *   File object to compare.
76
   */
77
  function assertDifferentFile($file1, $file2) {
78
    $this->assertNotEqual($file1->fid, $file2->fid, format_string('Files have different ids: %file1 != %file2.', array('%file1' => $file1->fid, '%file2' => $file2->fid)), 'Different file');
79
    $this->assertNotEqual($file1->uri, $file2->uri, format_string('Files have different paths: %file1 != %file2.', array('%file1' => $file1->uri, '%file2' => $file2->uri)), 'Different file');
80
  }
81

    
82
  /**
83
   * Check that two files are the same by comparing the fid and filepath.
84
   *
85
   * @param $file1
86
   *   File object to compare.
87
   * @param $file2
88
   *   File object to compare.
89
   */
90
  function assertSameFile($file1, $file2) {
91
    $this->assertEqual($file1->fid, $file2->fid, format_string('Files have the same ids: %file1 == %file2.', array('%file1' => $file1->fid, '%file2-fid' => $file2->fid)), 'Same file');
92
    $this->assertEqual($file1->uri, $file2->uri, format_string('Files have the same path: %file1 == %file2.', array('%file1' => $file1->uri, '%file2' => $file2->uri)), 'Same file');
93
  }
94

    
95
  /**
96
   * Helper function to test the permissions of a file.
97
   *
98
   * @param $filepath
99
   *   String file path.
100
   * @param $expected_mode
101
   *   Octal integer like 0664 or 0777.
102
   * @param $message
103
   *   Optional message.
104
   */
105
  function assertFilePermissions($filepath, $expected_mode, $message = NULL) {
106
    // Clear out PHP's file stat cache to be sure we see the current value.
107
    clearstatcache();
108

    
109
    // Mask out all but the last three octets.
110
    $actual_mode = fileperms($filepath) & 0777;
111

    
112
    // PHP on Windows has limited support for file permissions. Usually each of
113
    // "user", "group" and "other" use one octal digit (3 bits) to represent the
114
    // read/write/execute bits. On Windows, chmod() ignores the "group" and
115
    // "other" bits, and fileperms() returns the "user" bits in all three
116
    // positions. $expected_mode is updated to reflect this.
117
    if (substr(PHP_OS, 0, 3) == 'WIN') {
118
      // Reset the "group" and "other" bits.
119
      $expected_mode = $expected_mode & 0700;
120
      // Shift the "user" bits to the "group" and "other" positions also.
121
      $expected_mode = $expected_mode | $expected_mode >> 3 | $expected_mode >> 6;
122
    }
123

    
124
    if (!isset($message)) {
125
      $message = t('Expected file permission to be %expected, actually were %actual.', array('%actual' => decoct($actual_mode), '%expected' => decoct($expected_mode)));
126
    }
127
    $this->assertEqual($actual_mode, $expected_mode, $message);
128
  }
129

    
130
  /**
131
   * Helper function to test the permissions of a directory.
132
   *
133
   * @param $directory
134
   *   String directory path.
135
   * @param $expected_mode
136
   *   Octal integer like 0664 or 0777.
137
   * @param $message
138
   *   Optional message.
139
   */
140
  function assertDirectoryPermissions($directory, $expected_mode, $message = NULL) {
141
    // Clear out PHP's file stat cache to be sure we see the current value.
142
    clearstatcache();
143

    
144
    // Mask out all but the last three octets.
145
    $actual_mode = fileperms($directory) & 0777;
146

    
147
    // PHP on Windows has limited support for file permissions. Usually each of
148
    // "user", "group" and "other" use one octal digit (3 bits) to represent the
149
    // read/write/execute bits. On Windows, chmod() ignores the "group" and
150
    // "other" bits, and fileperms() returns the "user" bits in all three
151
    // positions. $expected_mode is updated to reflect this.
152
    if (substr(PHP_OS, 0, 3) == 'WIN') {
153
      // Reset the "group" and "other" bits.
154
      $expected_mode = $expected_mode & 0700;
155
      // Shift the "user" bits to the "group" and "other" positions also.
156
      $expected_mode = $expected_mode | $expected_mode >> 3 | $expected_mode >> 6;
157
    }
158

    
159
    if (!isset($message)) {
160
      $message = t('Expected directory permission to be %expected, actually were %actual.', array('%actual' => decoct($actual_mode), '%expected' => decoct($expected_mode)));
161
    }
162
    $this->assertEqual($actual_mode, $expected_mode, $message);
163
  }
164

    
165
  /**
166
   * Create a directory and assert it exists.
167
   *
168
   * @param $path
169
   *   Optional string with a directory path. If none is provided, a random
170
   *   name in the site's files directory will be used.
171
   * @return
172
   *   The path to the directory.
173
   */
174
  function createDirectory($path = NULL) {
175
    // A directory to operate on.
176
    if (!isset($path)) {
177
      $path = file_default_scheme() . '://' . $this->randomName();
178
    }
179
    $this->assertTrue(drupal_mkdir($path) && is_dir($path), 'Directory was created successfully.');
180
    return $path;
181
  }
182

    
183
  /**
184
   * Create a file and save it to the files table and assert that it occurs
185
   * correctly.
186
   *
187
   * @param $filepath
188
   *   Optional string specifying the file path. If none is provided then a
189
   *   randomly named file will be created in the site's files directory.
190
   * @param $contents
191
   *   Optional contents to save into the file. If a NULL value is provided an
192
   *   arbitrary string will be used.
193
   * @param $scheme
194
   *   Optional string indicating the stream scheme to use. Drupal core includes
195
   *   public, private, and temporary. The public wrapper is the default.
196
   * @return
197
   *   File object.
198
   */
199
  function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
200
    if (!isset($filepath)) {
201
      // Prefix with non-latin characters to ensure that all file-related
202
      // tests work with international filenames.
203
      $filepath = 'Файл для тестирования ' . $this->randomName();
204
    }
205
    if (!isset($scheme)) {
206
      $scheme = file_default_scheme();
207
    }
208
    $filepath = $scheme . '://' . $filepath;
209

    
210
    if (!isset($contents)) {
211
      $contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
212
    }
213

    
214
    file_put_contents($filepath, $contents);
215
    $this->assertTrue(is_file($filepath), 'The test file exists on the disk.', 'Create test file');
216

    
217
    $file = new stdClass();
218
    $file->uri = $filepath;
219
    $file->filename = drupal_basename($file->uri);
220
    $file->filemime = 'text/plain';
221
    $file->uid = 1;
222
    $file->timestamp = REQUEST_TIME;
223
    $file->filesize = filesize($file->uri);
224
    $file->status = 0;
225
    // Write the record directly rather than calling file_save() so we don't
226
    // invoke the hooks.
227
    $this->assertNotIdentical(drupal_write_record('file_managed', $file), FALSE, 'The file was added to the database.', 'Create test file');
228

    
229
    return $file;
230
  }
231
}
232

    
233
/**
234
 * Base class for file tests that use the file_test module to test uploads and
235
 * hooks.
236
 */
237
class FileHookTestCase extends FileTestCase {
238
  function setUp() {
239
    // Install file_test module
240
    parent::setUp('file_test');
241
    // Clear out any hook calls.
242
    file_test_reset();
243
  }
244

    
245
  /**
246
   * Assert that all of the specified hook_file_* hooks were called once, other
247
   * values result in failure.
248
   *
249
   * @param $expected
250
   *   Array with string containing with the hook name, e.g. 'load', 'save',
251
   *   'insert', etc.
252
   */
253
  function assertFileHooksCalled($expected) {
254
    // Determine which hooks were called.
255
    $actual = array_keys(array_filter(file_test_get_all_calls()));
256

    
257
    // Determine if there were any expected that were not called.
258
    $uncalled = array_diff($expected, $actual);
259
    if (count($uncalled)) {
260
      $this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled))));
261
    }
262
    else {
263
      $this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', array('%expected' => empty($expected) ? t('(none)') : implode(', ', $expected))));
264
    }
265

    
266
    // Determine if there were any unexpected calls.
267
    $unexpected = array_diff($actual, $expected);
268
    if (count($unexpected)) {
269
      $this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', array('%unexpected' => empty($unexpected) ? t('(none)') : implode(', ', $unexpected))));
270
    }
271
    else {
272
      $this->assertTrue(TRUE, 'No unexpected hooks were called.');
273
    }
274
  }
275

    
276
  /**
277
   * Assert that a hook_file_* hook was called a certain number of times.
278
   *
279
   * @param $hook
280
   *   String with the hook name, e.g. 'load', 'save', 'insert', etc.
281
   * @param $expected_count
282
   *   Optional integer count.
283
   * @param $message
284
   *   Optional translated string message.
285
   */
286
  function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
287
    $actual_count = count(file_test_get_calls($hook));
288

    
289
    if (!isset($message)) {
290
      if ($actual_count == $expected_count) {
291
        $message = format_string('hook_file_@name was called correctly.', array('@name' => $hook));
292
      }
293
      elseif ($expected_count == 0) {
294
        $message = format_plural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', array('@name' => $hook, '@count' => $actual_count));
295
      }
296
      else {
297
        $message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', array('@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count));
298
      }
299
    }
300
    $this->assertEqual($actual_count, $expected_count, $message);
301
  }
302
}
303

    
304

    
305
/**
306
 *  This will run tests against the file_space_used() function.
307
 */
308
class FileSpaceUsedTest extends FileTestCase {
309
  public static function getInfo() {
310
    return array(
311
      'name' => 'File space used tests',
312
      'description' => 'Tests the file_space_used() function.',
313
      'group' => 'File API',
314
    );
315
  }
316

    
317
  function setUp() {
318
    parent::setUp();
319

    
320
    // Create records for a couple of users with different sizes.
321
    $file = array('uid' => 2, 'uri' => 'public://example1.txt', 'filesize' => 50, 'status' => FILE_STATUS_PERMANENT);
322
    drupal_write_record('file_managed', $file);
323
    $file = array('uid' => 2, 'uri' => 'public://example2.txt', 'filesize' => 20, 'status' => FILE_STATUS_PERMANENT);
324
    drupal_write_record('file_managed', $file);
325
    $file = array('uid' => 3, 'uri' => 'public://example3.txt', 'filesize' => 100, 'status' => FILE_STATUS_PERMANENT);
326
    drupal_write_record('file_managed', $file);
327
    $file = array('uid' => 3, 'uri' => 'public://example4.txt', 'filesize' => 200, 'status' => FILE_STATUS_PERMANENT);
328
    drupal_write_record('file_managed', $file);
329

    
330
    // Now create some non-permanent files.
331
    $file = array('uid' => 2, 'uri' => 'public://example5.txt', 'filesize' => 1, 'status' => 0);
332
    drupal_write_record('file_managed', $file);
333
    $file = array('uid' => 3, 'uri' => 'public://example6.txt', 'filesize' => 3, 'status' => 0);
334
    drupal_write_record('file_managed', $file);
335
  }
336

    
337
  /**
338
   * Test different users with the default status.
339
   */
340
  function testFileSpaceUsed() {
341
    // Test different users with default status.
342
    $this->assertEqual(file_space_used(2), 70);
343
    $this->assertEqual(file_space_used(3), 300);
344
    $this->assertEqual(file_space_used(), 370);
345

    
346
    // Test the status fields
347
    $this->assertEqual(file_space_used(NULL, 0), 4);
348
    $this->assertEqual(file_space_used(NULL, FILE_STATUS_PERMANENT), 370);
349

    
350
    // Test both the user and status.
351
    $this->assertEqual(file_space_used(1, 0), 0);
352
    $this->assertEqual(file_space_used(1, FILE_STATUS_PERMANENT), 0);
353
    $this->assertEqual(file_space_used(2, 0), 1);
354
    $this->assertEqual(file_space_used(2, FILE_STATUS_PERMANENT), 70);
355
    $this->assertEqual(file_space_used(3, 0), 3);
356
    $this->assertEqual(file_space_used(3, FILE_STATUS_PERMANENT), 300);
357
  }
358
}
359

    
360
/**
361
 *  This will run tests against the file validation functions (file_validate_*).
362
 */
363
class FileValidatorTest extends DrupalWebTestCase {
364
  public static function getInfo() {
365
    return array(
366
      'name' => 'File validator tests',
367
      'description' => 'Tests the functions used to validate uploaded files.',
368
      'group' => 'File API',
369
    );
370
  }
371

    
372
  function setUp() {
373
    parent::setUp();
374

    
375
    $this->image = new stdClass();
376
    $this->image->uri = 'misc/druplicon.png';
377
    $this->image->filename = drupal_basename($this->image->uri);
378

    
379
    $this->non_image = new stdClass();
380
    $this->non_image->uri = 'misc/jquery.js';
381
    $this->non_image->filename = drupal_basename($this->non_image->uri);
382
  }
383

    
384
  /**
385
   * Test the file_validate_extensions() function.
386
   */
387
  function testFileValidateExtensions() {
388
    $file = new stdClass();
389
    $file->filename = 'asdf.txt';
390
    $errors = file_validate_extensions($file, 'asdf txt pork');
391
    $this->assertEqual(count($errors), 0, 'Valid extension accepted.', 'File');
392

    
393
    $file->filename = 'asdf.txt';
394
    $errors = file_validate_extensions($file, 'exe png');
395
    $this->assertEqual(count($errors), 1, 'Invalid extension blocked.', 'File');
396
  }
397

    
398
  /**
399
   *  This ensures a specific file is actually an image.
400
   */
401
  function testFileValidateIsImage() {
402
    $this->assertTrue(file_exists($this->image->uri), 'The image being tested exists.', 'File');
403
    $errors = file_validate_is_image($this->image);
404
    $this->assertEqual(count($errors), 0, 'No error reported for our image file.', 'File');
405

    
406
    $this->assertTrue(file_exists($this->non_image->uri), 'The non-image being tested exists.', 'File');
407
    $errors = file_validate_is_image($this->non_image);
408
    $this->assertEqual(count($errors), 1, 'An error reported for our non-image file.', 'File');
409
  }
410

    
411
  /**
412
   *  This ensures the resolution of a specific file is within bounds.
413
   *  The image will be resized if it's too large.
414
   */
415
  function testFileValidateImageResolution() {
416
    // Non-images.
417
    $errors = file_validate_image_resolution($this->non_image);
418
    $this->assertEqual(count($errors), 0, 'Should not get any errors for a non-image file.', 'File');
419
    $errors = file_validate_image_resolution($this->non_image, '50x50', '100x100');
420
    $this->assertEqual(count($errors), 0, 'Do not check the resolution on non files.', 'File');
421

    
422
    // Minimum size.
423
    $errors = file_validate_image_resolution($this->image);
424
    $this->assertEqual(count($errors), 0, 'No errors for an image when there is no minimum or maximum resolution.', 'File');
425
    $errors = file_validate_image_resolution($this->image, 0, '200x1');
426
    $this->assertEqual(count($errors), 1, 'Got an error for an image that was not wide enough.', 'File');
427
    $errors = file_validate_image_resolution($this->image, 0, '1x200');
428
    $this->assertEqual(count($errors), 1, 'Got an error for an image that was not tall enough.', 'File');
429
    $errors = file_validate_image_resolution($this->image, 0, '200x200');
430
    $this->assertEqual(count($errors), 1, 'Small images report an error.', 'File');
431

    
432
    // Maximum size.
433
    if (image_get_toolkit()) {
434
      // Copy the image so that the original doesn't get resized.
435
      copy('misc/druplicon.png', 'temporary://druplicon.png');
436
      $this->image->uri = 'temporary://druplicon.png';
437

    
438
      $errors = file_validate_image_resolution($this->image, '10x5');
439
      $this->assertEqual(count($errors), 0, 'No errors should be reported when an oversized image can be scaled down.', 'File');
440

    
441
      $info = image_get_info($this->image->uri);
442
      $this->assertTrue($info['width'] <= 10, 'Image scaled to correct width.', 'File');
443
      $this->assertTrue($info['height'] <= 5, 'Image scaled to correct height.', 'File');
444

    
445
      drupal_unlink('temporary://druplicon.png');
446
    }
447
    else {
448
      // TODO: should check that the error is returned if no toolkit is available.
449
      $errors = file_validate_image_resolution($this->image, '5x10');
450
      $this->assertEqual(count($errors), 1, 'Oversize images that cannot be scaled get an error.', 'File');
451
    }
452
  }
453

    
454
  /**
455
   *  This will ensure the filename length is valid.
456
   */
457
  function testFileValidateNameLength() {
458
    // Create a new file object.
459
    $file = new stdClass();
460

    
461
    // Add a filename with an allowed length and test it.
462
    $file->filename = str_repeat('x', 240);
463
    $this->assertEqual(strlen($file->filename), 240);
464
    $errors = file_validate_name_length($file);
465
    $this->assertEqual(count($errors), 0, 'No errors reported for 240 length filename.', 'File');
466

    
467
    // Add a filename with a length too long and test it.
468
    $file->filename = str_repeat('x', 241);
469
    $errors = file_validate_name_length($file);
470
    $this->assertEqual(count($errors), 1, 'An error reported for 241 length filename.', 'File');
471

    
472
    // Add a filename with an empty string and test it.
473
    $file->filename = '';
474
    $errors = file_validate_name_length($file);
475
    $this->assertEqual(count($errors), 1, 'An error reported for 0 length filename.', 'File');
476
  }
477

    
478

    
479
  /**
480
   * Test file_validate_size().
481
   */
482
  function testFileValidateSize() {
483
    // Create a file with a size of 1000 bytes, and quotas of only 1 byte.
484
    $file = new stdClass();
485
    $file->filesize = 1000;
486
    $errors = file_validate_size($file, 0, 0);
487
    $this->assertEqual(count($errors), 0, 'No limits means no errors.', 'File');
488
    $errors = file_validate_size($file, 1, 0);
489
    $this->assertEqual(count($errors), 1, 'Error for the file being over the limit.', 'File');
490
    $errors = file_validate_size($file, 0, 1);
491
    $this->assertEqual(count($errors), 1, 'Error for the user being over their limit.', 'File');
492
    $errors = file_validate_size($file, 1, 1);
493
    $this->assertEqual(count($errors), 2, 'Errors for both the file and their limit.', 'File');
494
  }
495
}
496

    
497

    
498

    
499
/**
500
 *  Tests the file_unmanaged_save_data() function.
501
 */
502
class FileUnmanagedSaveDataTest extends FileTestCase {
503
  public static function getInfo() {
504
    return array(
505
      'name' => 'Unmanaged file save data',
506
      'description' => 'Tests the unmanaged file save data function.',
507
      'group' => 'File API',
508
    );
509
  }
510

    
511
  /**
512
   * Test the file_unmanaged_save_data() function.
513
   */
514
  function testFileSaveData() {
515
    $contents = $this->randomName(8);
516

    
517
    // No filename.
518
    $filepath = file_unmanaged_save_data($contents);
519
    $this->assertTrue($filepath, 'Unnamed file saved correctly.');
520
    $this->assertEqual(file_uri_scheme($filepath), file_default_scheme(), "File was placed in Drupal's files directory.");
521
    $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
522

    
523
    // Provide a filename.
524
    $filepath = file_unmanaged_save_data($contents, 'public://asdf.txt', FILE_EXISTS_REPLACE);
525
    $this->assertTrue($filepath, 'Unnamed file saved correctly.');
526
    $this->assertEqual('asdf.txt', drupal_basename($filepath), 'File was named correctly.');
527
    $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
528
    $this->assertFilePermissions($filepath, variable_get('file_chmod_file', 0664));
529
  }
530
}
531

    
532
/**
533
 *  Tests the file_unmanaged_save_data() function on remote filesystems.
534
 */
535
class RemoteFileUnmanagedSaveDataTest extends FileUnmanagedSaveDataTest {
536
  public static function getInfo() {
537
    $info = parent::getInfo();
538
    $info['group'] = 'File API (remote)';
539
    return $info;
540
  }
541

    
542
  function setUp() {
543
    parent::setUp('file_test');
544
    variable_set('file_default_scheme', 'dummy-remote');
545
  }
546
}
547

    
548
/**
549
 * Test the file_save_upload() function.
550
 */
551
class FileSaveUploadTest extends FileHookTestCase {
552
  /**
553
   * An image file path for uploading.
554
   */
555
  protected $image;
556

    
557
  /**
558
   * A PHP file path for upload security testing.
559
   */
560
  protected $phpfile;
561

    
562
  /**
563
   * The largest file id when the test starts.
564
   */
565
  protected $maxFidBefore;
566

    
567
  public static function getInfo() {
568
    return array(
569
      'name' => 'File uploading',
570
      'description' => 'Tests the file uploading functions.',
571
      'group' => 'File API',
572
    );
573
  }
574

    
575
  function setUp() {
576
    parent::setUp();
577
    $account = $this->drupalCreateUser(array('access content'));
578
    $this->drupalLogin($account);
579

    
580
    $image_files = $this->drupalGetTestFiles('image');
581
    $this->image = current($image_files);
582

    
583
    list(, $this->image_extension) = explode('.', $this->image->filename);
584
    $this->assertTrue(is_file($this->image->uri), "The image file we're going to upload exists.");
585

    
586
    $this->phpfile = current($this->drupalGetTestFiles('php'));
587
    $this->assertTrue(is_file($this->phpfile->uri), "The PHP file we're going to upload exists.");
588

    
589
    $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
590

    
591
    // Upload with replace to guarantee there's something there.
592
    $edit = array(
593
      'file_test_replace' => FILE_EXISTS_REPLACE,
594
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
595
    );
596
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
597
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
598
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
599

    
600
    // Check that the correct hooks were called then clean out the hook
601
    // counters.
602
    $this->assertFileHooksCalled(array('validate', 'insert'));
603
    file_test_reset();
604
  }
605

    
606
  /**
607
   * Test the file_save_upload() function.
608
   */
609
  function testNormal() {
610
    $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
611
    $this->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
612
    $file1 = file_load($max_fid_after);
613
    $this->assertTrue($file1, 'Loaded the file.');
614
    // MIME type of the uploaded image may be either image/jpeg or image/png.
615
    $this->assertEqual(substr($file1->filemime, 0, 5), 'image', 'A MIME type was set.');
616

    
617
    // Reset the hook counters to get rid of the 'load' we just called.
618
    file_test_reset();
619

    
620
    // Upload a second file.
621
    $max_fid_before = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
622
    $image2 = current($this->drupalGetTestFiles('image'));
623
    $edit = array('files[file_test_upload]' => drupal_realpath($image2->uri));
624
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
625
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
626
    $this->assertRaw(t('You WIN!'));
627
    $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
628

    
629
    // Check that the correct hooks were called.
630
    $this->assertFileHooksCalled(array('validate', 'insert'));
631

    
632
    $file2 = file_load($max_fid_after);
633
    $this->assertTrue($file2);
634
    // MIME type of the uploaded image may be either image/jpeg or image/png.
635
    $this->assertEqual(substr($file2->filemime, 0, 5), 'image', 'A MIME type was set.');
636

    
637
    // Load both files using file_load_multiple().
638
    $files = file_load_multiple(array($file1->fid, $file2->fid));
639
    $this->assertTrue(isset($files[$file1->fid]), 'File was loaded successfully');
640
    $this->assertTrue(isset($files[$file2->fid]), 'File was loaded successfully');
641

    
642
    // Upload a third file to a subdirectory.
643
    $image3 = current($this->drupalGetTestFiles('image'));
644
    $image3_realpath = drupal_realpath($image3->uri);
645
    $dir = $this->randomName();
646
    $edit = array(
647
      'files[file_test_upload]' => $image3_realpath,
648
      'file_subdir' => $dir,
649
    );
650
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
651
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
652
    $this->assertRaw(t('You WIN!'));
653
    $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
654

    
655
    // Check that file_load_multiple() with no arguments returns FALSE.
656
    $this->assertFalse(file_load_multiple(), 'No files were loaded.');
657
  }
658

    
659
  /**
660
   * Test extension handling.
661
   */
662
  function testHandleExtension() {
663
    // The file being tested is a .gif which is in the default safe list
664
    // of extensions to allow when the extension validator isn't used. This is
665
    // implicitly tested at the testNormal() test. Here we tell
666
    // file_save_upload() to only allow ".foo".
667
    $extensions = 'foo';
668
    $edit = array(
669
      'file_test_replace' => FILE_EXISTS_REPLACE,
670
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
671
      'extensions' => $extensions,
672
    );
673

    
674
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
675
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
676
    $message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $extensions . '</em>';
677
    $this->assertRaw($message, 'Cannot upload a disallowed extension');
678
    $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
679

    
680
    // Check that the correct hooks were called.
681
    $this->assertFileHooksCalled(array('validate'));
682

    
683
    // Reset the hook counters.
684
    file_test_reset();
685

    
686
    $extensions = 'foo ' . $this->image_extension;
687
    // Now tell file_save_upload() to allow the extension of our test image.
688
    $edit = array(
689
      'file_test_replace' => FILE_EXISTS_REPLACE,
690
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
691
      'extensions' => $extensions,
692
    );
693

    
694
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
695
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
696
    $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload an allowed extension.');
697
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
698

    
699
    // Check that the correct hooks were called.
700
    $this->assertFileHooksCalled(array('validate', 'load', 'update'));
701

    
702
    // Reset the hook counters.
703
    file_test_reset();
704

    
705
    // Now tell file_save_upload() to allow any extension.
706
    $edit = array(
707
      'file_test_replace' => FILE_EXISTS_REPLACE,
708
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
709
      'allow_all_extensions' => 'empty_array',
710
    );
711
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
712
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
713
    $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload any extension.');
714
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
715

    
716
    // Check that the correct hooks were called.
717
    $this->assertFileHooksCalled(array('validate', 'load', 'update'));
718

    
719
    // Reset the hook counters.
720
    file_test_reset();
721

    
722
    // Now tell file_save_upload() to allow any extension and try and upload a
723
    // malicious file.
724
    $edit = array(
725
      'file_test_replace' => FILE_EXISTS_REPLACE,
726
      'files[file_test_upload]' => drupal_realpath($this->phpfile->uri),
727
      'is_image_file' => FALSE,
728
      'allow_all_extensions' => 'empty_array',
729
    );
730
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
731
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
732
    $message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '_.txt' . '</em>';
733
    $this->assertRaw($message, 'Dangerous file was renamed.');
734
    $this->assertText('File name is php-2.php_.txt.');
735
    $this->assertRaw(t('File MIME type is text/plain.'), "Dangerous file's MIME type was changed.");
736
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
737
    // Check that the correct hooks were called.
738
    $this->assertFileHooksCalled(array('validate', 'insert'));
739
  }
740

    
741
  /**
742
   * Test dangerous file handling.
743
   */
744
  function testHandleDangerousFile() {
745
    // Allow the .php extension and make sure it gets munged and given a .txt
746
    // extension for safety. Also check to make sure its MIME type was changed.
747
    $edit = array(
748
      'file_test_replace' => FILE_EXISTS_REPLACE,
749
      'files[file_test_upload]' => drupal_realpath($this->phpfile->uri),
750
      'is_image_file' => FALSE,
751
      'extensions' => 'php',
752
    );
753

    
754
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
755
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
756
    $message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '_.txt' . '</em>';
757
    $this->assertRaw($message, 'Dangerous file was renamed.');
758
    $this->assertRaw('File name is php-2.php_.txt.');
759
    $this->assertRaw(t('File MIME type is text/plain.'), "Dangerous file's MIME type was changed.");
760
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
761

    
762
    // Check that the correct hooks were called.
763
    $this->assertFileHooksCalled(array('validate', 'insert'));
764

    
765
    // Ensure dangerous files are not renamed when insecure uploads is TRUE.
766
    // Turn on insecure uploads.
767
    variable_set('allow_insecure_uploads', 1);
768
    // Reset the hook counters.
769
    file_test_reset();
770

    
771
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
772
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
773
    $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
774
    $this->assertRaw(t('File name is !filename', array('!filename' => $this->phpfile->filename)), 'Dangerous file was not renamed when insecure uploads is TRUE.');
775
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
776

    
777
    // Check that the correct hooks were called.
778
    $this->assertFileHooksCalled(array('validate', 'insert'));
779

    
780
    // Reset the hook counters.
781
    file_test_reset();
782

    
783
    // Even with insecure uploads allowed, the .php file should not be uploaded
784
    // if it is not explicitly included in the list of allowed extensions.
785
    $edit['extensions'] = 'foo';
786
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
787
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
788
    $message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $edit['extensions'] . '</em>';
789
    $this->assertRaw($message, 'Cannot upload a disallowed extension');
790
    $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
791

    
792
    // Check that the correct hooks were called.
793
    $this->assertFileHooksCalled(array('validate'));
794

    
795
    // Reset the hook counters.
796
    file_test_reset();
797

    
798
    // Turn off insecure uploads, then try the same thing as above (ensure that
799
    // the .php file is still rejected since it's not in the list of allowed
800
    // extensions).
801
    variable_set('allow_insecure_uploads', 0);
802
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
803
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
804
    $message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $edit['extensions'] . '</em>';
805
    $this->assertRaw($message, 'Cannot upload a disallowed extension');
806
    $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
807

    
808
    // Check that the correct hooks were called.
809
    $this->assertFileHooksCalled(array('validate'));
810

    
811
    // Reset the hook counters.
812
    file_test_reset();
813
  }
814

    
815
  /**
816
   * Test file munge handling.
817
   */
818
  function testHandleFileMunge() {
819
    // Ensure insecure uploads are disabled for this test.
820
    variable_set('allow_insecure_uploads', 0);
821
    $original_image_uri = $this->image->uri;
822
    $this->image = file_move($this->image, $this->image->uri . '.foo.' . $this->image_extension);
823

    
824
    // Reset the hook counters to get rid of the 'move' we just called.
825
    file_test_reset();
826

    
827
    $extensions = $this->image_extension;
828
    $edit = array(
829
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
830
      'extensions' => $extensions,
831
    );
832

    
833
    $munged_filename = $this->image->filename;
834
    $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
835
    $munged_filename .= '_.' . $this->image_extension;
836

    
837
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
838
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
839
    $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
840
    $this->assertRaw(t('File name is !filename', array('!filename' => $munged_filename)), 'File was successfully munged.');
841
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
842

    
843
    // Check that the correct hooks were called.
844
    $this->assertFileHooksCalled(array('validate', 'insert'));
845

    
846
    // Reset the hook counters.
847
    file_test_reset();
848

    
849
    // Ensure we don't munge the .foo extension if it is in the list of allowed
850
    // extensions.
851
    $extensions = 'foo ' . $this->image_extension;
852
    $edit = array(
853
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
854
      'extensions' => $extensions,
855
    );
856

    
857
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
858
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
859
    $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
860
    $this->assertRaw(t('File name is @filename', array('@filename' => 'image-test.png.foo.png')), 'File was not munged when all extensions within it are allowed.');
861
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
862

    
863
    // Check that the correct hooks were called.
864
    $this->assertFileHooksCalled(array('validate', 'insert'));
865

    
866
    // Ensure we don't munge files if we're allowing any extension.
867
    // Reset the hook counters.
868
    file_test_reset();
869

    
870
    $edit = array(
871
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
872
      'allow_all_extensions' => 'empty_array',
873
    );
874

    
875
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
876
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
877
    $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
878
    $this->assertRaw(t('File name is !filename', array('!filename' => $this->image->filename)), 'File was not munged when allowing any extension.');
879
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
880

    
881
    // Check that the correct hooks were called.
882
    $this->assertFileHooksCalled(array('validate', 'insert'));
883

    
884
    // Test that a dangerous extension such as .php is munged even if it is in
885
    // the list of allowed extensions.
886
    $this->image = file_move($this->image, $original_image_uri . '.php.' . $this->image_extension);
887
    // Reset the hook counters.
888
    file_test_reset();
889

    
890
    $extensions = 'php ' . $this->image_extension;
891
    $edit = array(
892
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
893
      'extensions' => $extensions,
894
    );
895

    
896
    $munged_filename = $this->image->filename;
897
    $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
898
    $munged_filename .= '_.' . $this->image_extension;
899

    
900
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
901
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
902
    $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
903
    $this->assertRaw(t('File name is @filename', array('@filename' => $munged_filename)), 'File was successfully munged.');
904
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
905

    
906
    // Check that the correct hooks were called.
907
    $this->assertFileHooksCalled(array('validate', 'insert'));
908

    
909
    // Reset the hook counters.
910
    file_test_reset();
911

    
912
    // Dangerous extensions are munged even when all extensions are allowed.
913
    $edit = array(
914
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
915
      'allow_all_extensions' => 'empty_array',
916
    );
917

    
918
    $munged_filename = $this->image->filename;
919
    $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
920
    $munged_filename .= '_.' . $this->image_extension;
921

    
922
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
923
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
924
    $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
925
    $this->assertRaw(t('File name is @filename.', array('@filename' => 'image-test.png_.php_.png_.txt')), 'File was successfully munged.');
926
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
927

    
928
    // Check that the correct hooks were called.
929
    $this->assertFileHooksCalled(array('validate', 'insert'));
930

    
931
    // Dangerous extensions are munged if is renamed to end in .txt.
932
    $this->image = file_move($this->image, $original_image_uri . '.cgi.' . $this->image_extension . '.txt');
933
    // Reset the hook counters.
934
    file_test_reset();
935

    
936
    $edit = array(
937
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
938
      'allow_all_extensions' => 'empty_array',
939
    );
940

    
941
    $munged_filename = $this->image->filename;
942
    $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
943
    $munged_filename .= '_.' . $this->image_extension;
944

    
945
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
946
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
947
    $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
948
    $this->assertRaw(t('File name is @filename.', array('@filename' => 'image-test.png_.cgi_.png_.txt')), 'File was successfully munged.');
949
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
950

    
951
    // Check that the correct hooks were called.
952
    $this->assertFileHooksCalled(array('validate', 'insert'));
953

    
954
    // Reset the hook counters.
955
    file_test_reset();
956

    
957
    // Ensure that setting $validators['file_validate_extensions'] = array('')
958
    // rejects all files without munging or renaming.
959
    $edit = array(
960
        'files[file_test_upload]' => drupal_realpath($this->image->uri),
961
        'allow_all_extensions' => 'empty_string',
962
    );
963

    
964
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
965
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
966
    $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
967
    $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
968

    
969
    // Check that the correct hooks were called.
970
    $this->assertFileHooksCalled(array('validate'));
971
  }
972

    
973
  /**
974
   * Test renaming when uploading over a file that already exists.
975
   */
976
  function testExistingRename() {
977
    $edit = array(
978
      'file_test_replace' => FILE_EXISTS_RENAME,
979
      'files[file_test_upload]' => drupal_realpath($this->image->uri)
980
    );
981
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
982
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
983
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
984

    
985
    // Check that the correct hooks were called.
986
    $this->assertFileHooksCalled(array('validate', 'insert'));
987
  }
988

    
989
  /**
990
   * Test replacement when uploading over a file that already exists.
991
   */
992
  function testExistingReplace() {
993
    $edit = array(
994
      'file_test_replace' => FILE_EXISTS_REPLACE,
995
      'files[file_test_upload]' => drupal_realpath($this->image->uri)
996
    );
997
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
998
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
999
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
1000

    
1001
    // Check that the correct hooks were called.
1002
    $this->assertFileHooksCalled(array('validate', 'load', 'update'));
1003
  }
1004

    
1005
  /**
1006
   * Test for failure when uploading over a file that already exists.
1007
   */
1008
  function testExistingError() {
1009
    $edit = array(
1010
      'file_test_replace' => FILE_EXISTS_ERROR,
1011
      'files[file_test_upload]' => drupal_realpath($this->image->uri)
1012
    );
1013
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
1014
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
1015
    $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
1016

    
1017
    // Check that the no hooks were called while failing.
1018
    $this->assertFileHooksCalled(array());
1019
  }
1020

    
1021
  /**
1022
   * Test for no failures when not uploading a file.
1023
   */
1024
  function testNoUpload() {
1025
    $this->drupalPost('file-test/upload', array(), t('Submit'));
1026
    $this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
1027
  }
1028
}
1029

    
1030
/**
1031
 * Test the file_save_upload() function on remote filesystems.
1032
 */
1033
class RemoteFileSaveUploadTest extends FileSaveUploadTest {
1034
  public static function getInfo() {
1035
    $info = parent::getInfo();
1036
    $info['group'] = 'File API (remote)';
1037
    return $info;
1038
  }
1039

    
1040
  function setUp() {
1041
    parent::setUp('file_test');
1042
    variable_set('file_default_scheme', 'dummy-remote');
1043
  }
1044
}
1045

    
1046
/**
1047
 * Directory related tests.
1048
 */
1049
class FileDirectoryTest extends FileTestCase {
1050
  public static function getInfo() {
1051
    return array(
1052
      'name' => 'File paths and directories',
1053
      'description' => 'Tests operations dealing with directories.',
1054
      'group' => 'File API',
1055
    );
1056
  }
1057

    
1058
  /**
1059
   * Test directory handling functions.
1060
   */
1061
  function testFileCheckDirectoryHandling() {
1062
    // A directory to operate on.
1063
    $directory = file_default_scheme() . '://' . $this->randomName() . '/' . $this->randomName();
1064
    $this->assertFalse(is_dir($directory), 'Directory does not exist prior to testing.');
1065

    
1066
    // Non-existent directory.
1067
    $this->assertFalse(file_prepare_directory($directory, 0), 'Error reported for non-existing directory.', 'File');
1068

    
1069
    // Make a directory.
1070
    $this->assertTrue(file_prepare_directory($directory, FILE_CREATE_DIRECTORY), 'No error reported when creating a new directory.', 'File');
1071

    
1072
    // Make sure directory actually exists.
1073
    $this->assertTrue(is_dir($directory), 'Directory actually exists.', 'File');
1074

    
1075
    if (substr(PHP_OS, 0, 3) != 'WIN') {
1076
      // PHP on Windows doesn't support any kind of useful read-only mode for
1077
      // directories. When executing a chmod() on a directory, PHP only sets the
1078
      // read-only flag, which doesn't prevent files to actually be written
1079
      // in the directory on any recent version of Windows.
1080

    
1081
      // Make directory read only.
1082
      @drupal_chmod($directory, 0444);
1083
      $this->assertFalse(file_prepare_directory($directory, 0), 'Error reported for a non-writeable directory.', 'File');
1084

    
1085
      // Test directory permission modification.
1086
      $this->assertTrue(file_prepare_directory($directory, FILE_MODIFY_PERMISSIONS), 'No error reported when making directory writeable.', 'File');
1087
    }
1088

    
1089
    // Test that the directory has the correct permissions.
1090
    $this->assertDirectoryPermissions($directory, variable_get('file_chmod_directory', 0775));
1091

    
1092
    // Remove .htaccess file to then test that it gets re-created.
1093
    @drupal_unlink(file_default_scheme() . '://.htaccess');
1094
    $this->assertFalse(is_file(file_default_scheme() . '://.htaccess'), 'Successfully removed the .htaccess file in the files directory.', 'File');
1095
    file_ensure_htaccess();
1096
    $this->assertTrue(is_file(file_default_scheme() . '://.htaccess'), 'Successfully re-created the .htaccess file in the files directory.', 'File');
1097
    // Verify contents of .htaccess file.
1098
    $file = file_get_contents(file_default_scheme() . '://.htaccess');
1099
    $this->assertEqual($file, file_htaccess_lines(FALSE), 'The .htaccess file contains the proper content.', 'File');
1100
  }
1101

    
1102
  /**
1103
   * This will take a directory and path, and find a valid filepath that is not
1104
   * taken by another file.
1105
   */
1106
  function testFileCreateNewFilepath() {
1107
    // First we test against an imaginary file that does not exist in a
1108
    // directory.
1109
    $basename = 'xyz.txt';
1110
    $directory = 'misc';
1111
    $original = $directory . '/' . $basename;
1112
    $path = file_create_filename($basename, $directory);
1113
    $this->assertEqual($path, $original, format_string('New filepath %new equals %original.', array('%new' => $path, '%original' => $original)), 'File');
1114

    
1115
    // Then we test against a file that already exists within that directory.
1116
    $basename = 'druplicon.png';
1117
    $original = $directory . '/' . $basename;
1118
    $expected = $directory . '/druplicon_0.png';
1119
    $path = file_create_filename($basename, $directory);
1120
    $this->assertEqual($path, $expected, format_string('Creating a new filepath from %original equals %new.', array('%new' => $path, '%original' => $original)), 'File');
1121

    
1122
    try {
1123
      $filename = "a\xFFtest\x80€.txt";
1124
      file_create_filename($filename, $directory);
1125
      $this->fail('Expected exception not thrown');
1126
    }
1127
    catch (RuntimeException $e) {
1128
      $this->assertEqual("Invalid filename '$filename'", $e->getMessage(), 'The invalid filename has been detected and RuntimeException has been thrown.');
1129
    }
1130

    
1131
    // @TODO: Finally we copy a file into a directory several times, to ensure a properly iterating filename suffix.
1132
  }
1133

    
1134
  /**
1135
   * This will test the filepath for a destination based on passed flags and
1136
   * whether or not the file exists.
1137
   *
1138
   * If a file exists, file_destination($destination, $replace) will either
1139
   * return:
1140
   * - the existing filepath, if $replace is FILE_EXISTS_REPLACE
1141
   * - a new filepath if FILE_EXISTS_RENAME
1142
   * - an error (returning FALSE) if FILE_EXISTS_ERROR.
1143
   * If the file doesn't currently exist, then it will simply return the
1144
   * filepath.
1145
   */
1146
  function testFileDestination() {
1147
    // First test for non-existent file.
1148
    $destination = 'misc/xyz.txt';
1149
    $path = file_destination($destination, FILE_EXISTS_REPLACE);
1150
    $this->assertEqual($path, $destination, 'Non-existing filepath destination is correct with FILE_EXISTS_REPLACE.', 'File');
1151
    $path = file_destination($destination, FILE_EXISTS_RENAME);
1152
    $this->assertEqual($path, $destination, 'Non-existing filepath destination is correct with FILE_EXISTS_RENAME.', 'File');
1153
    $path = file_destination($destination, FILE_EXISTS_ERROR);
1154
    $this->assertEqual($path, $destination, 'Non-existing filepath destination is correct with FILE_EXISTS_ERROR.', 'File');
1155

    
1156
    $destination = 'misc/druplicon.png';
1157
    $path = file_destination($destination, FILE_EXISTS_REPLACE);
1158
    $this->assertEqual($path, $destination, 'Existing filepath destination remains the same with FILE_EXISTS_REPLACE.', 'File');
1159
    $path = file_destination($destination, FILE_EXISTS_RENAME);
1160
    $this->assertNotEqual($path, $destination, 'A new filepath destination is created when filepath destination already exists with FILE_EXISTS_RENAME.', 'File');
1161
    $path = file_destination($destination, FILE_EXISTS_ERROR);
1162
    $this->assertEqual($path, FALSE, 'An error is returned when filepath destination already exists with FILE_EXISTS_ERROR.', 'File');
1163

    
1164
    try {
1165
      file_destination("core/misc/a\xFFtest\x80€.txt", FILE_EXISTS_REPLACE);
1166
      $this->fail('Expected exception not thrown');
1167
    }
1168
    catch (RuntimeException $e) {
1169
      $this->assertEqual("Invalid filename 'a\xFFtest\x80€.txt'", $e->getMessage(), 'The invalid destination has been detected and RuntimeException has been thrown.');
1170
    }
1171
  }
1172

    
1173
  /**
1174
   * Ensure that the file_directory_temp() function always returns a value.
1175
   */
1176
  function testFileDirectoryTemp() {
1177
    // Start with an empty variable to ensure we have a clean slate.
1178
    variable_set('file_temporary_path', '');
1179
    $tmp_directory = file_directory_temp();
1180
    $this->assertEqual(empty($tmp_directory), FALSE, 'file_directory_temp() returned a non-empty value.');
1181
    $setting = variable_get('file_temporary_path', '');
1182
    $this->assertEqual($setting, $tmp_directory, "The 'file_temporary_path' variable has the same value that file_directory_temp() returned.");
1183
  }
1184
}
1185

    
1186
/**
1187
 * Directory related tests.
1188
 */
1189
class RemoteFileDirectoryTest extends FileDirectoryTest {
1190
  public static function getInfo() {
1191
    $info = parent::getInfo();
1192
    $info['group'] = 'File API (remote)';
1193
    return $info;
1194
  }
1195

    
1196
  function setUp() {
1197
    parent::setUp('file_test');
1198
    variable_set('file_default_scheme', 'dummy-remote');
1199
  }
1200
}
1201

    
1202
/**
1203
 * Tests the file_scan_directory() function.
1204
 */
1205
class FileScanDirectoryTest extends FileTestCase {
1206
  public static function getInfo() {
1207
    return array(
1208
      'name' => 'File scan directory',
1209
      'description' => 'Tests the file_scan_directory() function.',
1210
      'group' => 'File API',
1211
    );
1212
  }
1213

    
1214
  function setUp() {
1215
    parent::setUp();
1216
    $this->path = drupal_get_path('module', 'simpletest') . '/files';
1217
  }
1218

    
1219
  /**
1220
   * Check the format of the returned values.
1221
   */
1222
  function testReturn() {
1223
    // Grab a listing of all the JavaSscript files and check that they're
1224
    // passed to the callback.
1225
    $all_files = file_scan_directory($this->path, '/^javascript-/');
1226
    ksort($all_files);
1227
    $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
1228

    
1229
    // Check the first file.
1230
    $file = reset($all_files);
1231
    $this->assertEqual(key($all_files), $file->uri, 'Correct array key was used for the first returned file.');
1232
    $this->assertEqual($file->uri, $this->path . '/javascript-1.txt', 'First file name was set correctly.');
1233
    $this->assertEqual($file->filename, 'javascript-1.txt', 'First basename was set correctly');
1234
    $this->assertEqual($file->name, 'javascript-1', 'First name was set correctly.');
1235

    
1236
    // Check the second file.
1237
    $file = next($all_files);
1238
    $this->assertEqual(key($all_files), $file->uri, 'Correct array key was used for the second returned file.');
1239
    $this->assertEqual($file->uri, $this->path . '/javascript-2.script', 'Second file name was set correctly.');
1240
    $this->assertEqual($file->filename, 'javascript-2.script', 'Second basename was set correctly');
1241
    $this->assertEqual($file->name, 'javascript-2', 'Second name was set correctly.');
1242
  }
1243

    
1244
  /**
1245
   * Check that the callback function is called correctly.
1246
   */
1247
  function testOptionCallback() {
1248
    // When nothing is matched nothing should be passed to the callback.
1249
    $all_files = file_scan_directory($this->path, '/^NONEXISTINGFILENAME/', array('callback' => 'file_test_file_scan_callback'));
1250
    $this->assertEqual(0, count($all_files), 'No files were found.');
1251
    $results = file_test_file_scan_callback();
1252
    file_test_file_scan_callback_reset();
1253
    $this->assertEqual(0, count($results), 'No files were passed to the callback.');
1254

    
1255
    // Grab a listing of all the JavaSscript files and check that they're
1256
    // passed to the callback.
1257
    $all_files = file_scan_directory($this->path, '/^javascript-/', array('callback' => 'file_test_file_scan_callback'));
1258
    $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
1259
    $results = file_test_file_scan_callback();
1260
    file_test_file_scan_callback_reset();
1261
    $this->assertEqual(2, count($results), 'Files were passed to the callback.');
1262
  }
1263

    
1264
  /**
1265
   * Check that the no-mask parameter is honored.
1266
   */
1267
  function testOptionNoMask() {
1268
    // Grab a listing of all the JavaSscript files.
1269
    $all_files = file_scan_directory($this->path, '/^javascript-/');
1270
    $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
1271

    
1272
    // Now use the nomast parameter to filter out the .script file.
1273
    $filtered_files = file_scan_directory($this->path, '/^javascript-/', array('nomask' => '/.script$/'));
1274
    $this->assertEqual(1, count($filtered_files), 'Filtered correctly.');
1275
  }
1276

    
1277
  /**
1278
   * Check that key parameter sets the return value's key.
1279
   */
1280
  function testOptionKey() {
1281
    // "filename", for the path starting with $dir.
1282
    $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script');
1283
    $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filepath')));
1284
    sort($actual);
1285
    $this->assertEqual($expected, $actual, 'Returned the correct values for the filename key.');
1286

    
1287
    // "basename", for the basename of the file.
1288
    $expected = array('javascript-1.txt', 'javascript-2.script');
1289
    $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filename')));
1290
    sort($actual);
1291
    $this->assertEqual($expected, $actual, 'Returned the correct values for the basename key.');
1292

    
1293
    // "name" for the name of the file without an extension.
1294
    $expected = array('javascript-1', 'javascript-2');
1295
    $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'name')));
1296
    sort($actual);
1297
    $this->assertEqual($expected, $actual, 'Returned the correct values for the name key.');
1298

    
1299
    // Invalid option that should default back to "filename".
1300
    $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script');
1301
    $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'INVALID')));
1302
    sort($actual);
1303
    $this->assertEqual($expected, $actual, 'An invalid key defaulted back to the default.');
1304
  }
1305

    
1306
  /**
1307
   * Check that the recurse option decends into subdirectories.
1308
   */
1309
  function testOptionRecurse() {
1310
    $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => FALSE));
1311
    $this->assertTrue(empty($files), "Without recursion couldn't find javascript files.");
1312

    
1313
    $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => TRUE));
1314
    $this->assertEqual(2, count($files), 'With recursion we found the expected javascript files.');
1315
  }
1316

    
1317

    
1318
  /**
1319
   * Check that the min_depth options lets us ignore files in the starting
1320
   * directory.
1321
   */
1322
  function testOptionMinDepth() {
1323
    $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 0));
1324
    $this->assertEqual(2, count($files), 'No minimum-depth gets files in current directory.');
1325

    
1326
    $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 1));
1327
    $this->assertTrue(empty($files), "Minimum-depth of 1 successfully excludes files from current directory.");
1328
  }
1329
}
1330

    
1331
/**
1332
 * Tests the file_scan_directory() function on remote filesystems.
1333
 */
1334
class RemoteFileScanDirectoryTest extends FileScanDirectoryTest {
1335
  public static function getInfo() {
1336
    $info = parent::getInfo();
1337
    $info['group'] = 'File API (remote)';
1338
    return $info;
1339
  }
1340

    
1341
  function setUp() {
1342
    parent::setUp('file_test');
1343
    variable_set('file_default_scheme', 'dummy-remote');
1344
  }
1345
}
1346

    
1347
/**
1348
 * Deletion related tests.
1349
 */
1350
class FileUnmanagedDeleteTest extends FileTestCase {
1351
  public static function getInfo() {
1352
    return array(
1353
      'name' => 'Unmanaged file delete',
1354
      'description' => 'Tests the unmanaged file delete function.',
1355
      'group' => 'File API',
1356
    );
1357
  }
1358

    
1359
  /**
1360
   * Delete a normal file.
1361
   */
1362
  function testNormal() {
1363
    // Create a file for testing
1364
    $file = $this->createFile();
1365

    
1366
    // Delete a regular file
1367
    $this->assertTrue(file_unmanaged_delete($file->uri), 'Deleted worked.');
1368
    $this->assertFalse(file_exists($file->uri), 'Test file has actually been deleted.');
1369
  }
1370

    
1371
  /**
1372
   * Try deleting a missing file.
1373
   */
1374
  function testMissing() {
1375
    // Try to delete a non-existing file
1376
    $this->assertTrue(file_unmanaged_delete(file_default_scheme() . '/' . $this->randomName()), 'Returns true when deleting a non-existent file.');
1377
  }
1378

    
1379
  /**
1380
   * Try deleting a directory.
1381
   */
1382
  function testDirectory() {
1383
    // A directory to operate on.
1384
    $directory = $this->createDirectory();
1385

    
1386
    // Try to delete a directory
1387
    $this->assertFalse(file_unmanaged_delete($directory), 'Could not delete the delete directory.');
1388
    $this->assertTrue(file_exists($directory), 'Directory has not been deleted.');
1389
  }
1390
}
1391

    
1392
/**
1393
 * Deletion related tests on remote filesystems.
1394
 */
1395
class RemoteFileUnmanagedDeleteTest extends FileUnmanagedDeleteTest {
1396
  public static function getInfo() {
1397
    $info = parent::getInfo();
1398
    $info['group'] = 'File API (remote)';
1399
    return $info;
1400
  }
1401

    
1402
  function setUp() {
1403
    parent::setUp('file_test');
1404
    variable_set('file_default_scheme', 'dummy-remote');
1405
  }
1406
}
1407

    
1408
/**
1409
 * Deletion related tests.
1410
 */
1411
class FileUnmanagedDeleteRecursiveTest extends FileTestCase {
1412
  public static function getInfo() {
1413
    return array(
1414
      'name' => 'Unmanaged recursive file delete',
1415
      'description' => 'Tests the unmanaged file delete recursive function.',
1416
      'group' => 'File API',
1417
    );
1418
  }
1419

    
1420
  /**
1421
   * Delete a normal file.
1422
   */
1423
  function testSingleFile() {
1424
    // Create a file for testing
1425
    $filepath = file_default_scheme() . '://' . $this->randomName();
1426
    file_put_contents($filepath, '');
1427

    
1428
    // Delete the file.
1429
    $this->assertTrue(file_unmanaged_delete_recursive($filepath), 'Function reported success.');
1430
    $this->assertFalse(file_exists($filepath), 'Test file has been deleted.');
1431
  }
1432

    
1433
  /**
1434
   * Try deleting an empty directory.
1435
   */
1436
  function testEmptyDirectory() {
1437
    // A directory to operate on.
1438
    $directory = $this->createDirectory();
1439

    
1440
    // Delete the directory.
1441
    $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
1442
    $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
1443
  }
1444

    
1445
  /**
1446
   * Try deleting a directory with some files.
1447
   */
1448
  function testDirectory() {
1449
    // A directory to operate on.
1450
    $directory = $this->createDirectory();
1451
    $filepathA = $directory . '/A';
1452
    $filepathB = $directory . '/B';
1453
    file_put_contents($filepathA, '');
1454
    file_put_contents($filepathB, '');
1455

    
1456
    // Delete the directory.
1457
    $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
1458
    $this->assertFalse(file_exists($filepathA), 'Test file A has been deleted.');
1459
    $this->assertFalse(file_exists($filepathB), 'Test file B has been deleted.');
1460
    $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
1461
  }
1462

    
1463
  /**
1464
   * Try deleting subdirectories with some files.
1465
   */
1466
  function testSubDirectory() {
1467
    // A directory to operate on.
1468
    $directory = $this->createDirectory();
1469
    $subdirectory = $this->createDirectory($directory . '/sub');
1470
    $filepathA = $directory . '/A';
1471
    $filepathB = $subdirectory . '/B';
1472
    file_put_contents($filepathA, '');
1473
    file_put_contents($filepathB, '');
1474

    
1475
    // Delete the directory.
1476
    $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
1477
    $this->assertFalse(file_exists($filepathA), 'Test file A has been deleted.');
1478
    $this->assertFalse(file_exists($filepathB), 'Test file B has been deleted.');
1479
    $this->assertFalse(file_exists($subdirectory), 'Subdirectory has been deleted.');
1480
    $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
1481
  }
1482
}
1483

    
1484
/**
1485
 * Deletion related tests on remote filesystems.
1486
 */
1487
class RemoteFileUnmanagedDeleteRecursiveTest extends FileUnmanagedDeleteRecursiveTest {
1488
  public static function getInfo() {
1489
    $info = parent::getInfo();
1490
    $info['group'] = 'File API (remote)';
1491
    return $info;
1492
  }
1493

    
1494
  function setUp() {
1495
    parent::setUp('file_test');
1496
    variable_set('file_default_scheme', 'dummy-remote');
1497
  }
1498
}
1499

    
1500
/**
1501
 * Unmanaged move related tests.
1502
 */
1503
class FileUnmanagedMoveTest extends FileTestCase {
1504
  public static function getInfo() {
1505
    return array(
1506
      'name' => 'Unmanaged file moving',
1507
      'description' => 'Tests the unmanaged file move function.',
1508
      'group' => 'File API',
1509
    );
1510
  }
1511

    
1512
  /**
1513
   * Move a normal file.
1514
   */
1515
  function testNormal() {
1516
    // Create a file for testing
1517
    $file = $this->createFile();
1518

    
1519
    // Moving to a new name.
1520
    $desired_filepath = 'public://' . $this->randomName();
1521
    $new_filepath = file_unmanaged_move($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
1522
    $this->assertTrue($new_filepath, 'Move was successful.');
1523
    $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
1524
    $this->assertTrue(file_exists($new_filepath), 'File exists at the new location.');
1525
    $this->assertFalse(file_exists($file->uri), 'No file remains at the old location.');
1526
    $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
1527

    
1528
    // Moving with rename.
1529
    $desired_filepath = 'public://' . $this->randomName();
1530
    $this->assertTrue(file_exists($new_filepath), 'File exists before moving.');
1531
    $this->assertTrue(file_put_contents($desired_filepath, ' '), 'Created a file so a rename will have to happen.');
1532
    $newer_filepath = file_unmanaged_move($new_filepath, $desired_filepath, FILE_EXISTS_RENAME);
1533
    $this->assertTrue($newer_filepath, 'Move was successful.');
1534
    $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
1535
    $this->assertTrue(file_exists($newer_filepath), 'File exists at the new location.');
1536
    $this->assertFalse(file_exists($new_filepath), 'No file remains at the old location.');
1537
    $this->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
1538

    
1539
    // TODO: test moving to a directory (rather than full directory/file path)
1540
    // TODO: test creating and moving normal files (rather than streams)
1541
  }
1542

    
1543
  /**
1544
   * Try to move a missing file.
1545
   */
1546
  function testMissing() {
1547
    // Move non-existent file.
1548
    $new_filepath = file_unmanaged_move($this->randomName(), $this->randomName());
1549
    $this->assertFalse($new_filepath, 'Moving a missing file fails.');
1550
  }
1551

    
1552
  /**
1553
   * Try to move a file onto itself.
1554
   */
1555
  function testOverwriteSelf() {
1556
    // Create a file for testing.
1557
    $file = $this->createFile();
1558

    
1559
    // Move the file onto itself without renaming shouldn't make changes.
1560
    $new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_REPLACE);
1561
    $this->assertFalse($new_filepath, 'Moving onto itself without renaming fails.');
1562
    $this->assertTrue(file_exists($file->uri), 'File exists after moving onto itself.');
1563

    
1564
    // Move the file onto itself with renaming will result in a new filename.
1565
    $new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_RENAME);
1566
    $this->assertTrue($new_filepath, 'Moving onto itself with renaming works.');
1567
    $this->assertFalse(file_exists($file->uri), 'Original file has been removed.');
1568
    $this->assertTrue(file_exists($new_filepath), 'File exists after moving onto itself.');
1569
  }
1570
}
1571

    
1572
/**
1573
 * Unmanaged move related tests on remote filesystems.
1574
 */
1575
class RemoteFileUnmanagedMoveTest extends FileUnmanagedMoveTest {
1576
  public static function getInfo() {
1577
    $info = parent::getInfo();
1578
    $info['group'] = 'File API (remote)';
1579
    return $info;
1580
  }
1581

    
1582
  function setUp() {
1583
    parent::setUp('file_test');
1584
    variable_set('file_default_scheme', 'dummy-remote');
1585
  }
1586
}
1587

    
1588
/**
1589
 * Unmanaged copy related tests.
1590
 */
1591
class FileUnmanagedCopyTest extends FileTestCase {
1592
  public static function getInfo() {
1593
    return array(
1594
      'name' => 'Unmanaged file copying',
1595
      'description' => 'Tests the unmanaged file copy function.',
1596
      'group' => 'File API',
1597
    );
1598
  }
1599

    
1600
  /**
1601
   * Copy a normal file.
1602
   */
1603
  function testNormal() {
1604
    // Create a file for testing
1605
    $file = $this->createFile();
1606

    
1607
    // Copying to a new name.
1608
    $desired_filepath = 'public://' . $this->randomName();
1609
    $new_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
1610
    $this->assertTrue($new_filepath, 'Copy was successful.');
1611
    $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
1612
    $this->assertTrue(file_exists($file->uri), 'Original file remains.');
1613
    $this->assertTrue(file_exists($new_filepath), 'New file exists.');
1614
    $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
1615

    
1616
    // Copying with rename.
1617
    $desired_filepath = 'public://' . $this->randomName();
1618
    $this->assertTrue(file_put_contents($desired_filepath, ' '), 'Created a file so a rename will have to happen.');
1619
    $newer_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_RENAME);
1620
    $this->assertTrue($newer_filepath, 'Copy was successful.');
1621
    $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
1622
    $this->assertTrue(file_exists($file->uri), 'Original file remains.');
1623
    $this->assertTrue(file_exists($newer_filepath), 'New file exists.');
1624
    $this->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
1625

    
1626
    // TODO: test copying to a directory (rather than full directory/file path)
1627
    // TODO: test copying normal files using normal paths (rather than only streams)
1628
  }
1629

    
1630
  /**
1631
   * Copy a non-existent file.
1632
   */
1633
  function testNonExistent() {
1634
    // Copy non-existent file
1635
    $desired_filepath = $this->randomName();
1636
    $this->assertFalse(file_exists($desired_filepath), "Randomly named file doesn't exists.");
1637
    $new_filepath = file_unmanaged_copy($desired_filepath, $this->randomName());
1638
    $this->assertFalse($new_filepath, 'Copying a missing file fails.');
1639
  }
1640

    
1641
  /**
1642
   * Copy a file onto itself.
1643
   */
1644
  function testOverwriteSelf() {
1645
    // Create a file for testing
1646
    $file = $this->createFile();
1647

    
1648
    // Copy the file onto itself with renaming works.
1649
    $new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_RENAME);
1650
    $this->assertTrue($new_filepath, 'Copying onto itself with renaming works.');
1651
    $this->assertNotEqual($new_filepath, $file->uri, 'Copied file has a new name.');
1652
    $this->assertTrue(file_exists($file->uri), 'Original file exists after copying onto itself.');
1653
    $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
1654
    $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
1655

    
1656
    // Copy the file onto itself without renaming fails.
1657
    $new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_ERROR);
1658
    $this->assertFalse($new_filepath, 'Copying onto itself without renaming fails.');
1659
    $this->assertTrue(file_exists($file->uri), 'File exists after copying onto itself.');
1660

    
1661
    // Copy the file into same directory without renaming fails.
1662
    $new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_ERROR);
1663
    $this->assertFalse($new_filepath, 'Copying onto itself fails.');
1664
    $this->assertTrue(file_exists($file->uri), 'File exists after copying onto itself.');
1665

    
1666
    // Copy the file into same directory with renaming works.
1667
    $new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_RENAME);
1668
    $this->assertTrue($new_filepath, 'Copying into same directory works.');
1669
    $this->assertNotEqual($new_filepath, $file->uri, 'Copied file has a new name.');
1670
    $this->assertTrue(file_exists($file->uri), 'Original file exists after copying onto itself.');
1671
    $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
1672
    $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
1673
  }
1674
}
1675

    
1676
/**
1677
 * Unmanaged copy related tests on remote filesystems.
1678
 */
1679
class RemoteFileUnmanagedCopyTest extends FileUnmanagedCopyTest {
1680
  public static function getInfo() {
1681
    $info = parent::getInfo();
1682
    $info['group'] = 'File API (remote)';
1683
    return $info;
1684
  }
1685

    
1686
  function setUp() {
1687
    parent::setUp('file_test');
1688
    variable_set('file_default_scheme', 'dummy-remote');
1689
  }
1690
}
1691

    
1692
/**
1693
 * Deletion related tests.
1694
 */
1695
class FileDeleteTest extends FileHookTestCase {
1696
  public static function getInfo() {
1697
    return array(
1698
      'name' => 'File delete',
1699
      'description' => 'Tests the file delete function.',
1700
      'group' => 'File API',
1701
    );
1702
  }
1703

    
1704
  /**
1705
   * Tries deleting a normal file (as opposed to a directory, symlink, etc).
1706
   */
1707
  function testUnused() {
1708
    $file = $this->createFile();
1709

    
1710
    // Check that deletion removes the file and database record.
1711
    $this->assertTrue(is_file($file->uri), 'File exists.');
1712
    $this->assertIdentical(file_delete($file), TRUE, 'Delete worked.');
1713
    $this->assertFileHooksCalled(array('delete'));
1714
    $this->assertFalse(file_exists($file->uri), 'Test file has actually been deleted.');
1715
    $this->assertFalse(file_load($file->fid), 'File was removed from the database.');
1716
  }
1717

    
1718
  /**
1719
   * Tries deleting a file that is in use.
1720
   */
1721
  function testInUse() {
1722
    $file = $this->createFile();
1723
    file_usage_add($file, 'testing', 'test', 1);
1724
    file_usage_add($file, 'testing', 'test', 1);
1725

    
1726
    file_usage_delete($file, 'testing', 'test', 1);
1727
    file_delete($file);
1728
    $usage = file_usage_list($file);
1729
    $this->assertEqual($usage['testing']['test'], array(1 => 1), 'Test file is still in use.');
1730
    $this->assertTrue(file_exists($file->uri), 'File still exists on the disk.');
1731
    $this->assertTrue(file_load($file->fid), 'File still exists in the database.');
1732

    
1733
    // Clear out the call to hook_file_load().
1734
    file_test_reset();
1735

    
1736
    file_usage_delete($file, 'testing', 'test', 1);
1737
    file_delete($file);
1738
    $usage = file_usage_list($file);
1739
    $this->assertFileHooksCalled(array('delete'));
1740
    $this->assertTrue(empty($usage), 'File usage data was removed.');
1741
    $this->assertFalse(file_exists($file->uri), 'File has been deleted after its last usage was removed.');
1742
    $this->assertFalse(file_load($file->fid), 'File was removed from the database.');
1743
  }
1744
}
1745

    
1746

    
1747
/**
1748
 * Move related tests
1749
 */
1750
class FileMoveTest extends FileHookTestCase {
1751
  public static function getInfo() {
1752
    return array(
1753
      'name' => 'File moving',
1754
      'description' => 'Tests the file move function.',
1755
      'group' => 'File API',
1756
    );
1757
  }
1758

    
1759
  /**
1760
   * Move a normal file.
1761
   */
1762
  function testNormal() {
1763
    $contents = $this->randomName(10);
1764
    $source = $this->createFile(NULL, $contents);
1765
    $desired_filepath = 'public://' . $this->randomName();
1766

    
1767
    // Clone the object so we don't have to worry about the function changing
1768
    // our reference copy.
1769
    $result = file_move(clone $source, $desired_filepath, FILE_EXISTS_ERROR);
1770

    
1771
    // Check the return status and that the contents changed.
1772
    $this->assertTrue($result, 'File moved successfully.');
1773
    $this->assertFalse(file_exists($source->uri));
1774
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file correctly written.');
1775

    
1776
    // Check that the correct hooks were called.
1777
    $this->assertFileHooksCalled(array('move', 'load', 'update'));
1778

    
1779
    // Make sure we got the same file back.
1780
    $this->assertEqual($source->fid, $result->fid, format_string("Source file id's' %fid is unchanged after move.", array('%fid' => $source->fid)));
1781

    
1782
    // Reload the file from the database and check that the changes were
1783
    // actually saved.
1784
    $loaded_file = file_load($result->fid, TRUE);
1785
    $this->assertTrue($loaded_file, 'File can be loaded from the database.');
1786
    $this->assertFileUnchanged($result, $loaded_file);
1787
  }
1788

    
1789
  /**
1790
   * Test renaming when moving onto a file that already exists.
1791
   */
1792
  function testExistingRename() {
1793
    // Setup a file to overwrite.
1794
    $contents = $this->randomName(10);
1795
    $source = $this->createFile(NULL, $contents);
1796
    $target = $this->createFile();
1797
    $this->assertDifferentFile($source, $target);
1798

    
1799
    // Clone the object so we don't have to worry about the function changing
1800
    // our reference copy.
1801
    $result = file_move(clone $source, $target->uri, FILE_EXISTS_RENAME);
1802

    
1803
    // Check the return status and that the contents changed.
1804
    $this->assertTrue($result, 'File moved successfully.');
1805
    $this->assertFalse(file_exists($source->uri));
1806
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file correctly written.');
1807

    
1808
    // Check that the correct hooks were called.
1809
    $this->assertFileHooksCalled(array('move', 'load', 'update'));
1810

    
1811
    // Compare the returned value to what made it into the database.
1812
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
1813
    // The target file should not have been altered.
1814
    $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
1815
    // Make sure we end up with two distinct files afterwards.
1816
    $this->assertDifferentFile($target, $result);
1817

    
1818
    // Compare the source and results.
1819
    $loaded_source = file_load($source->fid, TRUE);
1820
    $this->assertEqual($loaded_source->fid, $result->fid, "Returned file's id matches the source.");
1821
    $this->assertNotEqual($loaded_source->uri, $source->uri, 'Returned file path has changed from the original.');
1822
  }
1823

    
1824
  /**
1825
   * Test replacement when moving onto a file that already exists.
1826
   */
1827
  function testExistingReplace() {
1828
    // Setup a file to overwrite.
1829
    $contents = $this->randomName(10);
1830
    $source = $this->createFile(NULL, $contents);
1831
    $target = $this->createFile();
1832
    $this->assertDifferentFile($source, $target);
1833

    
1834
    // Clone the object so we don't have to worry about the function changing
1835
    // our reference copy.
1836
    $result = file_move(clone $source, $target->uri, FILE_EXISTS_REPLACE);
1837

    
1838
    // Look at the results.
1839
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were overwritten.');
1840
    $this->assertFalse(file_exists($source->uri));
1841
    $this->assertTrue($result, 'File moved successfully.');
1842

    
1843
    // Check that the correct hooks were called.
1844
    $this->assertFileHooksCalled(array('move', 'update', 'delete', 'load'));
1845

    
1846
    // Reload the file from the database and check that the changes were
1847
    // actually saved.
1848
    $loaded_result = file_load($result->fid, TRUE);
1849
    $this->assertFileUnchanged($result, $loaded_result);
1850
    // Check that target was re-used.
1851
    $this->assertSameFile($target, $loaded_result);
1852
    // Source and result should be totally different.
1853
    $this->assertDifferentFile($source, $loaded_result);
1854
  }
1855

    
1856
  /**
1857
   * Test replacement when moving onto itself.
1858
   */
1859
  function testExistingReplaceSelf() {
1860
    // Setup a file to overwrite.
1861
    $contents = $this->randomName(10);
1862
    $source = $this->createFile(NULL, $contents);
1863

    
1864
    // Copy the file over itself. Clone the object so we don't have to worry
1865
    // about the function changing our reference copy.
1866
    $result = file_move(clone $source, $source->uri, FILE_EXISTS_REPLACE);
1867
    $this->assertFalse($result, 'File move failed.');
1868
    $this->assertEqual($contents, file_get_contents($source->uri), 'Contents of file were not altered.');
1869

    
1870
    // Check that no hooks were called while failing.
1871
    $this->assertFileHooksCalled(array());
1872

    
1873
    // Load the file from the database and make sure it is identical to what
1874
    // was returned.
1875
    $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
1876
  }
1877

    
1878
  /**
1879
   * Test that moving onto an existing file fails when FILE_EXISTS_ERROR is
1880
   * specified.
1881
   */
1882
  function testExistingError() {
1883
    $contents = $this->randomName(10);
1884
    $source = $this->createFile();
1885
    $target = $this->createFile(NULL, $contents);
1886
    $this->assertDifferentFile($source, $target);
1887

    
1888
    // Clone the object so we don't have to worry about the function changing
1889
    // our reference copy.
1890
    $result = file_move(clone $source, $target->uri, FILE_EXISTS_ERROR);
1891

    
1892
    // Check the return status and that the contents did not change.
1893
    $this->assertFalse($result, 'File move failed.');
1894
    $this->assertTrue(file_exists($source->uri));
1895
    $this->assertEqual($contents, file_get_contents($target->uri), 'Contents of file were not altered.');
1896

    
1897
    // Check that no hooks were called while failing.
1898
    $this->assertFileHooksCalled(array());
1899

    
1900
    // Load the file from the database and make sure it is identical to what
1901
    // was returned.
1902
    $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
1903
    $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
1904
  }
1905
}
1906

    
1907

    
1908
/**
1909
 * Copy related tests.
1910
 */
1911
class FileCopyTest extends FileHookTestCase {
1912
  public static function getInfo() {
1913
    return array(
1914
      'name' => 'File copying',
1915
      'description' => 'Tests the file copy function.',
1916
      'group' => 'File API',
1917
    );
1918
  }
1919

    
1920
  /**
1921
   * Test file copying in the normal, base case.
1922
   */
1923
  function testNormal() {
1924
    $contents = $this->randomName(10);
1925
    $source = $this->createFile(NULL, $contents);
1926
    $desired_uri = 'public://' . $this->randomName();
1927

    
1928
    // Clone the object so we don't have to worry about the function changing
1929
    // our reference copy.
1930
    $result = file_copy(clone $source, $desired_uri, FILE_EXISTS_ERROR);
1931

    
1932
    // Check the return status and that the contents changed.
1933
    $this->assertTrue($result, 'File copied successfully.');
1934
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were copied correctly.');
1935

    
1936
    // Check that the correct hooks were called.
1937
    $this->assertFileHooksCalled(array('copy', 'insert'));
1938

    
1939
    $this->assertDifferentFile($source, $result);
1940
    $this->assertEqual($result->uri, $desired_uri, 'The copied file object has the desired filepath.');
1941
    $this->assertTrue(file_exists($source->uri), 'The original file still exists.');
1942
    $this->assertTrue(file_exists($result->uri), 'The copied file exists.');
1943

    
1944
    // Reload the file from the database and check that the changes were
1945
    // actually saved.
1946
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
1947
  }
1948

    
1949
  /**
1950
   * Test renaming when copying over a file that already exists.
1951
   */
1952
  function testExistingRename() {
1953
    // Setup a file to overwrite.
1954
    $contents = $this->randomName(10);
1955
    $source = $this->createFile(NULL, $contents);
1956
    $target = $this->createFile();
1957
    $this->assertDifferentFile($source, $target);
1958

    
1959
    // Clone the object so we don't have to worry about the function changing
1960
    // our reference copy.
1961
    $result = file_copy(clone $source, $target->uri, FILE_EXISTS_RENAME);
1962

    
1963
    // Check the return status and that the contents changed.
1964
    $this->assertTrue($result, 'File copied successfully.');
1965
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were copied correctly.');
1966
    $this->assertNotEqual($result->uri, $source->uri, 'Returned file path has changed from the original.');
1967

    
1968
    // Check that the correct hooks were called.
1969
    $this->assertFileHooksCalled(array('copy', 'insert'));
1970

    
1971
    // Load all the affected files to check the changes that actually made it
1972
    // to the database.
1973
    $loaded_source = file_load($source->fid, TRUE);
1974
    $loaded_target = file_load($target->fid, TRUE);
1975
    $loaded_result = file_load($result->fid, TRUE);
1976

    
1977
    // Verify that the source file wasn't changed.
1978
    $this->assertFileUnchanged($source, $loaded_source);
1979

    
1980
    // Verify that what was returned is what's in the database.
1981
    $this->assertFileUnchanged($result, $loaded_result);
1982

    
1983
    // Make sure we end up with three distinct files afterwards.
1984
    $this->assertDifferentFile($loaded_source, $loaded_target);
1985
    $this->assertDifferentFile($loaded_target, $loaded_result);
1986
    $this->assertDifferentFile($loaded_source, $loaded_result);
1987
  }
1988

    
1989
  /**
1990
   * Test replacement when copying over a file that already exists.
1991
   */
1992
  function testExistingReplace() {
1993
    // Setup a file to overwrite.
1994
    $contents = $this->randomName(10);
1995
    $source = $this->createFile(NULL, $contents);
1996
    $target = $this->createFile();
1997
    $this->assertDifferentFile($source, $target);
1998

    
1999
    // Clone the object so we don't have to worry about the function changing
2000
    // our reference copy.
2001
    $result = file_copy(clone $source, $target->uri, FILE_EXISTS_REPLACE);
2002

    
2003
    // Check the return status and that the contents changed.
2004
    $this->assertTrue($result, 'File copied successfully.');
2005
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were overwritten.');
2006
    $this->assertDifferentFile($source, $result);
2007

    
2008
    // Check that the correct hooks were called.
2009
    $this->assertFileHooksCalled(array('load', 'copy', 'update'));
2010

    
2011
    // Load all the affected files to check the changes that actually made it
2012
    // to the database.
2013
    $loaded_source = file_load($source->fid, TRUE);
2014
    $loaded_target = file_load($target->fid, TRUE);
2015
    $loaded_result = file_load($result->fid, TRUE);
2016

    
2017
    // Verify that the source file wasn't changed.
2018
    $this->assertFileUnchanged($source, $loaded_source);
2019

    
2020
    // Verify that what was returned is what's in the database.
2021
    $this->assertFileUnchanged($result, $loaded_result);
2022

    
2023
    // Target file was reused for the result.
2024
    $this->assertFileUnchanged($loaded_target, $loaded_result);
2025
  }
2026

    
2027
  /**
2028
   * Test that copying over an existing file fails when FILE_EXISTS_ERROR is
2029
   * specified.
2030
   */
2031
  function testExistingError() {
2032
    $contents = $this->randomName(10);
2033
    $source = $this->createFile();
2034
    $target = $this->createFile(NULL, $contents);
2035
    $this->assertDifferentFile($source, $target);
2036

    
2037
    // Clone the object so we don't have to worry about the function changing
2038
    // our reference copy.
2039
    $result = file_copy(clone $source, $target->uri, FILE_EXISTS_ERROR);
2040

    
2041
    // Check the return status and that the contents were not changed.
2042
    $this->assertFalse($result, 'File copy failed.');
2043
    $this->assertEqual($contents, file_get_contents($target->uri), 'Contents of file were not altered.');
2044

    
2045
    // Check that the correct hooks were called.
2046
    $this->assertFileHooksCalled(array());
2047

    
2048
    $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
2049
    $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
2050
  }
2051
}
2052

    
2053

    
2054
/**
2055
 * Tests the file_load() function.
2056
 */
2057
class FileLoadTest extends FileHookTestCase {
2058
  public static function getInfo() {
2059
    return array(
2060
      'name' => 'File loading',
2061
      'description' => 'Tests the file_load() function.',
2062
      'group' => 'File API',
2063
    );
2064
  }
2065

    
2066
  /**
2067
   * Try to load a non-existent file by fid.
2068
   */
2069
  function testLoadMissingFid() {
2070
    $this->assertFalse(file_load(-1), "Try to load an invalid fid fails.");
2071
    $this->assertFileHooksCalled(array());
2072
  }
2073

    
2074
  /**
2075
   * Try to load a non-existent file by URI.
2076
   */
2077
  function testLoadMissingFilepath() {
2078
    $files = file_load_multiple(array(), array('uri' => 'foobar://misc/druplicon.png'));
2079
    $this->assertFalse(reset($files), "Try to load a file that doesn't exist in the database fails.");
2080
    $this->assertFileHooksCalled(array());
2081
  }
2082

    
2083
  /**
2084
   * Try to load a non-existent file by status.
2085
   */
2086
  function testLoadInvalidStatus() {
2087
    $files = file_load_multiple(array(), array('status' => -99));
2088
    $this->assertFalse(reset($files), "Trying to load a file with an invalid status fails.");
2089
    $this->assertFileHooksCalled(array());
2090
  }
2091

    
2092
  /**
2093
   * Load a single file and ensure that the correct values are returned.
2094
   */
2095
  function testSingleValues() {
2096
    // Create a new file object from scratch so we know the values.
2097
    $file = $this->createFile('druplicon.txt', NULL, 'public');
2098

    
2099
    $by_fid_file = file_load($file->fid);
2100
    $this->assertFileHookCalled('load');
2101
    $this->assertTrue(is_object($by_fid_file), 'file_load() returned an object.');
2102
    $this->assertEqual($by_fid_file->fid, $file->fid, 'Loading by fid got the same fid.', 'File');
2103
    $this->assertEqual($by_fid_file->uri, $file->uri, 'Loading by fid got the correct filepath.', 'File');
2104
    $this->assertEqual($by_fid_file->filename, $file->filename, 'Loading by fid got the correct filename.', 'File');
2105
    $this->assertEqual($by_fid_file->filemime, $file->filemime, 'Loading by fid got the correct MIME type.', 'File');
2106
    $this->assertEqual($by_fid_file->status, $file->status, 'Loading by fid got the correct status.', 'File');
2107
    $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
2108
  }
2109

    
2110
  /**
2111
   * This will test loading file data from the database.
2112
   */
2113
  function testMultiple() {
2114
    // Create a new file object.
2115
    $file = $this->createFile('druplicon.txt', NULL, 'public');
2116

    
2117
    // Load by path.
2118
    file_test_reset();
2119
    $by_path_files = file_load_multiple(array(), array('uri' => $file->uri));
2120
    $this->assertFileHookCalled('load');
2121
    $this->assertEqual(1, count($by_path_files), 'file_load_multiple() returned an array of the correct size.');
2122
    $by_path_file = reset($by_path_files);
2123
    $this->assertTrue($by_path_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
2124
    $this->assertEqual($by_path_file->fid, $file->fid, 'Loading by filepath got the correct fid.', 'File');
2125

    
2126
    // Load by fid.
2127
    file_test_reset();
2128
    $by_fid_files = file_load_multiple(array($file->fid), array());
2129
    $this->assertFileHookCalled('load');
2130
    $this->assertEqual(1, count($by_fid_files), 'file_load_multiple() returned an array of the correct size.');
2131
    $by_fid_file = reset($by_fid_files);
2132
    $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
2133
    $this->assertEqual($by_fid_file->uri, $file->uri, 'Loading by fid got the correct filepath.', 'File');
2134
  }
2135
}
2136

    
2137
/**
2138
 * Tests the file_save() function.
2139
 */
2140
class FileSaveTest extends FileHookTestCase {
2141
  public static function getInfo() {
2142
    return array(
2143
      'name' => 'File saving',
2144
      'description' => 'Tests the file_save() function.',
2145
      'group' => 'File API',
2146
    );
2147
  }
2148

    
2149
  function testFileSave() {
2150
    // Create a new file object.
2151
    $file = array(
2152
      'uid' => 1,
2153
      'filename' => 'druplicon.txt',
2154
      'uri' => 'public://druplicon.txt',
2155
      'filemime' => 'text/plain',
2156
      'timestamp' => 1,
2157
      'status' => FILE_STATUS_PERMANENT,
2158
    );
2159
    $file = (object) $file;
2160
    file_put_contents($file->uri, 'hello world');
2161

    
2162
    // Save it, inserting a new record.
2163
    $saved_file = file_save($file);
2164

    
2165
    // Check that the correct hooks were called.
2166
    $this->assertFileHooksCalled(array('insert'));
2167

    
2168
    $this->assertNotNull($saved_file, 'Saving the file should give us back a file object.', 'File');
2169
    $this->assertTrue($saved_file->fid > 0, 'A new file ID is set when saving a new file to the database.', 'File');
2170
    $loaded_file = db_query('SELECT * FROM {file_managed} f WHERE f.fid = :fid', array(':fid' => $saved_file->fid))->fetch(PDO::FETCH_OBJ);
2171
    $this->assertNotNull($loaded_file, 'Record exists in the database.');
2172
    $this->assertEqual($loaded_file->status, $file->status, 'Status was saved correctly.');
2173
    $this->assertEqual($saved_file->filesize, filesize($file->uri), 'File size was set correctly.', 'File');
2174
    $this->assertTrue($saved_file->timestamp > 1, 'File size was set correctly.', 'File');
2175

    
2176

    
2177
    // Resave the file, updating the existing record.
2178
    file_test_reset();
2179
    $saved_file->status = 7;
2180
    $resaved_file = file_save($saved_file);
2181

    
2182
    // Check that the correct hooks were called.
2183
    $this->assertFileHooksCalled(array('load', 'update'));
2184

    
2185
    $this->assertEqual($resaved_file->fid, $saved_file->fid, 'The file ID of an existing file is not changed when updating the database.', 'File');
2186
    $this->assertTrue($resaved_file->timestamp >= $saved_file->timestamp, "Timestamp didn't go backwards.", 'File');
2187
    $loaded_file = db_query('SELECT * FROM {file_managed} f WHERE f.fid = :fid', array(':fid' => $saved_file->fid))->fetch(PDO::FETCH_OBJ);
2188
    $this->assertNotNull($loaded_file, 'Record still exists in the database.', 'File');
2189
    $this->assertEqual($loaded_file->status, $saved_file->status, 'Status was saved correctly.');
2190

    
2191
    // Try to insert a second file with the same name apart from case insensitivity
2192
    // to ensure the 'uri' index allows for filenames with different cases.
2193
    $file = (object) array(
2194
      'uid' => 1,
2195
      'filename' => 'DRUPLICON.txt',
2196
      'uri' => 'public://DRUPLICON.txt',
2197
      'filemime' => 'text/plain',
2198
      'timestamp' => 1,
2199
      'status' => FILE_STATUS_PERMANENT,
2200
    );
2201
    file_put_contents($file->uri, 'hello world');
2202
    file_save($file);
2203
  }
2204
}
2205

    
2206
/**
2207
 * Tests file usage functions.
2208
 */
2209
class FileUsageTest extends FileTestCase {
2210
  public static function getInfo() {
2211
    return array(
2212
      'name' => 'File usage',
2213
      'description' => 'Tests the file usage functions.',
2214
      'group' => 'File',
2215
    );
2216
  }
2217

    
2218
  /**
2219
   * Tests file_usage_list().
2220
   */
2221
  function testGetUsage() {
2222
    $file = $this->createFile();
2223
    db_insert('file_usage')
2224
      ->fields(array(
2225
        'fid' => $file->fid,
2226
        'module' => 'testing',
2227
        'type' => 'foo',
2228
        'id' => 1,
2229
        'count' => 1
2230
      ))
2231
      ->execute();
2232
    db_insert('file_usage')
2233
      ->fields(array(
2234
        'fid' => $file->fid,
2235
        'module' => 'testing',
2236
        'type' => 'bar',
2237
        'id' => 2,
2238
        'count' => 2
2239
      ))
2240
      ->execute();
2241

    
2242
    $usage = file_usage_list($file);
2243

    
2244
    $this->assertEqual(count($usage['testing']), 2, 'Returned the correct number of items.');
2245
    $this->assertTrue(isset($usage['testing']['foo'][1]), 'Returned the correct id.');
2246
    $this->assertTrue(isset($usage['testing']['bar'][2]), 'Returned the correct id.');
2247
    $this->assertEqual($usage['testing']['foo'][1], 1, 'Returned the correct count.');
2248
    $this->assertEqual($usage['testing']['bar'][2], 2, 'Returned the correct count.');
2249
  }
2250

    
2251
  /**
2252
   * Tests file_usage_add().
2253
   */
2254
  function testAddUsage() {
2255
    $file = $this->createFile();
2256
    file_usage_add($file, 'testing', 'foo', 1);
2257
    // Add the file twice to ensure that the count is incremented rather than
2258
    // creating additional records.
2259
    file_usage_add($file, 'testing', 'bar', 2);
2260
    file_usage_add($file, 'testing', 'bar', 2);
2261

    
2262
    $usage = db_select('file_usage', 'f')
2263
      ->fields('f')
2264
      ->condition('f.fid', $file->fid)
2265
      ->execute()
2266
      ->fetchAllAssoc('id');
2267
    $this->assertEqual(count($usage), 2, 'Created two records');
2268
    $this->assertEqual($usage[1]->module, 'testing', 'Correct module');
2269
    $this->assertEqual($usage[2]->module, 'testing', 'Correct module');
2270
    $this->assertEqual($usage[1]->type, 'foo', 'Correct type');
2271
    $this->assertEqual($usage[2]->type, 'bar', 'Correct type');
2272
    $this->assertEqual($usage[1]->count, 1, 'Correct count');
2273
    $this->assertEqual($usage[2]->count, 2, 'Correct count');
2274
  }
2275

    
2276
  /**
2277
   * Tests file_usage_delete().
2278
   */
2279
  function testRemoveUsage() {
2280
    $file = $this->createFile();
2281
    db_insert('file_usage')
2282
      ->fields(array(
2283
        'fid' => $file->fid,
2284
        'module' => 'testing',
2285
        'type' => 'bar',
2286
        'id' => 2,
2287
        'count' => 3,
2288
      ))
2289
      ->execute();
2290

    
2291
    // Normal decrement.
2292
    file_usage_delete($file, 'testing', 'bar', 2);
2293
    $count = db_select('file_usage', 'f')
2294
      ->fields('f', array('count'))
2295
      ->condition('f.fid', $file->fid)
2296
      ->execute()
2297
      ->fetchField();
2298
    $this->assertEqual(2, $count, 'The count was decremented correctly.');
2299

    
2300
    // Multiple decrement and removal.
2301
    file_usage_delete($file, 'testing', 'bar', 2, 2);
2302
    $count = db_select('file_usage', 'f')
2303
      ->fields('f', array('count'))
2304
      ->condition('f.fid', $file->fid)
2305
      ->execute()
2306
      ->fetchField();
2307
    $this->assertIdentical(FALSE, $count, 'The count was removed entirely when empty.');
2308

    
2309
    // Non-existent decrement.
2310
    file_usage_delete($file, 'testing', 'bar', 2);
2311
    $count = db_select('file_usage', 'f')
2312
      ->fields('f', array('count'))
2313
      ->condition('f.fid', $file->fid)
2314
      ->execute()
2315
      ->fetchField();
2316
    $this->assertIdentical(FALSE, $count, 'Decrementing non-exist record complete.');
2317
  }
2318
}
2319

    
2320
/**
2321
 * Tests the file_validate() function..
2322
 */
2323
class FileValidateTest extends FileHookTestCase {
2324
  public static function getInfo() {
2325
    return array(
2326
      'name' => 'File validate',
2327
      'description' => 'Tests the file_validate() function.',
2328
      'group' => 'File API',
2329
    );
2330
  }
2331

    
2332
  /**
2333
   * Test that the validators passed into are checked.
2334
   */
2335
  function testCallerValidation() {
2336
    $file = $this->createFile();
2337

    
2338
    // Empty validators.
2339
    $this->assertEqual(file_validate($file, array()), array(), 'Validating an empty array works successfully.');
2340
    $this->assertFileHooksCalled(array('validate'));
2341

    
2342
    // Use the file_test.module's test validator to ensure that passing tests
2343
    // return correctly.
2344
    file_test_reset();
2345
    file_test_set_return('validate', array());
2346
    $passing = array('file_test_validator' => array(array()));
2347
    $this->assertEqual(file_validate($file, $passing), array(), 'Validating passes.');
2348
    $this->assertFileHooksCalled(array('validate'));
2349

    
2350
    // Now test for failures in validators passed in and by hook_validate.
2351
    file_test_reset();
2352
    file_test_set_return('validate', array('Epic fail'));
2353
    $failing = array('file_test_validator' => array(array('Failed', 'Badly')));
2354
    $this->assertEqual(file_validate($file, $failing), array('Failed', 'Badly', 'Epic fail'), 'Validating returns errors.');
2355
    $this->assertFileHooksCalled(array('validate'));
2356
  }
2357

    
2358
  /**
2359
   * Tests hard-coded security check in file_validate().
2360
   */
2361
  public function testInsecureExtensions() {
2362
    $file = $this->createFile('test.php', 'Invalid PHP');
2363

    
2364
    // Test that file_validate() will check for insecure extensions by default.
2365
    $errors = file_validate($file, array());
2366
    $this->assertEqual('For security reasons, your upload has been rejected.', $errors[0]);
2367
    $this->assertFileHooksCalled(array('validate'));
2368
    file_test_reset();
2369

    
2370
    // Test that the 'allow_insecure_uploads' is respected.
2371
    variable_set('allow_insecure_uploads', 1);
2372
    $errors = file_validate($file, array());
2373
    $this->assertEqual(array(), $errors);
2374
    $this->assertFileHooksCalled(array('validate'));
2375
  }
2376
}
2377

    
2378
/**
2379
 *  Tests the file_save_data() function.
2380
 */
2381
class FileSaveDataTest extends FileHookTestCase {
2382
  public static function getInfo() {
2383
    return array(
2384
      'name' => 'File save data',
2385
      'description' => 'Tests the file save data function.',
2386
      'group' => 'File API',
2387
    );
2388
  }
2389

    
2390
  /**
2391
   * Test the file_save_data() function when no filename is provided.
2392
   */
2393
  function testWithoutFilename() {
2394
    $contents = $this->randomName(8);
2395

    
2396
    $result = file_save_data($contents);
2397
    $this->assertTrue($result, 'Unnamed file saved correctly.');
2398

    
2399
    $this->assertEqual(file_default_scheme(), file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
2400
    $this->assertEqual($result->filename, drupal_basename($result->uri), "Filename was set to the file's basename.");
2401
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
2402
    $this->assertEqual($result->filemime, 'application/octet-stream', 'A MIME type was set.');
2403
    $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
2404

    
2405
    // Check that the correct hooks were called.
2406
    $this->assertFileHooksCalled(array('insert'));
2407

    
2408
    // Verify that what was returned is what's in the database.
2409
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
2410
  }
2411

    
2412
  /**
2413
   * Test the file_save_data() function when a filename is provided.
2414
   */
2415
  function testWithFilename() {
2416
    $contents = $this->randomName(8);
2417

    
2418
    // Using filename with non-latin characters.
2419
    $filename = 'Текстовый файл.txt';
2420

    
2421
    $result = file_save_data($contents, 'public://' . $filename);
2422
    $this->assertTrue($result, 'Unnamed file saved correctly.');
2423

    
2424
    $this->assertEqual('public', file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
2425
    $this->assertEqual($filename, drupal_basename($result->uri), 'File was named correctly.');
2426
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
2427
    $this->assertEqual($result->filemime, 'text/plain', 'A MIME type was set.');
2428
    $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
2429

    
2430
    // Check that the correct hooks were called.
2431
    $this->assertFileHooksCalled(array('insert'));
2432

    
2433
    // Verify that what was returned is what's in the database.
2434
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
2435
  }
2436

    
2437
  /**
2438
   * Test file_save_data() when renaming around an existing file.
2439
   */
2440
  function testExistingRename() {
2441
    // Setup a file to overwrite.
2442
    $existing = $this->createFile();
2443
    $contents = $this->randomName(8);
2444

    
2445
    $result = file_save_data($contents, $existing->uri, FILE_EXISTS_RENAME);
2446
    $this->assertTrue($result, 'File saved successfully.');
2447

    
2448
    $this->assertEqual('public', file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
2449
    $this->assertEqual($result->filename, $existing->filename, 'Filename was set to the basename of the source, rather than that of the renamed file.');
2450
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
2451
    $this->assertEqual($result->filemime, 'application/octet-stream', 'A MIME type was set.');
2452
    $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
2453

    
2454
    // Check that the correct hooks were called.
2455
    $this->assertFileHooksCalled(array('insert'));
2456

    
2457
    // Ensure that the existing file wasn't overwritten.
2458
    $this->assertDifferentFile($existing, $result);
2459
    $this->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
2460

    
2461
    // Verify that was returned is what's in the database.
2462
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
2463
  }
2464

    
2465
  /**
2466
   * Test file_save_data() when replacing an existing file.
2467
   */
2468
  function testExistingReplace() {
2469
    // Setup a file to overwrite.
2470
    $existing = $this->createFile();
2471
    $contents = $this->randomName(8);
2472

    
2473
    $result = file_save_data($contents, $existing->uri, FILE_EXISTS_REPLACE);
2474
    $this->assertTrue($result, 'File saved successfully.');
2475

    
2476
    $this->assertEqual('public', file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
2477
    $this->assertEqual($result->filename, $existing->filename, 'Filename was set to the basename of the existing file, rather than preserving the original name.');
2478
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
2479
    $this->assertEqual($result->filemime, 'application/octet-stream', 'A MIME type was set.');
2480
    $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
2481

    
2482
    // Check that the correct hooks were called.
2483
    $this->assertFileHooksCalled(array('load', 'update'));
2484

    
2485
    // Verify that the existing file was re-used.
2486
    $this->assertSameFile($existing, $result);
2487

    
2488
    // Verify that what was returned is what's in the database.
2489
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
2490
  }
2491

    
2492
  /**
2493
   * Test that file_save_data() fails overwriting an existing file.
2494
   */
2495
  function testExistingError() {
2496
    $contents = $this->randomName(8);
2497
    $existing = $this->createFile(NULL, $contents);
2498

    
2499
    // Check the overwrite error.
2500
    $result = file_save_data('asdf', $existing->uri, FILE_EXISTS_ERROR);
2501
    $this->assertFalse($result, 'Overwriting a file fails when FILE_EXISTS_ERROR is specified.');
2502
    $this->assertEqual($contents, file_get_contents($existing->uri), 'Contents of existing file were unchanged.');
2503

    
2504
    // Check that no hooks were called while failing.
2505
    $this->assertFileHooksCalled(array());
2506

    
2507
    // Ensure that the existing file wasn't overwritten.
2508
    $this->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
2509
  }
2510
}
2511

    
2512
/**
2513
 * Tests for download/file transfer functions.
2514
 */
2515
class FileDownloadTest extends FileTestCase {
2516
  public static function getInfo() {
2517
    return array(
2518
      'name' => 'File download',
2519
      'description' => 'Tests for file download/transfer functions.',
2520
      'group' => 'File API',
2521
    );
2522
  }
2523

    
2524
  function setUp() {
2525
    parent::setUp('file_test');
2526
    // Clear out any hook calls.
2527
    file_test_reset();
2528
  }
2529

    
2530
  /**
2531
   * Test the public file transfer system.
2532
   */
2533
  function testPublicFileTransfer() {
2534
    // Test generating an URL to a created file.
2535
    $file = $this->createFile();
2536
    $url = file_create_url($file->uri);
2537
    // URLs can't contain characters outside the ASCII set so $filename has to be
2538
    // encoded.
2539
    $filename = $GLOBALS['base_url'] . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . rawurlencode($file->filename);
2540
    $this->assertEqual($filename, $url, 'Correctly generated a URL for a created file.');
2541
    $this->drupalHead($url);
2542
    $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the created file.');
2543

    
2544
    // Test generating an URL to a shipped file (i.e. a file that is part of
2545
    // Drupal core, a module or a theme, for example a JavaScript file).
2546
    $filepath = 'misc/jquery.js';
2547
    $url = file_create_url($filepath);
2548
    $this->assertEqual($GLOBALS['base_url'] . '/' . $filepath, $url, 'Correctly generated a URL for a shipped file.');
2549
    $this->drupalHead($url);
2550
    $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
2551
  }
2552

    
2553
  /**
2554
   * Test the private file transfer system.
2555
   */
2556
  function testPrivateFileTransfer() {
2557
    // Set file downloads to private so handler functions get called.
2558

    
2559
    // Create a file.
2560
    $contents = $this->randomName(8);
2561
    $file = $this->createFile(NULL, $contents, 'private');
2562
    $url  = file_create_url($file->uri);
2563

    
2564
    // Set file_test access header to allow the download.
2565
    file_test_set_return('download', array('x-foo' => 'Bar'));
2566
    $this->drupalGet($url);
2567
    $headers = $this->drupalGetHeaders();
2568
    $this->assertEqual($headers['x-foo'], 'Bar', 'Found header set by file_test module on private download.');
2569
    $this->assertResponse(200, 'Correctly allowed access to a file when file_test provides headers.');
2570

    
2571
    // Test that the file transferred correctly.
2572
    $this->assertEqual($contents, $this->content, 'Contents of the file are correct.');
2573

    
2574
    // Deny access to all downloads via a -1 header.
2575
    file_test_set_return('download', -1);
2576
    $this->drupalHead($url);
2577
    $this->assertResponse(403, 'Correctly denied access to a file when file_test sets the header to -1.');
2578

    
2579
    // Try non-existent file.
2580
    $url = file_create_url('private://' . $this->randomName());
2581
    $this->drupalHead($url);
2582
    $this->assertResponse(404, 'Correctly returned 404 response for a non-existent file.');
2583
  }
2584

    
2585
  /**
2586
   * Test file_create_url().
2587
   */
2588
  function testFileCreateUrl() {
2589
    global $base_url;
2590

    
2591
    // Tilde (~) is excluded from this test because it is encoded by
2592
    // rawurlencode() in PHP 5.2 but not in PHP 5.3, as per RFC 3986.
2593
    // @see http://www.php.net/manual/en/function.rawurlencode.php#86506
2594
    $basename = " -._!$'\"()*@[]?&+%#,;=:\n\x00" . // "Special" ASCII characters.
2595
      "%23%25%26%2B%2F%3F" . // Characters that look like a percent-escaped string.
2596
      "éøïвβ中國書۞"; // Characters from various non-ASCII alphabets.
2597
    $basename_encoded = '%20-._%21%24%27%22%28%29%2A%40%5B%5D%3F%26%2B%25%23%2C%3B%3D%3A__' .
2598
      '%2523%2525%2526%252B%252F%253F' .
2599
      '%C3%A9%C3%B8%C3%AF%D0%B2%CE%B2%E4%B8%AD%E5%9C%8B%E6%9B%B8%DB%9E';
2600

    
2601
    $this->checkUrl('public', '', $basename, $base_url . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . $basename_encoded);
2602
    $this->checkUrl('private', '', $basename, $base_url . '/system/files/' . $basename_encoded);
2603
    $this->checkUrl('private', '', $basename, $base_url . '/?q=system/files/' . $basename_encoded, '0');
2604
  }
2605

    
2606
  /**
2607
   * Download a file from the URL generated by file_create_url().
2608
   *
2609
   * Create a file with the specified scheme, directory and filename; check that
2610
   * the URL generated by file_create_url() for the specified file equals the
2611
   * specified URL; fetch the URL and then compare the contents to the file.
2612
   *
2613
   * @param $scheme
2614
   *   A scheme, e.g. "public"
2615
   * @param $directory
2616
   *   A directory, possibly ""
2617
   * @param $filename
2618
   *   A filename
2619
   * @param $expected_url
2620
   *   The expected URL
2621
   * @param $clean_url
2622
   *   The value of the clean_url setting
2623
   */
2624
  private function checkUrl($scheme, $directory, $filename, $expected_url, $clean_url = '1') {
2625
    variable_set('clean_url', $clean_url);
2626

    
2627
    // Convert $filename to a valid filename, i.e. strip characters not
2628
    // supported by the filesystem, and create the file in the specified
2629
    // directory.
2630
    $filepath = file_create_filename($filename, $directory);
2631
    $directory_uri = $scheme . '://' . dirname($filepath);
2632
    file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY);
2633
    $file = $this->createFile($filepath, NULL, $scheme);
2634

    
2635
    $url = file_create_url($file->uri);
2636
    $this->assertEqual($url, $expected_url, 'Generated URL matches expected URL.');
2637

    
2638
    if ($scheme == 'private') {
2639
      // Tell the implementation of hook_file_download() in file_test.module
2640
      // that this file may be downloaded.
2641
      file_test_set_return('download', array('x-foo' => 'Bar'));
2642
    }
2643

    
2644
    $this->drupalGet($url);
2645
    if ($this->assertResponse(200) == 'pass') {
2646
      $this->assertRaw(file_get_contents($file->uri), 'Contents of the file are correct.');
2647
    }
2648

    
2649
    file_delete($file);
2650
  }
2651
}
2652

    
2653
/**
2654
 * Tests for file URL rewriting.
2655
 */
2656
class FileURLRewritingTest extends FileTestCase {
2657
  public static function getInfo() {
2658
    return array(
2659
      'name' => 'File URL rewriting',
2660
      'description' => 'Tests for file URL rewriting.',
2661
      'group' => 'File',
2662
    );
2663
  }
2664

    
2665
  function setUp() {
2666
    parent::setUp('file_test');
2667
  }
2668

    
2669
  /**
2670
   * Test the generating of rewritten shipped file URLs.
2671
   */
2672
  function testShippedFileURL()  {
2673
    // Test generating an URL to a shipped file (i.e. a file that is part of
2674
    // Drupal core, a module or a theme, for example a JavaScript file).
2675

    
2676
    // Test alteration of file URLs to use a CDN.
2677
    variable_set('file_test_hook_file_url_alter', 'cdn');
2678
    $filepath = 'misc/jquery.js';
2679
    $url = file_create_url($filepath);
2680
    $this->assertEqual(FILE_URL_TEST_CDN_1 . '/' . $filepath, $url, 'Correctly generated a CDN URL for a shipped file.');
2681
    $filepath = 'misc/favicon.ico';
2682
    $url = file_create_url($filepath);
2683
    $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $filepath, $url, 'Correctly generated a CDN URL for a shipped file.');
2684

    
2685
    // Test alteration of file URLs to use root-relative URLs.
2686
    variable_set('file_test_hook_file_url_alter', 'root-relative');
2687
    $filepath = 'misc/jquery.js';
2688
    $url = file_create_url($filepath);
2689
    $this->assertEqual(base_path() . '/' . $filepath, $url, 'Correctly generated a root-relative URL for a shipped file.');
2690
    $filepath = 'misc/favicon.ico';
2691
    $url = file_create_url($filepath);
2692
    $this->assertEqual(base_path() . '/' . $filepath, $url, 'Correctly generated a root-relative URL for a shipped file.');
2693

    
2694
    // Test alteration of file URLs to use protocol-relative URLs.
2695
    variable_set('file_test_hook_file_url_alter', 'protocol-relative');
2696
    $filepath = 'misc/jquery.js';
2697
    $url = file_create_url($filepath);
2698
    $this->assertEqual('/' . base_path() . '/' . $filepath, $url, 'Correctly generated a protocol-relative URL for a shipped file.');
2699
    $filepath = 'misc/favicon.ico';
2700
    $url = file_create_url($filepath);
2701
    $this->assertEqual('/' . base_path() . '/' . $filepath, $url, 'Correctly generated a protocol-relative URL for a shipped file.');
2702
  }
2703

    
2704
  /**
2705
   * Test the generating of rewritten public created file URLs.
2706
   */
2707
  function testPublicCreatedFileURL() {
2708
    // Test generating an URL to a created file.
2709

    
2710
    // Test alteration of file URLs to use a CDN.
2711
    variable_set('file_test_hook_file_url_alter', 'cdn');
2712
    $file = $this->createFile();
2713
    $url = file_create_url($file->uri);
2714
    $public_directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
2715
    $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a CDN URL for a created file.');
2716

    
2717
    // Test alteration of file URLs to use root-relative URLs.
2718
    variable_set('file_test_hook_file_url_alter', 'root-relative');
2719
    $file = $this->createFile();
2720
    $url = file_create_url($file->uri);
2721
    $this->assertEqual(base_path() . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a root-relative URL for a created file.');
2722

    
2723
    // Test alteration of file URLs to use a protocol-relative URLs.
2724
    variable_set('file_test_hook_file_url_alter', 'protocol-relative');
2725
    $file = $this->createFile();
2726
    $url = file_create_url($file->uri);
2727
    $this->assertEqual('/' . base_path() . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a protocol-relative URL for a created file.');
2728
  }
2729
}
2730

    
2731
/**
2732
 * Tests for file_munge_filename() and file_unmunge_filename().
2733
 */
2734
class FileNameMungingTest extends FileTestCase {
2735
  public static function getInfo() {
2736
    return array(
2737
      'name' => 'File naming',
2738
      'description' => 'Test filename munging and unmunging.',
2739
      'group' => 'File API',
2740
    );
2741
  }
2742

    
2743
  function setUp() {
2744
    parent::setUp();
2745
    $this->bad_extension = 'foo';
2746
    $this->name = $this->randomName() . '.' . $this->bad_extension . '.txt';
2747
    $this->name_with_uc_ext = $this->randomName() . '.' . strtoupper($this->bad_extension) . '.txt';
2748
  }
2749

    
2750
  /**
2751
   * Create a file and munge/unmunge the name.
2752
   */
2753
  function testMunging() {
2754
    // Disable insecure uploads.
2755
    variable_set('allow_insecure_uploads', 0);
2756
    $munged_name = file_munge_filename($this->name, '', TRUE);
2757
    $messages = drupal_get_messages();
2758
    $this->assertTrue(in_array(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $munged_name)), $messages['status']), 'Alert properly set when a file is renamed.');
2759
    $this->assertNotEqual($munged_name, $this->name, format_string('The new filename (%munged) has been modified from the original (%original)', array('%munged' => $munged_name, '%original' => $this->name)));
2760
  }
2761

    
2762
  /**
2763
   * Tests munging with a null byte in the filename.
2764
   */
2765
  function testMungeNullByte() {
2766
    $prefix = $this->randomName();
2767
    $filename = $prefix . '.' . $this->bad_extension . "\0.txt";
2768
    $this->assertEqual(file_munge_filename($filename, ''), $prefix . '.' . $this->bad_extension . '_.txt', 'A filename with a null byte is correctly munged to remove the null byte.');
2769
  }
2770

    
2771
  /**
2772
   * If the allow_insecure_uploads variable evaluates to true, the file should
2773
   * come out untouched, no matter how evil the filename.
2774
   */
2775
  function testMungeIgnoreInsecure() {
2776
    variable_set('allow_insecure_uploads', 1);
2777
    $munged_name = file_munge_filename($this->name, '');
2778
    $this->assertIdentical($munged_name, $this->name, format_string('The original filename (%original) matches the munged filename (%munged) when insecure uploads are enabled.', array('%munged' => $munged_name, '%original' => $this->name)));
2779
  }
2780

    
2781
  /**
2782
   * White listed extensions are ignored by file_munge_filename().
2783
   */
2784
  function testMungeIgnoreWhitelisted() {
2785
    // Declare our extension as whitelisted. The declared extensions should
2786
    // be case insensitive so test using one with a different case.
2787
    $munged_name = file_munge_filename($this->name_with_uc_ext, $this->bad_extension);
2788
    $this->assertIdentical($munged_name, $this->name_with_uc_ext, format_string('The new filename (%munged) matches the original (%original) once the extension has been whitelisted.', array('%munged' => $munged_name, '%original' => $this->name_with_uc_ext)));
2789
    // The allowed extensions should also be normalized.
2790
    $munged_name = file_munge_filename($this->name, strtoupper($this->bad_extension));
2791
    $this->assertIdentical($munged_name, $this->name, format_string('The new filename (%munged) matches the original (%original) also when the whitelisted extension is in uppercase.', array('%munged' => $munged_name, '%original' => $this->name)));
2792
  }
2793

    
2794
  /**
2795
   * Tests unsafe extensions are munged by file_munge_filename().
2796
   */
2797
  public function testMungeUnsafe() {
2798
    $prefix = $this->randomName();
2799
    $name = "$prefix.php.txt";
2800
    // Put the php extension in the allowed list, but since it is in the unsafe
2801
    // extension list, it should still be munged.
2802
    $munged_name = file_munge_filename($name, 'php txt');
2803
    $this->assertIdentical($munged_name, "$prefix.php_.txt", format_string('The filename (%munged) has been modified from the original (%original) if the allowed extension is also on the unsafe list.', array('%munged' => $munged_name, '%original' => $name)));
2804
  }
2805

    
2806
  /**
2807
   * Ensure that unmunge gets your name back.
2808
   */
2809
  function testUnMunge() {
2810
    $munged_name = file_munge_filename($this->name, '', FALSE);
2811
    $unmunged_name = file_unmunge_filename($munged_name);
2812
    $this->assertIdentical($unmunged_name, $this->name, format_string('The unmunged (%unmunged) filename matches the original (%original)', array('%unmunged' => $unmunged_name, '%original' => $this->name)));
2813
  }
2814
}
2815

    
2816
/**
2817
 * Tests for file_get_mimetype().
2818
 */
2819
class FileMimeTypeTest extends DrupalWebTestCase {
2820
  function setUp() {
2821
    parent::setUp('file_test');
2822
  }
2823

    
2824
  public static function getInfo() {
2825
    return array(
2826
      'name' => 'File mimetypes',
2827
      'description' => 'Test filename mimetype detection.',
2828
      'group' => 'File API',
2829
    );
2830
  }
2831

    
2832
  /**
2833
   * Test mapping of mimetypes from filenames.
2834
   */
2835
  public function testFileMimeTypeDetection() {
2836
    $prefix = 'public://';
2837

    
2838
    $test_case = array(
2839
      'test.jar' => 'application/java-archive',
2840
      'test.jpeg' => 'image/jpeg',
2841
      'test.JPEG' => 'image/jpeg',
2842
      'test.jpg' => 'image/jpeg',
2843
      'test.jar.jpg' => 'image/jpeg',
2844
      'test.jpg.jar' => 'application/java-archive',
2845
      'test.pcf.Z' => 'application/x-font',
2846
      'pcf.z' => 'application/octet-stream',
2847
      'jar' => 'application/octet-stream',
2848
      'some.junk' => 'application/octet-stream',
2849
      'foo.file_test_1' => 'madeup/file_test_1',
2850
      'foo.file_test_2' => 'madeup/file_test_2',
2851
      'foo.doc' => 'madeup/doc',
2852
      'test.ogg' => 'audio/ogg',
2853
    );
2854

    
2855
    // Test using default mappings.
2856
    foreach ($test_case as $input => $expected) {
2857
      // Test stream [URI].
2858
      $output = file_get_mimetype($prefix . $input);
2859
      $this->assertIdentical($output, $expected, format_string('Mimetype for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
2860

    
2861
      // Test normal path equivalent
2862
      $output = file_get_mimetype($input);
2863
      $this->assertIdentical($output, $expected, format_string('Mimetype (using default mappings) for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
2864
    }
2865

    
2866
    // Now test passing in the map.
2867
    $mapping = array(
2868
      'mimetypes' => array(
2869
        0 => 'application/java-archive',
2870
        1 => 'image/jpeg',
2871
      ),
2872
      'extensions' => array(
2873
         'jar' => 0,
2874
         'jpg' => 1,
2875
      )
2876
    );
2877

    
2878
    $test_case = array(
2879
      'test.jar' => 'application/java-archive',
2880
      'test.jpeg' => 'application/octet-stream',
2881
      'test.jpg' => 'image/jpeg',
2882
      'test.jar.jpg' => 'image/jpeg',
2883
      'test.jpg.jar' => 'application/java-archive',
2884
      'test.pcf.z' => 'application/octet-stream',
2885
      'pcf.z' => 'application/octet-stream',
2886
      'jar' => 'application/octet-stream',
2887
      'some.junk' => 'application/octet-stream',
2888
      'foo.file_test_1' => 'application/octet-stream',
2889
      'foo.file_test_2' => 'application/octet-stream',
2890
      'foo.doc' => 'application/octet-stream',
2891
      'test.ogg' => 'application/octet-stream',
2892
    );
2893

    
2894
    foreach ($test_case as $input => $expected) {
2895
      $output = file_get_mimetype($input, $mapping);
2896
      $this->assertIdentical($output, $expected, format_string('Mimetype (using passed-in mappings) for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
2897
    }
2898
  }
2899
}
2900

    
2901
/**
2902
 * Tests stream wrapper functions.
2903
 */
2904
class StreamWrapperTest extends DrupalWebTestCase {
2905

    
2906
  protected $scheme = 'dummy';
2907
  protected $classname = 'DrupalDummyStreamWrapper';
2908

    
2909
  public static function getInfo() {
2910
    return array(
2911
      'name' => 'Stream wrappers',
2912
      'description' => 'Tests stream wrapper functions.',
2913
      'group' => 'File API',
2914
    );
2915
  }
2916

    
2917
  function setUp() {
2918
    parent::setUp('file_test');
2919
    drupal_static_reset('file_get_stream_wrappers');
2920
  }
2921

    
2922
  function tearDown() {
2923
    parent::tearDown();
2924
    stream_wrapper_unregister($this->scheme);
2925
  }
2926

    
2927
  /**
2928
   * Test the getClassName() function.
2929
   */
2930
  function testGetClassName() {
2931
    // Check the dummy scheme.
2932
    $this->assertEqual($this->classname, file_stream_wrapper_get_class($this->scheme), 'Got correct class name for dummy scheme.');
2933
    // Check core's scheme.
2934
    $this->assertEqual('DrupalPublicStreamWrapper', file_stream_wrapper_get_class('public'), 'Got correct class name for public scheme.');
2935
  }
2936

    
2937
  /**
2938
   * Test the file_stream_wrapper_get_instance_by_scheme() function.
2939
   */
2940
  function testGetInstanceByScheme() {
2941
    $instance = file_stream_wrapper_get_instance_by_scheme($this->scheme);
2942
    $this->assertEqual($this->classname, get_class($instance), 'Got correct class type for dummy scheme.');
2943

    
2944
    $instance = file_stream_wrapper_get_instance_by_scheme('public');
2945
    $this->assertEqual('DrupalPublicStreamWrapper', get_class($instance), 'Got correct class type for public scheme.');
2946
  }
2947

    
2948
  /**
2949
   * Test the URI and target functions.
2950
   */
2951
  function testUriFunctions() {
2952
    $instance = file_stream_wrapper_get_instance_by_uri($this->scheme . '://foo');
2953
    $this->assertEqual($this->classname, get_class($instance), 'Got correct class type for dummy URI.');
2954

    
2955
    $instance = file_stream_wrapper_get_instance_by_uri('public://foo');
2956
    $this->assertEqual('DrupalPublicStreamWrapper', get_class($instance), 'Got correct class type for public URI.');
2957

    
2958
    // Test file_uri_target().
2959
    $this->assertEqual(file_uri_target('public://foo/bar.txt'), 'foo/bar.txt', 'Got a valid stream target from public://foo/bar.txt.');
2960
    $this->assertFalse(file_uri_target('foo/bar.txt'), 'foo/bar.txt is not a valid stream.');
2961

    
2962
    // Test file_build_uri() and DrupalLocalStreamWrapper::getDirectoryPath().
2963
    $this->assertEqual(file_build_uri('foo/bar.txt'), 'public://foo/bar.txt', 'Expected scheme was added.');
2964
    $this->assertEqual(file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath(), variable_get('file_public_path'), 'Expected default directory path was returned.');
2965
    $this->assertEqual(file_stream_wrapper_get_instance_by_scheme('temporary')->getDirectoryPath(), variable_get('file_temporary_path'), 'Expected temporary directory path was returned.');
2966

    
2967
    variable_set('file_default_scheme', 'private');
2968
    $this->assertEqual(file_build_uri('foo/bar.txt'), 'private://foo/bar.txt', 'Got a valid URI from foo/bar.txt.');
2969
  }
2970

    
2971
  /**
2972
   * Test the scheme functions.
2973
   */
2974
  function testGetValidStreamScheme() {
2975
    $this->assertEqual('foo', file_uri_scheme('foo://pork//chops'), 'Got the correct scheme from foo://asdf');
2976
    $this->assertTrue(file_stream_wrapper_valid_scheme(file_uri_scheme('public://asdf')), 'Got a valid stream scheme from public://asdf');
2977
    $this->assertFalse(file_stream_wrapper_valid_scheme(file_uri_scheme('foo://asdf')), 'Did not get a valid stream scheme from foo://asdf');
2978
  }
2979

    
2980
  /**
2981
   * Tests that phar stream wrapper is registered as expected.
2982
   *
2983
   * @see file_get_stream_wrappers()
2984
   */
2985
  public function testPharStreamWrapperRegistration() {
2986
    if (!class_exists('Phar', FALSE)) {
2987
      $this->assertFalse(in_array('phar', stream_get_wrappers(), TRUE), 'PHP is compiled without phar support. Therefore, no phar stream wrapper is registered.');
2988
    }
2989
    elseif (version_compare(PHP_VERSION, '5.3.3', '<')) {
2990
      $this->assertFalse(in_array('phar', stream_get_wrappers(), TRUE), 'The PHP version is <5.3.3. The built-in phar stream wrapper has been unregistered and not replaced.');
2991
    }
2992
    else {
2993
      $this->assertTrue(in_array('phar', stream_get_wrappers(), TRUE), 'A phar stream wrapper is registered.');
2994
      $this->assertFalse(file_stream_wrapper_valid_scheme('phar'), 'The phar scheme is not a valid scheme for Drupal File API usage.');
2995
    }
2996

    
2997
    // Ensure that calling file_get_stream_wrappers() multiple times, both
2998
    // without and with a drupal_static_reset() in between, does not create
2999
    // errors due to the PharStreamWrapperManager singleton.
3000
    file_get_stream_wrappers();
3001
    file_get_stream_wrappers();
3002
    drupal_static_reset('file_get_stream_wrappers');
3003
    file_get_stream_wrappers();
3004
  }
3005

    
3006
  /**
3007
   * Tests that only valid phar files can be used.
3008
   */
3009
  public function testPharFile() {
3010
    if (!in_array('phar', stream_get_wrappers(), TRUE)) {
3011
      $this->pass('There is no phar stream wrapper registered.');
3012
      // Nothing else in this test is relevant when there's no phar stream
3013
      // wrapper. testPharStreamWrapperRegistration() is sufficient for testing
3014
      // the conditions of when the stream wrapper should or should not be
3015
      // registered.
3016
      return;
3017
    }
3018

    
3019
    $base = dirname(dirname(__FILE__)) . '/files';
3020

    
3021
    // Ensure that file operations via the phar:// stream wrapper work for phar
3022
    // files with the .phar extension.
3023
    $this->assertFalse(file_exists("phar://$base/phar-1.phar/no-such-file.php"));
3024
    $this->assertTrue(file_exists("phar://$base/phar-1.phar/index.php"));
3025
    $file_contents = file_get_contents("phar://$base/phar-1.phar/index.php");
3026
    $expected_hash = 'c7e7904ea573c5ebea3ef00bb08c1f86af1a45961fbfbeb1892ff4a98fd73ad5';
3027
    $this->assertIdentical($expected_hash, hash('sha256', $file_contents));
3028

    
3029
    // Ensure that file operations via the phar:// stream wrapper throw an
3030
    // exception for files without the .phar extension.
3031
    try {
3032
      file_exists("phar://$base/image-2.jpg/index.php");
3033
      $this->fail('Expected exception failed to be thrown when accessing an invalid phar file.');
3034
    }
3035
    catch (Exception $e) {
3036
      $this->assertEqual(get_class($e), 'TYPO3\PharStreamWrapper\Exception', 'Expected exception thrown when accessing an invalid phar file.');
3037
    }
3038
  }
3039
}