file.inc 67.7 KB
Newer Older
Dries's avatar
   
Dries committed
1
<?php
2
// $Id$
Kjartan's avatar
Kjartan committed
3

Dries's avatar
   
Dries committed
4
5
6
7
8
/**
 * @file
 * API for handling file uploads and server file management.
 */

Kjartan's avatar
Kjartan committed
9
/**
Kjartan's avatar
Kjartan committed
10
 * @defgroup file File interface
Kjartan's avatar
Kjartan committed
11
 * @{
Dries's avatar
   
Dries committed
12
 * Common file handling functions.
13
14
15
 *
 * Fields on the file object:
 * - fid - File ID
16
 * - uid - The {user}.uid of the user who is associated with the file.
17
18
19
 * - filename - Name of the file with no path components. This may differ from
 *   the basename of the filepath if the file is renamed to avoid overwriting
 *   an existing file.
20
21
22
 * - filepath - Path of the file relative to Drupal root.
 * - filemime - The file's MIME type.
 * - filesize - The size of the file in bytes.
23
24
25
26
 * - status - A bitmapped field indicating the status of the file. The first 8
 *   bits are reserved for Drupal core. The least sigifigant bit indicates
 *   temporary (0) or permanent (1). Temporary files older than
 *   DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed during cron runs.
27
 * - timestamp - UNIX timestamp for the date the file was added to the database.
Dries's avatar
   
Dries committed
28
29
 */

30
31
32
33
34
35
/**
 * Flag to indicate that the 'public' file download method is enabled.
 *
 * When using this method, files are available from a regular HTTP request,
 * which provides no additional access restrictions.
 */
Dries's avatar
   
Dries committed
36
define('FILE_DOWNLOADS_PUBLIC', 1);
37
38
39
40
41
42
43

/**
 * Flag to indicate that the 'private' file download method is enabled.
 *
 * When using this method, all file requests are served by Drupal, during which
 * access-control checking can be performed.
 */
Dries's avatar
   
Dries committed
44
define('FILE_DOWNLOADS_PRIVATE', 2);
45
46

/**
47
 * Flag used by file_check_directory() -- create directory if not present.
48
 */
Dries's avatar
   
Dries committed
49
define('FILE_CREATE_DIRECTORY', 1);
50
51

/**
52
 * Flag used by file_check_directory() -- file permissions may be changed.
53
 */
Dries's avatar
   
Dries committed
54
define('FILE_MODIFY_PERMISSIONS', 2);
55
56

/**
57
 * Flag for dealing with existing files: Appends number until name is unique.
58
 */
Dries's avatar
   
Dries committed
59
define('FILE_EXISTS_RENAME', 0);
60
61
62
63

/**
 * Flag for dealing with existing files: Replace the existing file.
 */
Dries's avatar
   
Dries committed
64
define('FILE_EXISTS_REPLACE', 1);
65
66
67
68

/**
 * Flag for dealing with existing files: Do nothing and return FALSE.
 */
Dries's avatar
   
Dries committed
69
define('FILE_EXISTS_ERROR', 2);
Dries's avatar
   
Dries committed
70

71
/**
72
73
74
75
 * File status -- This bit in the status indicates that the file is permanent
 * and should not be deleted during file garbage collection process. Temporary
 * files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed during cron
 * runs.
76
 */
77
78
define('FILE_STATUS_PERMANENT', 1);

Dries's avatar
   
Dries committed
79
80
/**
 * Create the download path to a file.
Dries's avatar
   
Dries committed
81
 *
82
83
 * @param $path A string containing the path of the file to generate URL for.
 * @return A string containing a URL that can be used to download the file.
Dries's avatar
   
Dries committed
84
85
 */
function file_create_url($path) {
86
87
  // Strip file_directory_path from $path. We only include relative paths in
  // URLs.
88
  if (strpos($path, file_directory_path() . '/') === 0) {
89
    $path = trim(substr($path, strlen(file_directory_path())), '\\/');
Kjartan's avatar
Kjartan committed
90
  }
91
  switch (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC)) {
Dries's avatar
   
Dries committed
92
    case FILE_DOWNLOADS_PUBLIC:
93
      return $GLOBALS['base_url'] . '/' . file_directory_path() . '/' . str_replace('\\', '/', $path);
Dries's avatar
   
Dries committed
94
    case FILE_DOWNLOADS_PRIVATE:
95
      return url('system/files/' . $path, array('absolute' => TRUE));
Dries's avatar
   
Dries committed
96
97
98
99
  }
}

/**
100
101
 * Make sure the destination is a complete path and resides in the file system
 * directory, if it is not prepend the file system directory.
Dries's avatar
   
Dries committed
102
 *
103
104
105
106
107
108
109
 * @param $destination
 *   A string containing the path to verify. If this value is omitted, Drupal's
 *   'files' directory will be used.
 * @return
 *   A string containing the path to file, with file system directory appended
 *   if necessary, or FALSE if the path is invalid (i.e. outside the configured
 *   'files' or temp directories).
Dries's avatar
   
Dries committed
110
 */
111
function file_create_path($destination = NULL) {
112
  $file_path = file_directory_path();
113
  if (is_null($destination)) {
114
    return $file_path;
Dries's avatar
   
Dries committed
115
  }
116
117
118
119
  // file_check_location() checks whether the destination is inside the Drupal
  // files directory.
  if (file_check_location($destination, $file_path)) {
    return $destination;
Dries's avatar
   
Dries committed
120
  }
121
122
  // Check if the destination is instead inside the Drupal temporary files
  // directory.
123
  elseif (file_check_location($destination, file_directory_temp())) {
124
    return $destination;
125
  }
126
  // Not found, try again with prefixed directory path.
127
  elseif (file_check_location($file_path . '/' . $destination, $file_path)) {
128
    return $file_path . '/' . $destination;
129
130
131
  }
  // File not found.
  return FALSE;
Dries's avatar
   
Dries committed
132
133
134
}

/**
135
136
137
138
139
140
141
142
 * Check that the directory exists and is writable.
 *
 * Directories need to have execute permissions to be considered a directory by
 * FTP servers, etc.
 *
 * @param $directory
 *   A string containing the name of a directory path.
 * @param $mode
143
144
145
 *   A bitmask to indicate if the directory should be created if it does
 *   not exist (FILE_CREATE_DIRECTORY) or made writable if it is read-only
 *   (FILE_MODIFY_PERMISSIONS).
146
147
148
149
150
151
152
 * @param $form_item
 *   An optional string containing the name of a form item that any errors will
 *   be attached to. This is useful for settings forms that require the user to
 *   specify a writable directory. If it can't be made to work, a form error
 *   will be set preventing them from saving the settings.
 * @return
 *   FALSE when directory not found, or TRUE when directory exists.
Dries's avatar
   
Dries committed
153
 */
154
function file_check_directory(&$directory, $mode = 0, $form_item = NULL) {
Dries's avatar
   
Dries committed
155
  $directory = rtrim($directory, '/\\');
Dries's avatar
   
Dries committed
156
157
158

  // Check if directory exists.
  if (!is_dir($directory)) {
159
160
    if (($mode & FILE_CREATE_DIRECTORY) && @mkdir($directory)) {
      @chmod($directory, 0775); // Necessary for non-webserver users.
Dries's avatar
   
Dries committed
161
162
163
    }
    else {
      if ($form_item) {
164
        form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => $directory)));
165
        watchdog('file system', 'The directory %directory does not exist.', array('%directory' => $directory), WATCHDOG_ERROR);
Dries's avatar
   
Dries committed
166
      }
167
      return FALSE;
Dries's avatar
   
Dries committed
168
169
170
171
172
    }
  }

  // Check to see if the directory is writable.
  if (!is_writable($directory)) {
173
174
175
176
177
178
179
    // If not able to modify permissions, or if able to, but chmod
    // fails, return false.
    if (!$mode || (($mode & FILE_MODIFY_PERMISSIONS) && !@chmod($directory, 0775))) {
      if ($form_item) {
        form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => $directory)));
        watchdog('file system', 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => $directory), WATCHDOG_ERROR);
      }
180
      return FALSE;
Dries's avatar
   
Dries committed
181
182
183
    }
  }

184
  if ((file_directory_path() == $directory || file_directory_temp() == $directory) && !is_file("$directory/.htaccess")) {
185
    $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
Gerhard Killesreiter's avatar
Gerhard Killesreiter committed
186
    if (($fp = fopen("$directory/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
187
      fclose($fp);
188
      chmod($directory . '/.htaccess', 0664);
189
190
    }
    else {
191
      $variables = array('%directory' => $directory, '!htaccess' => '<br />' . nl2br(check_plain($htaccess_lines)));
192
193
      form_set_error($form_item, t("Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines: <code>!htaccess</code>", $variables));
      watchdog('security', "Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines: <code>!htaccess</code>", $variables, WATCHDOG_ERROR);
194
195
196
    }
  }

197
  return TRUE;
Dries's avatar
   
Dries committed
198
199
200
}

/**
201
 * Checks path to see if it is a directory, or a directory/file.
Dries's avatar
   
Dries committed
202
 *
203
204
205
206
207
 * @param $path
 *   A string containing a file path. This will be set to the directory's path.
 * @return
 *   If the directory is not in a Drupal writable directory, FALSE is returned.
 *   Otherwise, the base name of the path is returned.
Dries's avatar
   
Dries committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
 */
function file_check_path(&$path) {
  // Check if path is a directory.
  if (file_check_directory($path)) {
    return '';
  }

  // Check if path is a possible dir/file.
  $filename = basename($path);
  $path = dirname($path);
  if (file_check_directory($path)) {
    return $filename;
  }

222
  return FALSE;
Dries's avatar
   
Dries committed
223
224
225
}

/**
226
227
228
229
230
 * Check if a file is really located inside $directory.
 *
 * This should be used to make sure a file specified is really located within
 * the directory to prevent exploits. Note that the file or path being checked
 * does not actually need to exist yet.
Dries's avatar
   
Dries committed
231
232
 *
 * @code
233
 *   // Returns FALSE:
Dries's avatar
   
Dries committed
234
235
236
 *   file_check_location('/www/example.com/files/../../../etc/passwd', '/www/example.com/files');
 * @endcode
 *
237
238
239
240
241
242
243
 * @param $source
 *   A string set to the file to check.
 * @param $directory
 *   A string where the file should be located.
 * @return
 *   FALSE if the path does not exist in the directory; otherwise, the real
 *   path of the source.
Dries's avatar
   
Dries committed
244
 */
245
function file_check_location($source, $directory = '') {
246
247
248
249
250
  $check = realpath($source);
  if ($check) {
    $source = $check;
  }
  else {
251
    // This file does not yet exist.
252
    $source = realpath(dirname($source)) . '/' . basename($source);
253
  }
254
  $directory = realpath($directory);
Dries's avatar
   
Dries committed
255
  if ($directory && strpos($source, $directory) !== 0) {
256
    return FALSE;
Dries's avatar
   
Dries committed
257
258
259
260
261
  }
  return $source;
}

/**
262
 * Load file objects from the database.
263
 *
264
265
266
267
268
 * @param $fids
 *   An array of file IDs.
 * @param $conditions
 *   An array of conditions to match against the {files} table. These
 *   should be supplied in the form array('field_name' => 'field_value').
269
 * @return
270
 *  An array of file objects, indexed by fid.
271
272
 *
 * @see hook_file_load()
273
 * @see file_load()
274
 */
275
276
function file_load_multiple($fids = array(), $conditions = array()) {
  $query = db_select('files', 'f')->fields('f');
277

278
279
280
  // If the $fids array is populated, add those to the query.
  if ($fids) {
    $query->condition('f.fid', $fids, 'IN');
281
282
  }

283
284
285
286
  // If the conditions array is populated, add those to the query.
  if ($conditions) {
    foreach ($conditions as $field => $value) {
      $query->condition('f.' . $field, $value);
287
288
    }
  }
289
  $files = $query->execute()->fetchAllAssoc('fid');
290

291
292
293
294
295
296
297
  // Invoke hook_file_load() on the terms loaded from the database
  // and add them to the static cache.
  if (!empty($files)) {
    foreach (module_implements('file_load') as $module) {
      $function = $module . '_file_load';
      $function($files);
    }
298
  }
299
300
  return $files;
}
301

302
303
304
305
306
307
308
309
310
311
312
313
314
315
/**
 * Load a file object from the database.
 *
 * @param $fid
 *  A file ID.
 * @return
 *   A file object.
 *
 * @see hook_file_load()
 * @see file_load_multiple()
 */
function file_load($fid) {
  $files = file_load_multiple(array($fid), array());
  return reset($files);
316
317
318
319
320
321
322
323
324
325
326
327
}

/**
 * Save a file object to the database.
 *
 * If the $file->fid is not set a new record will be added. Re-saving an
 * existing file will not change its status.
 *
 * @param $file
 *   A file object returned by file_load().
 * @return
 *   The updated file object.
328
 *
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
 * @see hook_file_insert()
 * @see hook_file_update()
 */
function file_save($file) {
  $file = (object)$file;
  $file->timestamp = REQUEST_TIME;
  $file->filesize = filesize($file->filepath);

  if (empty($file->fid)) {
    drupal_write_record('files', $file);
    // Inform modules about the newly added file.
    module_invoke_all('file_insert', $file);
  }
  else {
    drupal_write_record('files', $file, 'fid');
    // Inform modules that the file has been updated.
    module_invoke_all('file_update', $file);
  }

  return $file;
}

/**
 * Copy a file to a new location and adds a file record to the database.
 *
 * This function should be used when manipulating files that have records
 * stored in the database. This is a powerful function that in many ways
 * performs like an advanced version of copy().
 * - Checks if $source and $destination are valid and readable/writable.
 * - Checks that $source is not equal to $destination; if they are an error
 *   is reported.
 * - If file already exists in $destination either the call will error out,
 *   replace the file or rename the file based on the $replace parameter.
 * - Adds the new file to the files database. If the source file is a
 *   temporary file, the resulting file will also be a temporary file.
364
 *   @see file_save_upload() for details on temporary files.
365
366
367
368
 *
 * @param $source
 *   A file object.
 * @param $destination
369
370
371
 *   A string containing the destination that $source should be copied to. This
 *   can be a complete file path, a directory path or, if this value is omitted,
 *   Drupal's 'files' directory will be used.
372
373
 * @param $replace
 *   Replace behavior when the destination file already exists:
374
375
376
 *   - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
 *       the destination name exists then its database entry will be updated. If
 *       no database entry is found then a new one will be created.
377
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
378
 *       unique.
379
380
381
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
 * @return
 *   File object if the copy is successful, or FALSE in the event of an error.
382
 *
383
384
385
386
387
388
389
390
 * @see file_unmanaged_copy()
 * @see hook_file_copy()
 */
function file_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  $source = (object)$source;

  if ($filepath = file_unmanaged_copy($source->filepath, $destination, $replace)) {
    $file = clone $source;
391
    $file->fid = NULL;
392
    $file->filepath = $filepath;
393
394
395
396
397
398
399
400
401
    $file->filename = basename($filepath);
    // If we are replacing an existing file re-use its database record.
    if ($replace == FILE_EXISTS_REPLACE) {
      $existing_files = file_load_multiple(array(), array('filepath' => $filepath));
      if (count($existing_files)) {
        $existing = reset($existing_files);
        $file->fid = $existing->fid;
        $file->filename = $existing->filename;
      }
402
    }
403
404
405
406
407
408
409
410
411
412
413
414
    // If we are renaming around an existing file (rather than a directory),
    // use its basename for the filename.
    else if ($replace == FILE_EXISTS_RENAME && is_file(file_create_path($destination))) {
      $file->filename = basename($destination);
    }

    $file = file_save($file);

    // Inform modules that the file has been copied.
    module_invoke_all('file_copy', $file, $source);

    return $file;
415
416
417
418
419
420
421
  }
  return FALSE;
}

/**
 * Copy a file to a new location without calling any hooks or making any
 * changes to the database.
Dries's avatar
   
Dries committed
422
 *
423
424
425
426
427
428
429
430
431
432
433
 * This is a powerful function that in many ways performs like an advanced
 * version of copy().
 * - Checks if $source and $destination are valid and readable/writable.
 * - Checks that $source is not equal to $destination; if they are an error
 *   is reported.
 * - If file already exists in $destination either the call will error out,
 *   replace the file or rename the file based on the $replace parameter.
 *
 * @param $source
 *   A string specifying the file location of the original file.
 * @param $destination
434
435
436
 *   A string containing the destination that $source should be copied to. This
 *   can be a complete file path, a directory path or, if this value is omitted,
 *   Drupal's 'files' directory will be used.
437
438
439
440
 * @param $replace
 *   Replace behavior when the destination file already exists:
 *   - FILE_EXISTS_REPLACE - Replace the existing file.
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
441
 *       unique.
442
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
443
444
 * @return
 *   The path to the new file, or FALSE in the event of an error.
445
 *
446
 * @see file_copy()
Dries's avatar
   
Dries committed
447
 */
448
function file_unmanaged_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
449
450
451
452
453
  $source = realpath($source);
  if (!file_exists($source)) {
    drupal_set_message(t('The specified file %file could not be copied, because no file by that name exists. Please check that you supplied the correct filename.', array('%file' => $source)), 'error');
    return FALSE;
  }
Dries's avatar
   
Dries committed
454

455
456
  $destination = file_create_path($destination);
  $directory = $destination;
Dries's avatar
   
Dries committed
457
458
459
  $basename = file_check_path($directory);

  // Make sure we at least have a valid directory.
460
  if ($basename === FALSE) {
461
    drupal_set_message(t('The specified file %file could not be copied, because the destination %directory is not properly configured.', array('%file' => $source, '%directory' => $destination)), 'error');
462
    return FALSE;
Dries's avatar
   
Dries committed
463
464
  }

465
466
  // If the destination file is not specified then use the filename of the
  // source file.
Dries's avatar
   
Dries committed
467
  $basename = $basename ? $basename : basename($source);
468
  $destination = file_destination($directory . '/' . $basename, $replace);
469

470
471
472
  if ($destination === FALSE) {
    drupal_set_message(t('The specified file %file could not be copied because a file by that name already exists in the destination.', array('%file' => $source)), 'error');
    return FALSE;
Dries's avatar
   
Dries committed
473
  }
474
475
476
477
478
479
  // Make sure source and destination filenames are not the same, makes no
  // sense to copy it if they are. In fact copying the file will most likely
  // result in a 0 byte file. Which is bad. Real bad.
  if ($source == realpath($destination)) {
    drupal_set_message(t('The specified file %file was not copied because it would overwrite itself.', array('%file' => $source)), 'error');
    return FALSE;
Dries's avatar
   
Dries committed
480
  }
481
482
483
  if (!@copy($source, $destination)) {
    drupal_set_message(t('The specified file %file could not be copied.', array('%file' => $source)), 'error');
    return FALSE;
Dries's avatar
   
Dries committed
484
  }
Dries's avatar
   
Dries committed
485

486
487
488
489
490
491
492
  // Give everyone read access so that FTP'd users or
  // non-webserver users can see/read these files,
  // and give group write permissions so group members
  // can alter files uploaded by the webserver.
  @chmod($destination, 0664);

  return $destination;
Dries's avatar
   
Dries committed
493
494
}

495
496
497
498
/**
 * Determines the destination path for a file depending on how replacement of
 * existing files should be handled.
 *
499
500
501
502
 * @param $destination
 *   A string specifying the desired path.
 * @param $replace
 *   Replace behavior when the destination file already exists.
503
 *   - FILE_EXISTS_REPLACE - Replace the existing file.
504
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
505
 *       unique.
506
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
507
508
 * @return
 *   The destination file path or FALSE if the file already exists and
509
510
511
512
513
 *   FILE_EXISTS_ERROR was specified.
 */
function file_destination($destination, $replace) {
  if (file_exists($destination)) {
    switch ($replace) {
514
515
516
517
      case FILE_EXISTS_REPLACE:
        // Do nothing here, we want to overwrite the existing file.
        break;

518
519
520
521
522
523
524
      case FILE_EXISTS_RENAME:
        $basename = basename($destination);
        $directory = dirname($destination);
        $destination = file_create_filename($basename, $directory);
        break;

      case FILE_EXISTS_ERROR:
525
        drupal_set_message(t('The specified file %file could not be copied, because a file by that name already exists in the destination.', array('%file' => $destination)), 'error');
526
527
528
529
530
531
        return FALSE;
    }
  }
  return $destination;
}

Dries's avatar
   
Dries committed
532
/**
533
534
535
536
537
538
539
540
541
542
543
544
545
 * Move a file to a new location and update the file's database entry.
 *
 * Moving a file is performed by copying the file to the new location and then
 * deleting the original.
 * - Checks if $source and $destination are valid and readable/writable.
 * - Performs a file move if $source is not equal to $destination.
 * - If file already exists in $destination either the call will error out,
 *   replace the file or rename the file based on the $replace parameter.
 * - Adds the new file to the files database.
 *
 * @param $source
 *   A file object.
 * @param $destination
546
547
548
 *   A string containing the destination that $source should be moved to. This
 *   can be a complete file path, a directory path or, if this value is omitted,
 *   Drupal's 'files' directory will be used.
549
550
 * @param $replace
 *   Replace behavior when the destination file already exists:
551
552
553
554
555
 *   - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
 *       the destination name exists then its database entry will be updated and
 *       file_delete() called on the source file after hook_file_move is called.
 *       If no database entry is found then the source files record will be
 *       updated.
556
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
557
 *       unique.
558
559
560
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
 * @return
 *   Resulting file object for success, or FALSE in the event of an error.
561
 *
562
563
564
565
566
567
568
 * @see file_unmanaged_move()
 * @see hook_file_move()
 */
function file_move($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  $source = (object)$source;

  if ($filepath = file_unmanaged_move($source->filepath, $destination, $replace)) {
569
570
    $delete_source = FALSE;

571
572
    $file = clone $source;
    $file->filepath = $filepath;
573
574
575
576
577
578
579
580
581
582
583
584
585
    // If we are replacing an existing file re-use its database record.
    if ($replace == FILE_EXISTS_REPLACE) {
      $existing_files = file_load_multiple(array(), array('filepath' => $filepath));
      if (count($existing_files)) {
        $existing = reset($existing_files);
        $delete_source = TRUE;
        $file->fid = $existing->fid;
      }
    }
    // If we are renaming around an existing file (rather than a directory),
    // use its basename for the filename.
    else if ($replace == FILE_EXISTS_RENAME && is_file(file_create_path($destination))) {
      $file->filename = basename($destination);
586
    }
587
588
589
590
591
592
593
594
595
596
597
598

    $file = file_save($file);

    // Inform modules that the file has been moved.
    module_invoke_all('file_move', $file, $source);

    if ($delete_source) {
      // Try a soft delete to remove original if it's not in use elsewhere.
      file_delete($source);
    }

    return $file;
599
600
601
602
603
604
605
  }
  return FALSE;
}

/**
 * Move a file to a new location without calling any hooks or making any
 * changes to the database.
Dries's avatar
   
Dries committed
606
 *
607
608
609
 * @param $source
 *   A string specifying the file location of the original file.
 * @param $destination
610
611
612
 *   A string containing the destination that $source should be moved to. This
 *   can be a complete file path, a directory name or, if this value is omitted,
 *   Drupal's 'files' directory will be used.
613
614
615
616
 * @param $replace
 *   Replace behavior when the destination file already exists:
 *   - FILE_EXISTS_REPLACE - Replace the existing file.
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
617
 *       unique.
618
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
619
620
 * @return
 *   The filepath of the moved file, or FALSE in the event of an error.
621
 *
622
 * @see file_move()
Dries's avatar
   
Dries committed
623
 */
624
625
626
function file_unmanaged_move($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  $filepath = file_unmanaged_copy($source, $destination, $replace);
  if ($filepath == FALSE || file_unmanaged_delete($source) == FALSE) {
627
    return FALSE;
Dries's avatar
   
Dries committed
628
  }
629
  return $filepath;
Dries's avatar
   
Dries committed
630
631
}

632
/**
633
634
635
636
637
638
639
640
641
642
643
644
 * Munge the filename as needed for security purposes.
 *
 * For instance the file name "exploit.php.pps" would become "exploit.php_.pps".
 *
 * @param $filename
 *   The name of a file to modify.
 * @param $extensions
 *   A space separated list of extensions that should not be altered.
 * @param $alerts
 *   Whether alerts (watchdog, drupal_set_message()) should be displayed.
 * @return
 *   $filename The potentially modified $filename.
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
 */
function file_munge_filename($filename, $extensions, $alerts = TRUE) {
  $original = $filename;

  // Allow potentially insecure uploads for very savvy users and admin
  if (!variable_get('allow_insecure_uploads', 0)) {
    $whitelist = array_unique(explode(' ', trim($extensions)));

    // Split the filename up by periods. The first part becomes the basename
    // the last part the final extension.
    $filename_parts = explode('.', $filename);
    $new_filename = array_shift($filename_parts); // Remove file basename.
    $final_extension = array_pop($filename_parts); // Remove final extension.

    // Loop through the middle parts of the name and add an underscore to the
    // end of each section that could be a file extension but isn't in the list
    // of allowed extensions.
    foreach ($filename_parts as $filename_part) {
663
      $new_filename .= '.' . $filename_part;
664
665
666
667
      if (!in_array($filename_part, $whitelist) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $filename_part)) {
        $new_filename .= '_';
      }
    }
668
    $filename = $new_filename . '.' . $final_extension;
669
670
671
672
673
674
675
676
677
678
679
680

    if ($alerts && $original != $filename) {
      drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $filename)));
    }
  }

  return $filename;
}

/**
 * Undo the effect of upload_munge_filename().
 *
681
682
683
684
 * @param $filename
 *   String with the filename to be unmunged.
 * @return
 *   An unmunged filename string.
685
686
687
688
689
 */
function file_unmunge_filename($filename) {
  return str_replace('_.', '.', $filename);
}

690
/**
691
692
693
694
 * Create a full file path from a directory and filename.
 *
 * If a file with the specified name already exists, an alternative will be
 * used.
695
 *
696
697
698
699
 * @param $basename
 *   String filename
 * @param $directory
 *   String directory
700
 * @return
701
702
 *   File path consisting of $directory and a unique filename based off
 *   of $basename.
703
 */
Dries's avatar
   
Dries committed
704
function file_create_filename($basename, $directory) {
705
  $destination = $directory . '/' . $basename;
Dries's avatar
   
Dries committed
706

707
  if (file_exists($destination)) {
Dries's avatar
   
Dries committed
708
    // Destination file already exists, generate an alternative.
709
710
    $pos = strrpos($basename, '.');
    if ($pos !== FALSE) {
Dries's avatar
   
Dries committed
711
712
713
714
715
      $name = substr($basename, 0, $pos);
      $ext = substr($basename, $pos);
    }
    else {
      $name = $basename;
716
      $ext = '';
Dries's avatar
   
Dries committed
717
718
719
720
    }

    $counter = 0;
    do {
721
722
      $destination = $directory . '/' . $name . '_' . $counter++ . $ext;
    } while (file_exists($destination));
Dries's avatar
   
Dries committed
723
724
  }

725
  return $destination;
Dries's avatar
   
Dries committed
726
727
}

728
/**
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
 * Delete a file and its database record.
 *
 * If the $force parameter is not TRUE hook_file_references() will be called
 * to determine if the file is being used by any modules. If the file is being
 * used is the delete will be canceled.
 *
 * @param $file
 *   A file object.
 * @param $force
 *   Boolean indicating that the file should be deleted even if
 *   hook_file_references() reports that the file is in use.
 * @return mixed
 *   TRUE for success, FALSE in the event of an error, or an array if the file
 *   is being used by another module. The array keys are the module's name and
 *   the values are the number of references.
744
 *
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
 * @see file_unmanaged_delete()
 * @see hook_file_references()
 * @see hook_file_delete()
 */
function file_delete($file, $force = FALSE) {
  $file = (object)$file;

  // If any module returns a value from the reference hook, the file will not
  // be deleted from Drupal, but file_delete will return a populated array that
  // tests as TRUE.
  if (!$force && ($references = module_invoke_all('file_references', $file))) {
    return $references;
  }

  // Let other modules clean up any references to the deleted file.
  module_invoke_all('file_delete', $file);

  // Make sure the file is deleted before removing its row from the
  // database, so UIs can still find the file in the database.
  if (file_unmanaged_delete($file->filepath)) {
    db_delete('files')->condition('fid', $file->fid)->execute();
    return TRUE;
  }
  return FALSE;
}

/**
 * Delete a file without calling any hooks or making any changes to the
 * database.
 *
 * This function should be used when the file to be deleted does not have an
 * entry recorded in the files table.
777
 *
778
779
780
781
782
 * @param $path
 *   A string containing a file path.
 * @return
 *   TRUE for success or path does not exist, or FALSE in the event of an
 *   error.
783
 *
784
 * @see file_delete()
785
 * @see file_unmanaged_delete_recursive()
786
 */
787
function file_unmanaged_delete($path) {
788
  if (is_dir($path)) {
789
    watchdog('file', '%path is a directory and cannot be removed using file_unmanaged_delete().', array('%path' => $path), WATCHDOG_ERROR);
790
791
    return FALSE;
  }
792
  if (is_file($path)) {
Dries's avatar
   
Dries committed
793
    return unlink($path);
794
  }
795
  // Return TRUE for non-existent file, but log that nothing was actually
796
797
  // deleted, as the current state is the indended result.
  if (!file_exists($path)) {
798
    watchdog('file', 'The file %path was not deleted, because it does not exist.', array('%path' => $path), WATCHDOG_NOTICE);
799
800
    return TRUE;
  }
801
802
803
  // We cannot handle anything other than files and directories. Log an error
  // for everything else (sockets, symbolic links, etc).
  watchdog('file', 'The file %path is not of a recognized type so it was not deleted.', array('%path' => $path), WATCHDOG_ERROR);
804
  return FALSE;
Dries's avatar
   
Dries committed
805
806
}

807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
/**
 * Recursively delete all files and directories in the specified filepath.
 *
 * If the specified path is a directory then the function will call itself
 * recursively to process the contents. Once the contents have been removed the
 * directory will also be removed.
 *
 * If the specified path is a file then it will be passed to
 * file_unmanaged_delete().
 *
 * Note that this only deletes visible files with write permission.
 *
 * @param $path
 *   A string containing a file or directory path.
 * @return
 *   TRUE for success or path does not exist, or FALSE in the event of an
 *   error.
 *
 * @see file_unmanaged_delete()
 */
function file_unmanaged_delete_recursive($path) {
  if (is_dir($path)) {
    $dir = dir($path);
    while (($entry = $dir->read()) !== FALSE) {
      if ($entry == '.' || $entry == '..') {
        continue;
      }
      $entry_path = $path . '/' . $entry;
      file_unmanaged_delete_recursive($entry_path);
    }
    return rmdir($path);
  }
  return file_unmanaged_delete($path);
}

842
/**
843
 * Determine total disk space used by a single user or the whole filesystem.
844
 *
845
 * @param $uid
846
847
848
849
850
851
852
 *   Optional. A user id, specifying NULL returns the total space used by all
 *   non-temporary files.
 * @param $status
 *   Optional. File Status to return. Combine with a bitwise OR(|) to return
 *   multiple statuses. The default status is FILE_STATUS_PERMANENT.
 * @return
 *   An integer containing the number of bytes used.
853
 */
854
function file_space_used($uid = NULL, $status = FILE_STATUS_PERMANENT) {
855
856
857
858
859
  $query = db_select('files', 'f');
  // Use separate placeholders for the status to avoid a bug in some versions
  // of PHP. @see http://drupal.org/node/352956
  $query->where('f.status & :status1 = :status2', array(':status1' => $status, ':status2' => $status));
  $query->addExpression('SUM(f.filesize)', 'filesize');
860
  if (!is_null($uid)) {
861
    $query->condition('f.uid', $uid);
862
  }
863
  return $query->execute()->fetchField();
864
865
}

Dries's avatar
   
Dries committed
866
/**
867
 * Saves a file upload to a new location.
Dries's avatar
   
Dries committed
868
 *
869
 * The file will be added to the files table as a temporary file. Temporary
870
871
 * files are periodically cleaned. To make the file a permanent file call
 * assign the status and use file_save() to save it.
872
873
874
875
876
 *
 * @param $source
 *   A string specifying the name of the upload field to save.
 * @param $validators
 *   An optional, associative array of callback functions used to validate the
877
 *   file. See @file_validate for a full discussion of the array format.
878
 * @param $destination
879
880
 *   A string containing the directory $source should be copied to. If this is
 *   not provided or is not writable, the temporary directory will be used.
881
882
883
884
885
 * @param $replace
 *   A boolean indicating whether an existing file of the same name in the
 *   destination directory should overwritten. A false value will generate a
 *   new, unique filename in the destination directory.
 * @return
886
887
 *   An object containing the file information if the upload succeeded, FALSE
 *   in the event of an error, or NULL if no file was uploaded.
Dries's avatar
   
Dries committed
888
 */
889
function file_save_upload($source, $validators = array(), $destination = FALSE, $replace = FILE_EXISTS_RENAME) {
890
891
892
893
894
895
896
897
898
  global $user;
  static $upload_cache;

  // Return cached objects without processing since the file will have
  // already been processed and the paths in _FILES will be invalid.
  if (isset($upload_cache[$source])) {
    return $upload_cache[$source];
  }

899
  // Make sure there's an upload to process.
900
901
  if (empty($_FILES['files']['name'][$source])) {
    return NULL;
902
  }
903

904
905
906
907
908
909
  // Check for file upload errors and return FALSE if a lower level system
  // error occurred. For a complete list of errors:
  // @see http://php.net/manual/en/features.file-upload.errors.php
  switch ($_FILES['files']['error'][$source]) {
    case UPLOAD_ERR_INI_SIZE:
    case UPLOAD_ERR_FORM_SIZE:
910
      drupal_set_message(t('The file %file could not be saved, because it exceeds %maxsize, the maximum allowed size for uploads.', array('%file' => $_FILES['files']['name'][$source], '%maxsize' => format_size(file_upload_max_size()))), 'error');
911
      return FALSE;
912

913
914
    case UPLOAD_ERR_PARTIAL:
    case UPLOAD_ERR_NO_FILE:
915
      drupal_set_message(t('The file %file could not be saved, because the upload did not complete.', array('%file' => $_FILES['files']['name'][$source])), 'error');
916
      return FALSE;
917

918
919
920
921
922
923
    case UPLOAD_ERR_OK:
      // Final check that this is a valid upload, if it isn't, use the
      // default error handler.
      if (is_uploaded_file($_FILES['files']['tmp_name'][$source])) {
         break;
      }
924

925
926
    // Unknown error
    default:
927
      drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', array('%file' => $_FILES['files']['name'][$source])), 'error');
928
929
      return FALSE;
  }
930

931
932
933
934
935
936
937
  // Build the list of non-munged extensions.
  // @todo: this should not be here. we need to figure out the right place.
  $extensions = '';
  foreach ($user->roles as $rid => $name) {
    $extensions .= ' ' . variable_get("upload_extensions_$rid",
    variable_get('upload_extensions_default', 'jpg jpeg gif png txt html doc xls pdf ppt pps odt ods odp'));
  }
938

939
940
941
942
943
944
945
946
  // Begin building file object.
  $file = new stdClass();
  $file->uid      = $user->uid;
  $file->status   = 0;
  $file->filename = file_munge_filename(trim(basename($_FILES['files']['name'][$source]), '.'), $extensions);
  $file->filepath = $_FILES['files']['tmp_name'][$source];
  $file->filemime = file_get_mimetype($file->filename);
  $file->filesize = $_FILES['files']['size'][$source];
947

948
949
950
951
952
953
  // Rename potentially executable files, to help prevent exploits.
  if (preg_match('/\.(php|pl|py|cgi|asp|js)$/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
    $file->filemime = 'text/plain';
    $file->filepath .= '.txt';
    $file->filename .= '.txt';
  }
954

955
956
957
958
959
  // If the destination is not provided, or is not writable, then use the
  // temporary directory.
  if (empty($destination) || file_check_path($destination) === FALSE) {
    $destination = file_directory_temp();
  }
960

961
962
  $file->source = $source;
  $file->destination = file_destination(file_create_path($destination . '/' . $file->filename), $replace);
963
964
965
966
967
  // If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and
  // there's an existing file so we need to bail.
  if ($file->destination === FALSE) {
    return FALSE;
  }
968

969
970
  // Add in our check of the the file name length.
  $validators['file_validate_name_length'] = array();
Dries's avatar
   
Dries committed
971

972
973
  // Call the validation functions specified by this function's caller.
  $errors = file_validate($file, $validators);
974

975
976
977
978
979
  // Check for errors.
  if (!empty($errors)) {
    $message = t('The specified file %name could not be uploaded.', array('%name' => $file->filename));
    if (count($errors) > 1) {
      $message .= theme('item_list', $errors);
980
    }
981
982
    else {
      $message .= ' ' . array_pop($errors);
983
    }
984
985
986
987
988
989
990
991
992
993
994
995
996
997
    form_set_error($source, $message);
    return FALSE;
  }

  // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary
  // directory. This overcomes open_basedir restrictions for future file
  // operations.
  $file->filepath = $file->destination;
  if (!move_uploaded_file($_FILES['files']['tmp_name'][$source], $file->filepath)) {
    form_set_error($source, t('File upload error. Could not move uploaded file.'));
    watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->filepath));
    return FALSE;
  }

998
999
1000
1001
1002
1003
1004
1005
1006
  // If we are replacing an existing file re-use its database record.
  if ($replace == FILE_EXISTS_REPLACE) {
    $existing_files = file_load_multiple(array(), array('filepath' => $file->filepath));
    if (count($existing_files)) {
      $existing = reset($existing_files);
      $file->fid = $existing->fid;
    }
  }

1007
1008
1009
1010
1011
  // If we made it this far it's safe to record this file in the database.
  if ($file = file_save($file)) {
    // Add file to the cache.
    $upload_cache[$source] = $file;
    return $file;
Dries's avatar
   
Dries committed
1012
  }
1013
  return FALSE;
Dries's avatar
   
Dries committed
1014
1015
}

1016
1017
1018
1019

/**
 * Check that a file meets the criteria specified by the validators.
 *
1020
1021
1022
 * After executing the validator callbacks specified hook_file_validate() will
 * also be called to allow other modules to report errors about the file.
 *
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
 * @param $file
 *   A Drupal file object.
 * @param $validators
 *   An optional, associative array of callback functions used to validate the
 *   file. The keys are function names and the values arrays of callback
 *   parameters which will be passed in after the user and file objects. The
 *   functions should return an array of error messages, an empty array
 *   indicates that the file passed validation. The functions will be called in
 *   the order specified.
 * @return
 *   An array contaning validation error messages.
1034
 *
1035
 * @see hook_file_validate()
1036
1037
1038
1039
1040
1041
1042
1043
1044
 */
function file_validate(&$file, $validators = array()) {
  // Call the validation functions specified by this function's caller.
  $errors = array();
  foreach ($validators as $function => $args) {
    array_unshift($args, $file);
    $errors = array_merge($errors, call_user_func_array($function, $args));
  }

1045
1046
  // Let other modules perform validation on the new file.
  return array_merge($errors, module_invoke_all('file_validate', $file));
1047
1048
}

1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
/**
 * Check for files with names longer than we can store in the database.
 *
 * @param $file
 *   A Drupal file object.
 * @return
 *   An array. If the file name is too long, it will contain an error message.
 */
function file_validate_name_length($file) {
  $errors = array();

1060
1061
1062
  if (empty($file->filename)) {
    $errors[] = t("The file's name is empty. Please give a name to the file.");
  }
1063
  if (strlen($file->filename) > 255) {
1064
    $errors[] = t("The file's name exceeds the 255 characters limit. Please rename the file and try again.");
1065
1066
1067
1068
1069
  }
  return $errors;
}

/**
1070
 * Check that the filename ends with an allowed extension.
1071
1072
1073
1074
 *
 * @param $file
 *   A Drupal file object.
 * @param $extensions
1075
 *   A string with a space separated list of allowed extensions.
1076
 * @return
1077
1078
 *   An array. If the file extension is not allowed, it will contain an error
 *   message.
1079
1080
 *
 * @see hook_file_validate()
1081
1082
1083
1084
1085
1086
 */
function file_validate_extensions($file, $extensions) {
  global $user;

  $errors = array();

1087
1088
1089
  $regex = '/\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
  if (!preg_match($regex, $file->filename)) {
    $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions));
1090
1091
1092
1093
1094
  }
  return $errors;
}

/**
1095
1096
1097
 * Check that the file's size is below certain limits.
 *
 * This check is not enforced for the user #1.
1098
1099
1100
1101
1102
1103
 *
 * @param $file
 *   A Drupal file object.
 * @param $file_limit
 *   An integer specifying the maximum file size in bytes. Zero indicates that
 *   no limit should be enforced.
1104
 * @param $user_limit
1105
1106
 *   An integer specifying the maximum number of bytes the user is allowed.
 *   Zero indicates that no limit should be enforced.
1107
 * @return
1108
1109
 *   An array. If the file size exceeds limits, it will contain an error
 *   message.
1110
1111
 *
 * @see hook_file_validate()
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
 */
function file_validate_size($file, $file_limit = 0, $user_limit = 0) {
  global $user;

  $errors = array();

  // Bypass validation for uid  = 1.
  if ($user->uid != 1) {
    if ($file_limit && $file->filesize > $file_limit) {
      $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($file_limit)));
    }

1124
    if ($user_limit && (file_space_used($user->uid) + $file->filesize) > $user_limit) {
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
      $errors[] = t('The file is %filesize which would exceed your disk quota of %quota.', array('%filesize' => format_size($file->filesize), '%quota' => format_size($user_limit)));
    }
  }
  return $errors;
}

/**
 * Check that the file is recognized by image_get_info() as an image.
 *
 * @param $file
 *   A Drupal file object.
 * @return
 *   An array. If the file is not an image, it will contain an error message.
1138
1139
 *
 * @see hook_file_validate()
1140
 */
1141
function file_validate_is_image($file) {
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
  $errors = array();

  $info = image_get_info($file->filepath);
  if (!$info || empty($info['extension'])) {
    $errors[] = t('Only JPEG, PNG and GIF images are allowed.');
  }

  return $errors;
}

/**
 * If the file is an image verify that its dimensions are within the specified
1154
1155
1156
1157
 * maximum and minimum dimensions.
 *
 * Non-image files will be ignored. If a image toolkit is available the image
 * will be scalled to fit within the desired maximum dimensions.
1158
1159
 *
 * @param $file
1160
1161
 *   A Drupal file object. This function may resize the file affecting its
 *   size.
1162
1163
1164
1165
1166
1167
 * @param $maximum_dimensions
 *   An optional string in the form WIDTHxHEIGHT e.g. '640x480' or '85x85'. If
 *   an image toolkit is installed the image will be resized down to these
 *   dimensions. A value of 0 indicates no restriction on size, so resizing
 *   will be attempted.
 * @param $minimum_dimensions
1168
1169
 *   An optional string in the form WIDTHxHEIGHT. This will check that the
 *   image meets a minimum size. A value of 0 indicates no restriction.
1170
1171
1172
 * @return
 *   An array. If the file is an image and did not meet the requirements, it
 *   will contain an error message.
1173
1174
 *
 * @see hook_file_validate()
1175
 */
1176
function file_validate_image_resolution($file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
  $errors = array();

  // Check first that the file is an image.
  if ($info = image_get_info($file->filepath)) {
    if ($maximum_dimensions) {
      // Check that it is smaller than the given dimensions.
      list($width, $height) = explode('x', $maximum_dimensions);
      if ($info['width'] > $width || $info['height'] > $height) {
        // Try to resize the image to fit the dimensions.
        if (image_get_toolkit() && image_scale($file->filepath, $file->filepath, $width, $height)) {
          drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));

          // Clear the cached filesize and refresh the image information.
          clearstatcache();
          $info = image_get_info($file->filepath);
          $file->filesize = $info['file_size'];
        }
        else {
          $errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions));
        }
      }
    }

    if ($minimum_dimensions) {
      // Check that it is larger than the given dimensions.
      list($width, $height) = explode('x', $minimum_dimensions);
1203
      if ($info['width'] < $width || $info['height'] < $height) {
1204
1205
1206
1207
1208
1209
1210
1211
        $errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', array('%dimensions' => $minimum_dimensions));
      }
    }
  }

  return $errors;
}

1212
/**
1213
 * Save a string to the specified destination and create a database file entry.
1214
 *
1215
1216
1217
1218
1219
1220
1221
1222
 * @param $data
 *   A string containing the contents of the file.
 * @param $destination
 *   A string containing the destination location. If no value is provided
 *   then a randomly name will be generated and the file saved in Drupal's
 *   files directory.
 * @param $replace
 *   Replace behavior when the destination file already exists:
1223
1224
1225
 *   - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
 *       the destination name exists then its database entry will be updated. If
 *       no database entry is found then a new one will be created.
1226
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
1227
 *       unique.
1228
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
1229
 * @return
1230
 *   A file object, or FALSE on error.
1231
 *