Projet

Général

Profil

Paste
Télécharger (88,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / file.inc @ 2196f227

1
<?php
2

    
3
/**
4
 * @file
5
 * API for handling file uploads and server file management.
6
 */
7

    
8
/**
9
 * Manually include stream wrapper code.
10
 *
11
 * Stream wrapper code is included here because there are cases where
12
 * File API is needed before a bootstrap, or in an alternate order (e.g.
13
 * maintenance theme).
14
 */
15
require_once DRUPAL_ROOT . '/includes/stream_wrappers.inc';
16

    
17
/**
18
 * @defgroup file File interface
19
 * @{
20
 * Common file handling functions.
21
 *
22
 * Fields on the file object:
23
 * - fid: File ID
24
 * - uid: The {users}.uid of the user who is associated with the file.
25
 * - filename: Name of the file with no path components. This may differ from
26
 *   the basename of the filepath if the file is renamed to avoid overwriting
27
 *   an existing file.
28
 * - uri: URI of the file.
29
 * - filemime: The file's MIME type.
30
 * - filesize: The size of the file in bytes.
31
 * - status: A bitmapped field indicating the status of the file. The first 8
32
 *   bits are reserved for Drupal core. The least significant bit indicates
33
 *   temporary (0) or permanent (1). Temporary files older than
34
 *   DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed during cron runs.
35
 * - timestamp: UNIX timestamp for the date the file was added to the database.
36
 */
37

    
38
/**
39
 * Flag used by file_prepare_directory() -- create directory if not present.
40
 */
41
define('FILE_CREATE_DIRECTORY', 1);
42

    
43
/**
44
 * Flag used by file_prepare_directory() -- file permissions may be changed.
45
 */
46
define('FILE_MODIFY_PERMISSIONS', 2);
47

    
48
/**
49
 * Flag for dealing with existing files: Appends number until name is unique.
50
 */
51
define('FILE_EXISTS_RENAME', 0);
52

    
53
/**
54
 * Flag for dealing with existing files: Replace the existing file.
55
 */
56
define('FILE_EXISTS_REPLACE', 1);
57

    
58
/**
59
 * Flag for dealing with existing files: Do nothing and return FALSE.
60
 */
61
define('FILE_EXISTS_ERROR', 2);
62

    
63
/**
64
 * Indicates that the file is permanent and should not be deleted.
65
 *
66
 * Temporary files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed
67
 * during cron runs, but permanent files will not be removed during the file
68
 * garbage collection process.
69
 */
70
define('FILE_STATUS_PERMANENT', 1);
71

    
72
/**
73
 * Provides Drupal stream wrapper registry.
74
 *
75
 * A stream wrapper is an abstraction of a file system that allows Drupal to
76
 * use the same set of methods to access both local files and remote resources.
77
 *
78
 * Provide a facility for managing and querying user-defined stream wrappers
79
 * in PHP. PHP's internal stream_get_wrappers() doesn't return the class
80
 * registered to handle a stream, which we need to be able to find the handler
81
 * for class instantiation.
82
 *
83
 * If a module registers a scheme that is already registered with PHP, the
84
 * existing scheme will be unregistered and replaced with the specified class.
85
 *
86
 * A stream is referenced as "scheme://target".
87
 *
88
 * The optional $filter parameter can be used to retrieve only the stream
89
 * wrappers that are appropriate for particular usage. For example, this returns
90
 * only stream wrappers that use local file storage:
91
 * @code
92
 *   $local_stream_wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL);
93
 * @endcode
94
 *
95
 * The $filter parameter can only filter to types containing a particular flag.
96
 * In some cases, you may want to filter to types that do not contain a
97
 * particular flag. For example, you may want to retrieve all stream wrappers
98
 * that are not writable, or all stream wrappers that are not local. PHP's
99
 * array_diff_key() function can be used to help with this. For example, this
100
 * returns only stream wrappers that do not use local file storage:
101
 * @code
102
 *   $remote_stream_wrappers = array_diff_key(file_get_stream_wrappers(STREAM_WRAPPERS_ALL), file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL));
103
 * @endcode
104
 *
105
 * @param $filter
106
 *   (Optional) Filters out all types except those with an on bit for each on
107
 *   bit in $filter. For example, if $filter is STREAM_WRAPPERS_WRITE_VISIBLE,
108
 *   which is equal to (STREAM_WRAPPERS_READ | STREAM_WRAPPERS_WRITE |
109
 *   STREAM_WRAPPERS_VISIBLE), then only stream wrappers with all three of these
110
 *   bits set are returned. Defaults to STREAM_WRAPPERS_ALL, which returns all
111
 *   registered stream wrappers.
112
 *
113
 * @return
114
 *   An array keyed by scheme, with values containing an array of information
115
 *   about the stream wrapper, as returned by hook_stream_wrappers(). If $filter
116
 *   is omitted or set to STREAM_WRAPPERS_ALL, the entire Drupal stream wrapper
117
 *   registry is returned. Otherwise only the stream wrappers whose 'type'
118
 *   bitmask has an on bit for each bit specified in $filter are returned.
119
 *
120
 * @see hook_stream_wrappers()
121
 * @see hook_stream_wrappers_alter()
122
 */
123
function file_get_stream_wrappers($filter = STREAM_WRAPPERS_ALL) {
124
  $wrappers_storage = &drupal_static(__FUNCTION__);
125

    
126
  if (!isset($wrappers_storage)) {
127
    $wrappers = module_invoke_all('stream_wrappers');
128
    foreach ($wrappers as $scheme => $info) {
129
      // Add defaults.
130
      $wrappers[$scheme] += array('type' => STREAM_WRAPPERS_NORMAL);
131
    }
132
    drupal_alter('stream_wrappers', $wrappers);
133
    $existing = stream_get_wrappers();
134
    foreach ($wrappers as $scheme => $info) {
135
      // We only register classes that implement our interface.
136
      if (in_array('DrupalStreamWrapperInterface', class_implements($info['class']), TRUE)) {
137
        // Record whether we are overriding an existing scheme.
138
        if (in_array($scheme, $existing, TRUE)) {
139
          $wrappers[$scheme]['override'] = TRUE;
140
          stream_wrapper_unregister($scheme);
141
        }
142
        else {
143
          $wrappers[$scheme]['override'] = FALSE;
144
        }
145
        if (($info['type'] & STREAM_WRAPPERS_LOCAL) == STREAM_WRAPPERS_LOCAL) {
146
          stream_wrapper_register($scheme, $info['class']);
147
        }
148
        else {
149
          stream_wrapper_register($scheme, $info['class'], STREAM_IS_URL);
150
        }
151
      }
152
      // Pre-populate the static cache with the filters most typically used.
153
      $wrappers_storage[STREAM_WRAPPERS_ALL][$scheme] = $wrappers[$scheme];
154
      if (($info['type'] & STREAM_WRAPPERS_WRITE_VISIBLE) == STREAM_WRAPPERS_WRITE_VISIBLE) {
155
        $wrappers_storage[STREAM_WRAPPERS_WRITE_VISIBLE][$scheme] = $wrappers[$scheme];
156
      }
157
    }
158
  }
159

    
160
  if (!isset($wrappers_storage[$filter])) {
161
    $wrappers_storage[$filter] = array();
162
    foreach ($wrappers_storage[STREAM_WRAPPERS_ALL] as $scheme => $info) {
163
      // Bit-wise filter.
164
      if (($info['type'] & $filter) == $filter) {
165
        $wrappers_storage[$filter][$scheme] = $info;
166
      }
167
    }
168
  }
169

    
170
  return $wrappers_storage[$filter];
171
}
172

    
173
/**
174
 * Returns the stream wrapper class name for a given scheme.
175
 *
176
 * @param $scheme
177
 *   Stream scheme.
178
 *
179
 * @return
180
 *   Return string if a scheme has a registered handler, or FALSE.
181
 */
182
function file_stream_wrapper_get_class($scheme) {
183
  $wrappers = file_get_stream_wrappers();
184
  return empty($wrappers[$scheme]) ? FALSE : $wrappers[$scheme]['class'];
185
}
186

    
187
/**
188
 * Returns the scheme of a URI (e.g. a stream).
189
 *
190
 * @param $uri
191
 *   A stream, referenced as "scheme://target".
192
 *
193
 * @return
194
 *   A string containing the name of the scheme, or FALSE if none. For example,
195
 *   the URI "public://example.txt" would return "public".
196
 *
197
 * @see file_uri_target()
198
 */
199
function file_uri_scheme($uri) {
200
  $position = strpos($uri, '://');
201
  return $position ? substr($uri, 0, $position) : FALSE;
202
}
203

    
204
/**
205
 * Checks that the scheme of a stream URI is valid.
206
 *
207
 * Confirms that there is a registered stream handler for the provided scheme
208
 * and that it is callable. This is useful if you want to confirm a valid
209
 * scheme without creating a new instance of the registered handler.
210
 *
211
 * @param $scheme
212
 *   A URI scheme, a stream is referenced as "scheme://target".
213
 *
214
 * @return
215
 *   Returns TRUE if the string is the name of a validated stream,
216
 *   or FALSE if the scheme does not have a registered handler.
217
 */
218
function file_stream_wrapper_valid_scheme($scheme) {
219
  // Does the scheme have a registered handler that is callable?
220
  $class = file_stream_wrapper_get_class($scheme);
221
  if (class_exists($class)) {
222
    return TRUE;
223
  }
224
  else {
225
    return FALSE;
226
  }
227
}
228

    
229

    
230
/**
231
 * Returns the part of a URI after the schema.
232
 *
233
 * @param $uri
234
 *   A stream, referenced as "scheme://target".
235
 *
236
 * @return
237
 *   A string containing the target (path), or FALSE if none.
238
 *   For example, the URI "public://sample/test.txt" would return
239
 *   "sample/test.txt".
240
 *
241
 * @see file_uri_scheme()
242
 */
243
function file_uri_target($uri) {
244
  $data = explode('://', $uri, 2);
245

    
246
  // Remove erroneous leading or trailing, forward-slashes and backslashes.
247
  return count($data) == 2 ? trim($data[1], '\/') : FALSE;
248
}
249

    
250
/**
251
 * Gets the default file stream implementation.
252
 *
253
 * @return
254
 *   'public', 'private' or any other file scheme defined as the default.
255
 */
256
function file_default_scheme() {
257
  return variable_get('file_default_scheme', 'public');
258
}
259

    
260
/**
261
 * Normalizes a URI by making it syntactically correct.
262
 *
263
 * A stream is referenced as "scheme://target".
264
 *
265
 * The following actions are taken:
266
 * - Remove trailing slashes from target
267
 * - Trim erroneous leading slashes from target. e.g. ":///" becomes "://".
268
 *
269
 * @param $uri
270
 *   String reference containing the URI to normalize.
271
 *
272
 * @return
273
 *   The normalized URI.
274
 */
275
function file_stream_wrapper_uri_normalize($uri) {
276
  // Inline file_uri_scheme() function call for performance reasons.
277
  $position = strpos($uri, '://');
278
  $scheme = $position ? substr($uri, 0, $position) : FALSE;
279

    
280
  if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
281
    $target = file_uri_target($uri);
282

    
283
    if ($target !== FALSE) {
284
      $uri = $scheme . '://' . $target;
285
    }
286
  }
287
  return $uri;
288
}
289

    
290
/**
291
 * Returns a reference to the stream wrapper class responsible for a given URI.
292
 *
293
 * The scheme determines the stream wrapper class that should be
294
 * used by consulting the stream wrapper registry.
295
 *
296
 * @param $uri
297
 *   A stream, referenced as "scheme://target".
298
 *
299
 * @return
300
 *   Returns a new stream wrapper object appropriate for the given URI or FALSE
301
 *   if no registered handler could be found. For example, a URI of
302
 *   "private://example.txt" would return a new private stream wrapper object
303
 *   (DrupalPrivateStreamWrapper).
304
 */
305
function file_stream_wrapper_get_instance_by_uri($uri) {
306
  $scheme = file_uri_scheme($uri);
307
  $class = file_stream_wrapper_get_class($scheme);
308
  if (class_exists($class)) {
309
    $instance = new $class();
310
    $instance->setUri($uri);
311
    return $instance;
312
  }
313
  else {
314
    return FALSE;
315
  }
316
}
317

    
318
/**
319
 * Returns a reference to the stream wrapper class responsible for a scheme.
320
 *
321
 * This helper method returns a stream instance using a scheme. That is, the
322
 * passed string does not contain a "://". For example, "public" is a scheme
323
 * but "public://" is a URI (stream). This is because the later contains both
324
 * a scheme and target despite target being empty.
325
 *
326
 * Note: the instance URI will be initialized to "scheme://" so that you can
327
 * make the customary method calls as if you had retrieved an instance by URI.
328
 *
329
 * @param $scheme
330
 *   If the stream was "public://target", "public" would be the scheme.
331
 *
332
 * @return
333
 *   Returns a new stream wrapper object appropriate for the given $scheme.
334
 *   For example, for the public scheme a stream wrapper object
335
 *   (DrupalPublicStreamWrapper).
336
 *   FALSE is returned if no registered handler could be found.
337
 */
338
function file_stream_wrapper_get_instance_by_scheme($scheme) {
339
  $class = file_stream_wrapper_get_class($scheme);
340
  if (class_exists($class)) {
341
    $instance = new $class();
342
    $instance->setUri($scheme . '://');
343
    return $instance;
344
  }
345
  else {
346
    return FALSE;
347
  }
348
}
349

    
350
/**
351
 * Creates a web-accessible URL for a stream to an external or local file.
352
 *
353
 * Compatibility: normal paths and stream wrappers.
354
 *
355
 * There are two kinds of local files:
356
 * - "managed files", i.e. those stored by a Drupal-compatible stream wrapper.
357
 *   These are files that have either been uploaded by users or were generated
358
 *   automatically (for example through CSS aggregation).
359
 * - "shipped files", i.e. those outside of the files directory, which ship as
360
 *   part of Drupal core or contributed modules or themes.
361
 *
362
 * @param $uri
363
 *   The URI to a file for which we need an external URL, or the path to a
364
 *   shipped file.
365
 *
366
 * @return
367
 *   A string containing a URL that may be used to access the file.
368
 *   If the provided string already contains a preceding 'http', 'https', or
369
 *   '/', nothing is done and the same string is returned. If a stream wrapper
370
 *   could not be found to generate an external URL, then FALSE is returned.
371
 *
372
 * @see http://drupal.org/node/515192
373
 */
374
function file_create_url($uri) {
375
  // Allow the URI to be altered, e.g. to serve a file from a CDN or static
376
  // file server.
377
  drupal_alter('file_url', $uri);
378

    
379
  $scheme = file_uri_scheme($uri);
380

    
381
  if (!$scheme) {
382
    // Allow for:
383
    // - root-relative URIs (e.g. /foo.jpg in http://example.com/foo.jpg)
384
    // - protocol-relative URIs (e.g. //bar.jpg, which is expanded to
385
    //   http://example.com/bar.jpg by the browser when viewing a page over
386
    //   HTTP and to https://example.com/bar.jpg when viewing a HTTPS page)
387
    // Both types of relative URIs are characterized by a leading slash, hence
388
    // we can use a single check.
389
    if (drupal_substr($uri, 0, 1) == '/') {
390
      return $uri;
391
    }
392
    else {
393
      // If this is not a properly formatted stream, then it is a shipped file.
394
      // Therefore, return the urlencoded URI with the base URL prepended.
395
      return $GLOBALS['base_url'] . '/' . drupal_encode_path($uri);
396
    }
397
  }
398
  elseif ($scheme == 'http' || $scheme == 'https') {
399
    // Check for HTTP so that we don't have to implement getExternalUrl() for
400
    // the HTTP wrapper.
401
    return $uri;
402
  }
403
  else {
404
    // Attempt to return an external URL using the appropriate wrapper.
405
    if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
406
      return $wrapper->getExternalUrl();
407
    }
408
    else {
409
      return FALSE;
410
    }
411
  }
412
}
413

    
414
/**
415
 * Checks that the directory exists and is writable.
416
 *
417
 * Directories need to have execute permissions to be considered a directory by
418
 * FTP servers, etc.
419
 *
420
 * @param $directory
421
 *   A string reference containing the name of a directory path or URI. A
422
 *   trailing slash will be trimmed from a path.
423
 * @param $options
424
 *   A bitmask to indicate if the directory should be created if it does
425
 *   not exist (FILE_CREATE_DIRECTORY) or made writable if it is read-only
426
 *   (FILE_MODIFY_PERMISSIONS).
427
 *
428
 * @return
429
 *   TRUE if the directory exists (or was created) and is writable. FALSE
430
 *   otherwise.
431
 */
432
function file_prepare_directory(&$directory, $options = FILE_MODIFY_PERMISSIONS) {
433
  if (!file_stream_wrapper_valid_scheme(file_uri_scheme($directory))) {
434
    // Only trim if we're not dealing with a stream.
435
    $directory = rtrim($directory, '/\\');
436
  }
437

    
438
  // Check if directory exists.
439
  if (!is_dir($directory)) {
440
    // Let mkdir() recursively create directories and use the default directory
441
    // permissions.
442
    if (($options & FILE_CREATE_DIRECTORY) && @drupal_mkdir($directory, NULL, TRUE)) {
443
      return drupal_chmod($directory);
444
    }
445
    return FALSE;
446
  }
447
  // The directory exists, so check to see if it is writable.
448
  $writable = is_writable($directory);
449
  if (!$writable && ($options & FILE_MODIFY_PERMISSIONS)) {
450
    return drupal_chmod($directory);
451
  }
452

    
453
  return $writable;
454
}
455

    
456
/**
457
 * Creates a .htaccess file in each Drupal files directory if it is missing.
458
 */
459
function file_ensure_htaccess() {
460
  file_create_htaccess('public://', FALSE);
461
  if (variable_get('file_private_path', FALSE)) {
462
    file_create_htaccess('private://', TRUE);
463
  }
464
  file_create_htaccess('temporary://', TRUE);
465
}
466

    
467
/**
468
 * Creates a .htaccess file in the given directory.
469
 *
470
 * @param $directory
471
 *   The directory.
472
 * @param $private
473
 *   FALSE indicates that $directory should be an open and public directory.
474
 *   The default is TRUE which indicates a private and protected directory.
475
 * @param $force_overwrite
476
 *   Set to TRUE to attempt to overwrite the existing .htaccess file if one is
477
 *   already present. Defaults to FALSE.
478
 */
479
function file_create_htaccess($directory, $private = TRUE, $force_overwrite = FALSE) {
480
  if (file_uri_scheme($directory)) {
481
    $directory = file_stream_wrapper_uri_normalize($directory);
482
  }
483
  else {
484
    $directory = rtrim($directory, '/\\');
485
  }
486
  $htaccess_path =  $directory . '/.htaccess';
487

    
488
  if (file_exists($htaccess_path) && !$force_overwrite) {
489
    // Short circuit if the .htaccess file already exists.
490
    return;
491
  }
492

    
493
  $htaccess_lines = file_htaccess_lines($private);
494

    
495
  // Write the .htaccess file.
496
  if (file_put_contents($htaccess_path, $htaccess_lines)) {
497
    drupal_chmod($htaccess_path, 0444);
498
  }
499
  else {
500
    $variables = array('%directory' => $directory, '!htaccess' => '<br />' . nl2br(check_plain($htaccess_lines)));
501
    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);
502
  }
503
}
504

    
505
/**
506
 * Returns the standard .htaccess lines that Drupal writes to file directories.
507
 *
508
 * @param $private
509
 *   (Optional) Set to FALSE to return the .htaccess lines for an open and
510
 *   public directory. The default is TRUE, which returns the .htaccess lines
511
 *   for a private and protected directory.
512
 *
513
 * @return
514
 *   A string representing the desired contents of the .htaccess file.
515
 *
516
 * @see file_create_htaccess()
517
 */
518
function file_htaccess_lines($private = TRUE) {
519
  $lines = <<<EOF
520
# Turn off all options we don't need.
521
Options None
522
Options +FollowSymLinks
523

    
524
# Set the catch-all handler to prevent scripts from being executed.
525
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
526
<Files *>
527
  # Override the handler again if we're run later in the evaluation list.
528
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
529
</Files>
530

    
531
# If we know how to do it safely, disable the PHP engine entirely.
532
<IfModule mod_php5.c>
533
  php_flag engine off
534
</IfModule>
535
EOF;
536

    
537
  if ($private) {
538
    $lines = "Deny from all\n\n" . $lines;
539
  }
540

    
541
  return $lines;
542
}
543

    
544
/**
545
 * Loads file objects from the database.
546
 *
547
 * @param $fids
548
 *   An array of file IDs.
549
 * @param $conditions
550
 *   (deprecated) An associative array of conditions on the {file_managed}
551
 *   table, where the keys are the database fields and the values are the
552
 *   values those fields must have. Instead, it is preferable to use
553
 *   EntityFieldQuery to retrieve a list of entity IDs loadable by
554
 *   this function.
555
 *
556
 * @return
557
 *   An array of file objects, indexed by fid.
558
 *
559
 * @todo Remove $conditions in Drupal 8.
560
 *
561
 * @see hook_file_load()
562
 * @see file_load()
563
 * @see entity_load()
564
 * @see EntityFieldQuery
565
 */
566
function file_load_multiple($fids = array(), $conditions = array()) {
567
  return entity_load('file', $fids, $conditions);
568
}
569

    
570
/**
571
 * Loads a single file object from the database.
572
 *
573
 * @param $fid
574
 *   A file ID.
575
 *
576
 * @return
577
 *   An object representing the file, or FALSE if the file was not found.
578
 *
579
 * @see hook_file_load()
580
 * @see file_load_multiple()
581
 */
582
function file_load($fid) {
583
  $files = file_load_multiple(array($fid), array());
584
  return reset($files);
585
}
586

    
587
/**
588
 * Saves a file object to the database.
589
 *
590
 * If the $file->fid is not set a new record will be added.
591
 *
592
 * @param $file
593
 *   A file object returned by file_load().
594
 *
595
 * @return
596
 *   The updated file object.
597
 *
598
 * @see hook_file_insert()
599
 * @see hook_file_update()
600
 */
601
function file_save(stdClass $file) {
602
  $file->timestamp = REQUEST_TIME;
603
  $file->filesize = filesize($file->uri);
604

    
605
  // Load the stored entity, if any.
606
  if (!empty($file->fid) && !isset($file->original)) {
607
    $file->original = entity_load_unchanged('file', $file->fid);
608
  }
609

    
610
  module_invoke_all('file_presave', $file);
611
  module_invoke_all('entity_presave', $file, 'file');
612

    
613
  if (empty($file->fid)) {
614
    drupal_write_record('file_managed', $file);
615
    // Inform modules about the newly added file.
616
    module_invoke_all('file_insert', $file);
617
    module_invoke_all('entity_insert', $file, 'file');
618
  }
619
  else {
620
    drupal_write_record('file_managed', $file, 'fid');
621
    // Inform modules that the file has been updated.
622
    module_invoke_all('file_update', $file);
623
    module_invoke_all('entity_update', $file, 'file');
624
  }
625

    
626
  // Clear internal properties.
627
  unset($file->original);
628
  // Clear the static loading cache.
629
  entity_get_controller('file')->resetCache(array($file->fid));
630

    
631
  return $file;
632
}
633

    
634
/**
635
 * Determines where a file is used.
636
 *
637
 * @param $file
638
 *   A file object.
639
 *
640
 * @return
641
 *   A nested array with usage data. The first level is keyed by module name,
642
 *   the second by object type and the third by the object id. The value
643
 *   of the third level contains the usage count.
644
 *
645
 * @see file_usage_add()
646
 * @see file_usage_delete()
647
 */
648
function file_usage_list(stdClass $file) {
649
  $result = db_select('file_usage', 'f')
650
    ->fields('f', array('module', 'type', 'id', 'count'))
651
    ->condition('fid', $file->fid)
652
    ->condition('count', 0, '>')
653
    ->execute();
654
  $references = array();
655
  foreach ($result as $usage) {
656
    $references[$usage->module][$usage->type][$usage->id] = $usage->count;
657
  }
658
  return $references;
659
}
660

    
661
/**
662
 * Records that a module is using a file.
663
 *
664
 * This usage information will be queried during file_delete() to ensure that
665
 * a file is not in use before it is physically removed from disk.
666
 *
667
 * Examples:
668
 * - A module that associates files with nodes, so $type would be
669
 *   'node' and $id would be the node's nid. Files for all revisions are stored
670
 *   within a single nid.
671
 * - The User module associates an image with a user, so $type would be 'user'
672
 *   and the $id would be the user's uid.
673
 *
674
 * @param $file
675
 *   A file object.
676
 * @param $module
677
 *   The name of the module using the file.
678
 * @param $type
679
 *   The type of the object that contains the referenced file.
680
 * @param $id
681
 *   The unique, numeric ID of the object containing the referenced file.
682
 * @param $count
683
 *   (optional) The number of references to add to the object. Defaults to 1.
684
 *
685
 * @see file_usage_list()
686
 * @see file_usage_delete()
687
 */
688
function file_usage_add(stdClass $file, $module, $type, $id, $count = 1) {
689
  db_merge('file_usage')
690
    ->key(array(
691
      'fid' => $file->fid,
692
      'module' => $module,
693
      'type' => $type,
694
      'id' => $id,
695
    ))
696
    ->fields(array('count' => $count))
697
    ->expression('count', 'count + :count', array(':count' => $count))
698
    ->execute();
699
}
700

    
701
/**
702
 * Removes a record to indicate that a module is no longer using a file.
703
 *
704
 * The file_delete() function is typically called after removing a file usage
705
 * to remove the record from the file_managed table and delete the file itself.
706
 *
707
 * @param $file
708
 *   A file object.
709
 * @param $module
710
 *   The name of the module using the file.
711
 * @param $type
712
 *   (optional) The type of the object that contains the referenced file. May
713
 *   be omitted if all module references to a file are being deleted.
714
 * @param $id
715
 *   (optional) The unique, numeric ID of the object containing the referenced
716
 *   file. May be omitted if all module references to a file are being deleted.
717
 * @param $count
718
 *   (optional) The number of references to delete from the object. Defaults to
719
 *   1. 0 may be specified to delete all references to the file within a
720
 *   specific object.
721
 *
722
 * @see file_usage_add()
723
 * @see file_usage_list()
724
 * @see file_delete()
725
 */
726
function file_usage_delete(stdClass $file, $module, $type = NULL, $id = NULL, $count = 1) {
727
  // Delete rows that have a exact or less value to prevent empty rows.
728
  $query = db_delete('file_usage')
729
    ->condition('module', $module)
730
    ->condition('fid', $file->fid);
731
  if ($type && $id) {
732
    $query
733
      ->condition('type', $type)
734
      ->condition('id', $id);
735
  }
736
  if ($count) {
737
    $query->condition('count', $count, '<=');
738
  }
739
  $result = $query->execute();
740

    
741
  // If the row has more than the specified count decrement it by that number.
742
  if (!$result && $count > 0) {
743
    $query = db_update('file_usage')
744
      ->condition('module', $module)
745
      ->condition('fid', $file->fid);
746
    if ($type && $id) {
747
      $query
748
        ->condition('type', $type)
749
        ->condition('id', $id);
750
    }
751
    $query->expression('count', 'count - :count', array(':count' => $count));
752
    $query->execute();
753
  }
754
}
755

    
756
/**
757
 * Copies a file to a new location and adds a file record to the database.
758
 *
759
 * This function should be used when manipulating files that have records
760
 * stored in the database. This is a powerful function that in many ways
761
 * performs like an advanced version of copy().
762
 * - Checks if $source and $destination are valid and readable/writable.
763
 * - If file already exists in $destination either the call will error out,
764
 *   replace the file or rename the file based on the $replace parameter.
765
 * - If the $source and $destination are equal, the behavior depends on the
766
 *   $replace parameter. FILE_EXISTS_REPLACE will error out. FILE_EXISTS_RENAME
767
 *   will rename the file until the $destination is unique.
768
 * - Adds the new file to the files database. If the source file is a
769
 *   temporary file, the resulting file will also be a temporary file. See
770
 *   file_save_upload() for details on temporary files.
771
 *
772
 * @param $source
773
 *   A file object.
774
 * @param $destination
775
 *   A string containing the destination that $source should be copied to.
776
 *   This must be a stream wrapper URI.
777
 * @param $replace
778
 *   Replace behavior when the destination file already exists:
779
 *   - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
780
 *       the destination name exists then its database entry will be updated. If
781
 *       no database entry is found then a new one will be created.
782
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
783
 *       unique.
784
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
785
 *
786
 * @return
787
 *   File object if the copy is successful, or FALSE in the event of an error.
788
 *
789
 * @see file_unmanaged_copy()
790
 * @see hook_file_copy()
791
 */
792
function file_copy(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
793
  if (!file_valid_uri($destination)) {
794
    if (($realpath = drupal_realpath($source->uri)) !== FALSE) {
795
      watchdog('file', 'File %file (%realpath) could not be copied, because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', array('%file' => $source->uri, '%realpath' => $realpath, '%destination' => $destination));
796
    }
797
    else {
798
      watchdog('file', 'File %file could not be copied, because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', array('%file' => $source->uri, '%destination' => $destination));
799
    }
800
    drupal_set_message(t('The specified file %file could not be copied, because the destination is invalid. More information is available in the system log.', array('%file' => $source->uri)), 'error');
801
    return FALSE;
802
  }
803

    
804
  if ($uri = file_unmanaged_copy($source->uri, $destination, $replace)) {
805
    $file = clone $source;
806
    $file->fid = NULL;
807
    $file->uri = $uri;
808
    $file->filename = drupal_basename($uri);
809
    // If we are replacing an existing file re-use its database record.
810
    if ($replace == FILE_EXISTS_REPLACE) {
811
      $existing_files = file_load_multiple(array(), array('uri' => $uri));
812
      if (count($existing_files)) {
813
        $existing = reset($existing_files);
814
        $file->fid = $existing->fid;
815
        $file->filename = $existing->filename;
816
      }
817
    }
818
    // If we are renaming around an existing file (rather than a directory),
819
    // use its basename for the filename.
820
    elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
821
      $file->filename = drupal_basename($destination);
822
    }
823

    
824
    $file = file_save($file);
825

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

    
829
    return $file;
830
  }
831
  return FALSE;
832
}
833

    
834
/**
835
 * Determines whether the URI has a valid scheme for file API operations.
836
 *
837
 * There must be a scheme and it must be a Drupal-provided scheme like
838
 * 'public', 'private', 'temporary', or an extension provided with
839
 * hook_stream_wrappers().
840
 *
841
 * @param $uri
842
 *   The URI to be tested.
843
 *
844
 * @return
845
 *   TRUE if the URI is allowed.
846
 */
847
function file_valid_uri($uri) {
848
  // Assert that the URI has an allowed scheme. Barepaths are not allowed.
849
  $uri_scheme = file_uri_scheme($uri);
850
  if (empty($uri_scheme) || !file_stream_wrapper_valid_scheme($uri_scheme)) {
851
    return FALSE;
852
  }
853
  return TRUE;
854
}
855

    
856
/**
857
 * Copies a file to a new location without invoking the file API.
858
 *
859
 * This is a powerful function that in many ways performs like an advanced
860
 * version of copy().
861
 * - Checks if $source and $destination are valid and readable/writable.
862
 * - If file already exists in $destination either the call will error out,
863
 *   replace the file or rename the file based on the $replace parameter.
864
 * - If the $source and $destination are equal, the behavior depends on the
865
 *   $replace parameter. FILE_EXISTS_REPLACE will error out. FILE_EXISTS_RENAME
866
 *   will rename the file until the $destination is unique.
867
 * - Provides a fallback using realpaths if the move fails using stream
868
 *   wrappers. This can occur because PHP's copy() function does not properly
869
 *   support streams if safe_mode or open_basedir are enabled. See
870
 *   https://bugs.php.net/bug.php?id=60456
871
 *
872
 * @param $source
873
 *   A string specifying the filepath or URI of the source file.
874
 * @param $destination
875
 *   A URI containing the destination that $source should be copied to. The
876
 *   URI may be a bare filepath (without a scheme). If this value is omitted,
877
 *   Drupal's default files scheme will be used, usually "public://".
878
 * @param $replace
879
 *   Replace behavior when the destination file already exists:
880
 *   - FILE_EXISTS_REPLACE - Replace the existing file.
881
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
882
 *       unique.
883
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
884
 *
885
 * @return
886
 *   The path to the new file, or FALSE in the event of an error.
887
 *
888
 * @see file_copy()
889
 */
890
function file_unmanaged_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
891
  $original_source = $source;
892
  $original_destination = $destination;
893

    
894
  // Assert that the source file actually exists.
895
  if (!file_exists($source)) {
896
    // @todo Replace drupal_set_message() calls with exceptions instead.
897
    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' => $original_source)), 'error');
898
    if (($realpath = drupal_realpath($original_source)) !== FALSE) {
899
      watchdog('file', 'File %file (%realpath) could not be copied because it does not exist.', array('%file' => $original_source, '%realpath' => $realpath));
900
    }
901
    else {
902
      watchdog('file', 'File %file could not be copied because it does not exist.', array('%file' => $original_source));
903
    }
904
    return FALSE;
905
  }
906

    
907
  // Build a destination URI if necessary.
908
  if (!isset($destination)) {
909
    $destination = file_build_uri(drupal_basename($source));
910
  }
911

    
912

    
913
  // Prepare the destination directory.
914
  if (file_prepare_directory($destination)) {
915
    // The destination is already a directory, so append the source basename.
916
    $destination = file_stream_wrapper_uri_normalize($destination . '/' . drupal_basename($source));
917
  }
918
  else {
919
    // Perhaps $destination is a dir/file?
920
    $dirname = drupal_dirname($destination);
921
    if (!file_prepare_directory($dirname)) {
922
      // The destination is not valid.
923
      watchdog('file', 'File %file could not be copied, because the destination directory %destination is not configured correctly.', array('%file' => $original_source, '%destination' => $dirname));
924
      drupal_set_message(t('The specified file %file could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.', array('%file' => $original_source)), 'error');
925
      return FALSE;
926
    }
927
  }
928

    
929
  // Determine whether we can perform this operation based on overwrite rules.
930
  $destination = file_destination($destination, $replace);
931
  if ($destination === FALSE) {
932
    drupal_set_message(t('The file %file could not be copied because a file by that name already exists in the destination directory.', array('%file' => $original_source)), 'error');
933
    watchdog('file', 'File %file could not be copied because a file by that name already exists in the destination directory (%directory)', array('%file' => $original_source, '%directory' => $destination));
934
    return FALSE;
935
  }
936

    
937
  // Assert that the source and destination filenames are not the same.
938
  $real_source = drupal_realpath($source);
939
  $real_destination = drupal_realpath($destination);
940
  if ($source == $destination || ($real_source !== FALSE) && ($real_source == $real_destination)) {
941
    drupal_set_message(t('The specified file %file was not copied because it would overwrite itself.', array('%file' => $source)), 'error');
942
    watchdog('file', 'File %file could not be copied because it would overwrite itself.', array('%file' => $source));
943
    return FALSE;
944
  }
945
  // Make sure the .htaccess files are present.
946
  file_ensure_htaccess();
947
  // Perform the copy operation.
948
  if (!@copy($source, $destination)) {
949
    // If the copy failed and realpaths exist, retry the operation using them
950
    // instead.
951
    if ($real_source === FALSE || $real_destination === FALSE || !@copy($real_source, $real_destination)) {
952
      watchdog('file', 'The specified file %file could not be copied to %destination.', array('%file' => $source, '%destination' => $destination), WATCHDOG_ERROR);
953
      return FALSE;
954
    }
955
  }
956

    
957
  // Set the permissions on the new file.
958
  drupal_chmod($destination);
959

    
960
  return $destination;
961
}
962

    
963
/**
964
 * Constructs a URI to Drupal's default files location given a relative path.
965
 */
966
function file_build_uri($path) {
967
  $uri = file_default_scheme() . '://' . $path;
968
  return file_stream_wrapper_uri_normalize($uri);
969
}
970

    
971
/**
972
 * Determines the destination path for a file.
973
 *
974
 * @param $destination
975
 *   A string specifying the desired final URI or filepath.
976
 * @param $replace
977
 *   Replace behavior when the destination file already exists.
978
 *   - FILE_EXISTS_REPLACE - Replace the existing file.
979
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
980
 *       unique.
981
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
982
 *
983
 * @return
984
 *   The destination filepath, or FALSE if the file already exists
985
 *   and FILE_EXISTS_ERROR is specified.
986
 */
987
function file_destination($destination, $replace) {
988
  if (file_exists($destination)) {
989
    switch ($replace) {
990
      case FILE_EXISTS_REPLACE:
991
        // Do nothing here, we want to overwrite the existing file.
992
        break;
993

    
994
      case FILE_EXISTS_RENAME:
995
        $basename = drupal_basename($destination);
996
        $directory = drupal_dirname($destination);
997
        $destination = file_create_filename($basename, $directory);
998
        break;
999

    
1000
      case FILE_EXISTS_ERROR:
1001
        // Error reporting handled by calling function.
1002
        return FALSE;
1003
    }
1004
  }
1005
  return $destination;
1006
}
1007

    
1008
/**
1009
 * Moves a file to a new location and update the file's database entry.
1010
 *
1011
 * Moving a file is performed by copying the file to the new location and then
1012
 * deleting the original.
1013
 * - Checks if $source and $destination are valid and readable/writable.
1014
 * - Performs a file move if $source is not equal to $destination.
1015
 * - If file already exists in $destination either the call will error out,
1016
 *   replace the file or rename the file based on the $replace parameter.
1017
 * - Adds the new file to the files database.
1018
 *
1019
 * @param $source
1020
 *   A file object.
1021
 * @param $destination
1022
 *   A string containing the destination that $source should be moved to.
1023
 *   This must be a stream wrapper URI.
1024
 * @param $replace
1025
 *   Replace behavior when the destination file already exists:
1026
 *   - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
1027
 *       the destination name exists then its database entry will be updated and
1028
 *       file_delete() called on the source file after hook_file_move is called.
1029
 *       If no database entry is found then the source files record will be
1030
 *       updated.
1031
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
1032
 *       unique.
1033
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
1034
 *
1035
 * @return
1036
 *   Resulting file object for success, or FALSE in the event of an error.
1037
 *
1038
 * @see file_unmanaged_move()
1039
 * @see hook_file_move()
1040
 */
1041
function file_move(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
1042
  if (!file_valid_uri($destination)) {
1043
    if (($realpath = drupal_realpath($source->uri)) !== FALSE) {
1044
      watchdog('file', 'File %file (%realpath) could not be moved, because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', array('%file' => $source->uri, '%realpath' => $realpath, '%destination' => $destination));
1045
    }
1046
    else {
1047
      watchdog('file', 'File %file could not be moved, because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', array('%file' => $source->uri, '%destination' => $destination));
1048
    }
1049
    drupal_set_message(t('The specified file %file could not be moved, because the destination is invalid. More information is available in the system log.', array('%file' => $source->uri)), 'error');
1050
    return FALSE;
1051
  }
1052

    
1053
  if ($uri = file_unmanaged_move($source->uri, $destination, $replace)) {
1054
    $delete_source = FALSE;
1055

    
1056
    $file = clone $source;
1057
    $file->uri = $uri;
1058
    // If we are replacing an existing file re-use its database record.
1059
    if ($replace == FILE_EXISTS_REPLACE) {
1060
      $existing_files = file_load_multiple(array(), array('uri' => $uri));
1061
      if (count($existing_files)) {
1062
        $existing = reset($existing_files);
1063
        $delete_source = TRUE;
1064
        $file->fid = $existing->fid;
1065
      }
1066
    }
1067
    // If we are renaming around an existing file (rather than a directory),
1068
    // use its basename for the filename.
1069
    elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
1070
      $file->filename = drupal_basename($destination);
1071
    }
1072

    
1073
    $file = file_save($file);
1074

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

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

    
1083
    return $file;
1084
  }
1085
  return FALSE;
1086
}
1087

    
1088
/**
1089
 * Moves a file to a new location without database changes or hook invocation.
1090
 *
1091
 * @param $source
1092
 *   A string specifying the filepath or URI of the original file.
1093
 * @param $destination
1094
 *   A string containing the destination that $source should be moved to.
1095
 *   This must be a stream wrapper URI. If this value is omitted, Drupal's
1096
 *   default files scheme will be used, usually "public://".
1097
 * @param $replace
1098
 *   Replace behavior when the destination file already exists:
1099
 *   - FILE_EXISTS_REPLACE - Replace the existing file.
1100
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
1101
 *       unique.
1102
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
1103
 *
1104
 * @return
1105
 *   The URI of the moved file, or FALSE in the event of an error.
1106
 *
1107
 * @see file_move()
1108
 */
1109
function file_unmanaged_move($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
1110
  $filepath = file_unmanaged_copy($source, $destination, $replace);
1111
  if ($filepath == FALSE || file_unmanaged_delete($source) == FALSE) {
1112
    return FALSE;
1113
  }
1114
  return $filepath;
1115
}
1116

    
1117
/**
1118
 * Modifies a filename as needed for security purposes.
1119
 *
1120
 * Munging a file name prevents unknown file extensions from masking exploit
1121
 * files. When web servers such as Apache decide how to process a URL request,
1122
 * they use the file extension. If the extension is not recognized, Apache
1123
 * skips that extension and uses the previous file extension. For example, if
1124
 * the file being requested is exploit.php.pps, and Apache does not recognize
1125
 * the '.pps' extension, it treats the file as PHP and executes it. To make
1126
 * this file name safe for Apache and prevent it from executing as PHP, the
1127
 * .php extension is "munged" into .php_, making the safe file name
1128
 * exploit.php_.pps.
1129
 *
1130
 * Specifically, this function adds an underscore to all extensions that are
1131
 * between 2 and 5 characters in length, internal to the file name, and not
1132
 * included in $extensions.
1133
 *
1134
 * Function behavior is also controlled by the Drupal variable
1135
 * 'allow_insecure_uploads'. If 'allow_insecure_uploads' evaluates to TRUE, no
1136
 * alterations will be made, if it evaluates to FALSE, the filename is 'munged'.
1137
 *
1138
 * @param $filename
1139
 *   File name to modify.
1140
 * @param $extensions
1141
 *   A space-separated list of extensions that should not be altered.
1142
 * @param $alerts
1143
 *   If TRUE, drupal_set_message() will be called to display a message if the
1144
 *   file name was changed.
1145
 *
1146
 * @return
1147
 *   The potentially modified $filename.
1148
 */
1149
function file_munge_filename($filename, $extensions, $alerts = TRUE) {
1150
  $original = $filename;
1151

    
1152
  // Allow potentially insecure uploads for very savvy users and admin
1153
  if (!variable_get('allow_insecure_uploads', 0)) {
1154
    // Remove any null bytes. See http://php.net/manual/security.filesystem.nullbytes.php
1155
    $filename = str_replace(chr(0), '', $filename);
1156

    
1157
    $whitelist = array_unique(explode(' ', strtolower(trim($extensions))));
1158

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

    
1165
    // Loop through the middle parts of the name and add an underscore to the
1166
    // end of each section that could be a file extension but isn't in the list
1167
    // of allowed extensions.
1168
    foreach ($filename_parts as $filename_part) {
1169
      $new_filename .= '.' . $filename_part;
1170
      if (!in_array(strtolower($filename_part), $whitelist) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $filename_part)) {
1171
        $new_filename .= '_';
1172
      }
1173
    }
1174
    $filename = $new_filename . '.' . $final_extension;
1175

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

    
1181
  return $filename;
1182
}
1183

    
1184
/**
1185
 * Undoes the effect of file_munge_filename().
1186
 *
1187
 * @param $filename
1188
 *   String with the filename to be unmunged.
1189
 *
1190
 * @return
1191
 *   An unmunged filename string.
1192
 */
1193
function file_unmunge_filename($filename) {
1194
  return str_replace('_.', '.', $filename);
1195
}
1196

    
1197
/**
1198
 * Creates a full file path from a directory and filename.
1199
 *
1200
 * If a file with the specified name already exists, an alternative will be
1201
 * used.
1202
 *
1203
 * @param $basename
1204
 *   String filename
1205
 * @param $directory
1206
 *   String containing the directory or parent URI.
1207
 *
1208
 * @return
1209
 *   File path consisting of $directory and a unique filename based off
1210
 *   of $basename.
1211
 */
1212
function file_create_filename($basename, $directory) {
1213
  // Strip control characters (ASCII value < 32). Though these are allowed in
1214
  // some filesystems, not many applications handle them well.
1215
  $basename = preg_replace('/[\x00-\x1F]/u', '_', $basename);
1216
  if (substr(PHP_OS, 0, 3) == 'WIN') {
1217
    // These characters are not allowed in Windows filenames
1218
    $basename = str_replace(array(':', '*', '?', '"', '<', '>', '|'), '_', $basename);
1219
  }
1220

    
1221
  // A URI or path may already have a trailing slash or look like "public://".
1222
  if (substr($directory, -1) == '/') {
1223
    $separator = '';
1224
  }
1225
  else {
1226
    $separator = '/';
1227
  }
1228

    
1229
  $destination = $directory . $separator . $basename;
1230

    
1231
  if (file_exists($destination)) {
1232
    // Destination file already exists, generate an alternative.
1233
    $pos = strrpos($basename, '.');
1234
    if ($pos !== FALSE) {
1235
      $name = substr($basename, 0, $pos);
1236
      $ext = substr($basename, $pos);
1237
    }
1238
    else {
1239
      $name = $basename;
1240
      $ext = '';
1241
    }
1242

    
1243
    $counter = 0;
1244
    do {
1245
      $destination = $directory . $separator . $name . '_' . $counter++ . $ext;
1246
    } while (file_exists($destination));
1247
  }
1248

    
1249
  return $destination;
1250
}
1251

    
1252
/**
1253
 * Deletes a file and its database record.
1254
 *
1255
 * If the $force parameter is not TRUE, file_usage_list() will be called to
1256
 * determine if the file is being used by any modules. If the file is being
1257
 * used the delete will be canceled.
1258
 *
1259
 * @param $file
1260
 *   A file object.
1261
 * @param $force
1262
 *   Boolean indicating that the file should be deleted even if the file is
1263
 *   reported as in use by the file_usage table.
1264
 *
1265
 * @return mixed
1266
 *   TRUE for success, FALSE in the event of an error, or an array if the file
1267
 *   is being used by any modules.
1268
 *
1269
 * @see file_unmanaged_delete()
1270
 * @see file_usage_list()
1271
 * @see file_usage_delete()
1272
 * @see hook_file_delete()
1273
 */
1274
function file_delete(stdClass $file, $force = FALSE) {
1275
  if (!file_valid_uri($file->uri)) {
1276
    if (($realpath = drupal_realpath($file->uri)) !== FALSE) {
1277
      watchdog('file', 'File %file (%realpath) could not be deleted because it is not a valid URI. This may be caused by improper use of file_delete() or a missing stream wrapper.', array('%file' => $file->uri, '%realpath' => $realpath));
1278
    }
1279
    else {
1280
      watchdog('file', 'File %file could not be deleted because it is not a valid URI. This may be caused by improper use of file_delete() or a missing stream wrapper.', array('%file' => $file->uri));
1281
    }
1282
    drupal_set_message(t('The specified file %file could not be deleted, because it is not a valid URI. More information is available in the system log.', array('%file' => $file->uri)), 'error');
1283
    return FALSE;
1284
  }
1285

    
1286
  // If any module still has a usage entry in the file_usage table, the file
1287
  // will not be deleted, but file_delete() will return a populated array
1288
  // that tests as TRUE.
1289
  if (!$force && ($references = file_usage_list($file))) {
1290
    return $references;
1291
  }
1292

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

    
1297
  // Make sure the file is deleted before removing its row from the
1298
  // database, so UIs can still find the file in the database.
1299
  if (file_unmanaged_delete($file->uri)) {
1300
    db_delete('file_managed')->condition('fid', $file->fid)->execute();
1301
    db_delete('file_usage')->condition('fid', $file->fid)->execute();
1302
    entity_get_controller('file')->resetCache();
1303
    return TRUE;
1304
  }
1305
  return FALSE;
1306
}
1307

    
1308
/**
1309
 * Deletes a file without database changes or hook invocations.
1310
 *
1311
 * This function should be used when the file to be deleted does not have an
1312
 * entry recorded in the files table.
1313
 *
1314
 * @param $path
1315
 *   A string containing a file path or (streamwrapper) URI.
1316
 *
1317
 * @return
1318
 *   TRUE for success or path does not exist, or FALSE in the event of an
1319
 *   error.
1320
 *
1321
 * @see file_delete()
1322
 * @see file_unmanaged_delete_recursive()
1323
 */
1324
function file_unmanaged_delete($path) {
1325
  if (is_dir($path)) {
1326
    watchdog('file', '%path is a directory and cannot be removed using file_unmanaged_delete().', array('%path' => $path), WATCHDOG_ERROR);
1327
    return FALSE;
1328
  }
1329
  if (is_file($path)) {
1330
    return drupal_unlink($path);
1331
  }
1332
  // Return TRUE for non-existent file, but log that nothing was actually
1333
  // deleted, as the current state is the intended result.
1334
  if (!file_exists($path)) {
1335
    watchdog('file', 'The file %path was not deleted, because it does not exist.', array('%path' => $path), WATCHDOG_NOTICE);
1336
    return TRUE;
1337
  }
1338
  // We cannot handle anything other than files and directories. Log an error
1339
  // for everything else (sockets, symbolic links, etc).
1340
  watchdog('file', 'The file %path is not of a recognized type so it was not deleted.', array('%path' => $path), WATCHDOG_ERROR);
1341
  return FALSE;
1342
}
1343

    
1344
/**
1345
 * Deletes all files and directories in the specified filepath recursively.
1346
 *
1347
 * If the specified path is a directory then the function will call itself
1348
 * recursively to process the contents. Once the contents have been removed the
1349
 * directory will also be removed.
1350
 *
1351
 * If the specified path is a file then it will be passed to
1352
 * file_unmanaged_delete().
1353
 *
1354
 * Note that this only deletes visible files with write permission.
1355
 *
1356
 * @param $path
1357
 *   A string containing either an URI or a file or directory path.
1358
 *
1359
 * @return
1360
 *   TRUE for success or if path does not exist, FALSE in the event of an
1361
 *   error.
1362
 *
1363
 * @see file_unmanaged_delete()
1364
 */
1365
function file_unmanaged_delete_recursive($path) {
1366
  if (is_dir($path)) {
1367
    $dir = dir($path);
1368
    while (($entry = $dir->read()) !== FALSE) {
1369
      if ($entry == '.' || $entry == '..') {
1370
        continue;
1371
      }
1372
      $entry_path = $path . '/' . $entry;
1373
      file_unmanaged_delete_recursive($entry_path);
1374
    }
1375
    $dir->close();
1376

    
1377
    return drupal_rmdir($path);
1378
  }
1379
  return file_unmanaged_delete($path);
1380
}
1381

    
1382
/**
1383
 * Determines total disk space used by a single user or the whole filesystem.
1384
 *
1385
 * @param $uid
1386
 *   Optional. A user id, specifying NULL returns the total space used by all
1387
 *   non-temporary files.
1388
 * @param $status
1389
 *   Optional. The file status to consider. The default is to only
1390
 *   consider files in status FILE_STATUS_PERMANENT.
1391
 *
1392
 * @return
1393
 *   An integer containing the number of bytes used.
1394
 */
1395
function file_space_used($uid = NULL, $status = FILE_STATUS_PERMANENT) {
1396
  $query = db_select('file_managed', 'f');
1397
  $query->condition('f.status', $status);
1398
  $query->addExpression('SUM(f.filesize)', 'filesize');
1399
  if (isset($uid)) {
1400
    $query->condition('f.uid', $uid);
1401
  }
1402
  return $query->execute()->fetchField();
1403
}
1404

    
1405
/**
1406
 * Saves a file upload to a new location.
1407
 *
1408
 * The file will be added to the {file_managed} table as a temporary file.
1409
 * Temporary files are periodically cleaned. To make the file a permanent file,
1410
 * assign the status and use file_save() to save the changes.
1411
 *
1412
 * @param $form_field_name
1413
 *   A string that is the associative array key of the upload form element in
1414
 *   the form array.
1415
 * @param $validators
1416
 *   An optional, associative array of callback functions used to validate the
1417
 *   file. See file_validate() for a full discussion of the array format.
1418
 *   If no extension validator is provided it will default to a limited safe
1419
 *   list of extensions which is as follows: "jpg jpeg gif png txt
1420
 *   doc xls pdf ppt pps odt ods odp". To allow all extensions you must
1421
 *   explicitly set the 'file_validate_extensions' validator to an empty array
1422
 *   (Beware: this is not safe and should only be allowed for trusted users, if
1423
 *   at all).
1424
 * @param $destination
1425
 *   A string containing the URI that the file should be copied to. This must
1426
 *   be a stream wrapper URI. If this value is omitted, Drupal's temporary
1427
 *   files scheme will be used ("temporary://").
1428
 * @param $replace
1429
 *   Replace behavior when the destination file already exists:
1430
 *   - FILE_EXISTS_REPLACE: Replace the existing file.
1431
 *   - FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is
1432
 *     unique.
1433
 *   - FILE_EXISTS_ERROR: Do nothing and return FALSE.
1434
 *
1435
 * @return
1436
 *   An object containing the file information if the upload succeeded, FALSE
1437
 *   in the event of an error, or NULL if no file was uploaded. The
1438
 *   documentation for the "File interface" group, which you can find under
1439
 *   Related topics, or the header at the top of this file, documents the
1440
 *   components of a file object. In addition to the standard components,
1441
 *   this function adds:
1442
 *   - source: Path to the file before it is moved.
1443
 *   - destination: Path to the file after it is moved (same as 'uri').
1444
 */
1445
function file_save_upload($form_field_name, $validators = array(), $destination = FALSE, $replace = FILE_EXISTS_RENAME) {
1446
  global $user;
1447
  static $upload_cache;
1448

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

    
1455
  // Make sure there's an upload to process.
1456
  if (empty($_FILES['files']['name'][$form_field_name])) {
1457
    return NULL;
1458
  }
1459

    
1460
  // Check for file upload errors and return FALSE if a lower level system
1461
  // error occurred. For a complete list of errors:
1462
  // See http://php.net/manual/features.file-upload.errors.php.
1463
  switch ($_FILES['files']['error'][$form_field_name]) {
1464
    case UPLOAD_ERR_INI_SIZE:
1465
    case UPLOAD_ERR_FORM_SIZE:
1466
      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'][$form_field_name], '%maxsize' => format_size(file_upload_max_size()))), 'error');
1467
      return FALSE;
1468

    
1469
    case UPLOAD_ERR_PARTIAL:
1470
    case UPLOAD_ERR_NO_FILE:
1471
      drupal_set_message(t('The file %file could not be saved, because the upload did not complete.', array('%file' => $_FILES['files']['name'][$form_field_name])), 'error');
1472
      return FALSE;
1473

    
1474
    case UPLOAD_ERR_OK:
1475
      // Final check that this is a valid upload, if it isn't, use the
1476
      // default error handler.
1477
      if (is_uploaded_file($_FILES['files']['tmp_name'][$form_field_name])) {
1478
        break;
1479
      }
1480

    
1481
    // Unknown error
1482
    default:
1483
      drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', array('%file' => $_FILES['files']['name'][$form_field_name])), 'error');
1484
      return FALSE;
1485
  }
1486

    
1487
  // Begin building file object.
1488
  $file = new stdClass();
1489
  $file->uid      = $user->uid;
1490
  $file->status   = 0;
1491
  $file->filename = trim(drupal_basename($_FILES['files']['name'][$form_field_name]), '.');
1492
  $file->uri      = $_FILES['files']['tmp_name'][$form_field_name];
1493
  $file->filemime = file_get_mimetype($file->filename);
1494
  $file->filesize = $_FILES['files']['size'][$form_field_name];
1495

    
1496
  $extensions = '';
1497
  if (isset($validators['file_validate_extensions'])) {
1498
    if (isset($validators['file_validate_extensions'][0])) {
1499
      // Build the list of non-munged extensions if the caller provided them.
1500
      $extensions = $validators['file_validate_extensions'][0];
1501
    }
1502
    else {
1503
      // If 'file_validate_extensions' is set and the list is empty then the
1504
      // caller wants to allow any extension. In this case we have to remove the
1505
      // validator or else it will reject all extensions.
1506
      unset($validators['file_validate_extensions']);
1507
    }
1508
  }
1509
  else {
1510
    // No validator was provided, so add one using the default list.
1511
    // Build a default non-munged safe list for file_munge_filename().
1512
    $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp';
1513
    $validators['file_validate_extensions'] = array();
1514
    $validators['file_validate_extensions'][0] = $extensions;
1515
  }
1516

    
1517
  if (!empty($extensions)) {
1518
    // Munge the filename to protect against possible malicious extension hiding
1519
    // within an unknown file type (ie: filename.html.foo).
1520
    $file->filename = file_munge_filename($file->filename, $extensions);
1521
  }
1522

    
1523
  // Rename potentially executable files, to help prevent exploits (i.e. will
1524
  // rename filename.php.foo and filename.php to filename.php.foo.txt and
1525
  // filename.php.txt, respectively). Don't rename if 'allow_insecure_uploads'
1526
  // evaluates to TRUE.
1527
  if (!variable_get('allow_insecure_uploads', 0) && preg_match('/\.(php|pl|py|cgi|asp|js)(\.|$)/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
1528
    $file->filemime = 'text/plain';
1529
    $file->uri .= '.txt';
1530
    $file->filename .= '.txt';
1531
    // The .txt extension may not be in the allowed list of extensions. We have
1532
    // to add it here or else the file upload will fail.
1533
    if (!empty($extensions)) {
1534
      $validators['file_validate_extensions'][0] .= ' txt';
1535
      drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $file->filename)));
1536
    }
1537
  }
1538

    
1539
  // If the destination is not provided, use the temporary directory.
1540
  if (empty($destination)) {
1541
    $destination = 'temporary://';
1542
  }
1543

    
1544
  // Assert that the destination contains a valid stream.
1545
  $destination_scheme = file_uri_scheme($destination);
1546
  if (!$destination_scheme || !file_stream_wrapper_valid_scheme($destination_scheme)) {
1547
    drupal_set_message(t('The file could not be uploaded, because the destination %destination is invalid.', array('%destination' => $destination)), 'error');
1548
    return FALSE;
1549
  }
1550

    
1551
  $file->source = $form_field_name;
1552
  // A URI may already have a trailing slash or look like "public://".
1553
  if (substr($destination, -1) != '/') {
1554
    $destination .= '/';
1555
  }
1556
  $file->destination = file_destination($destination . $file->filename, $replace);
1557
  // If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and
1558
  // there's an existing file so we need to bail.
1559
  if ($file->destination === FALSE) {
1560
    drupal_set_message(t('The file %source could not be uploaded because a file by that name already exists in the destination %directory.', array('%source' => $form_field_name, '%directory' => $destination)), 'error');
1561
    return FALSE;
1562
  }
1563

    
1564
  // Add in our check of the file name length.
1565
  $validators['file_validate_name_length'] = array();
1566

    
1567
  // Call the validation functions specified by this function's caller.
1568
  $errors = file_validate($file, $validators);
1569

    
1570
  // Check for errors.
1571
  if (!empty($errors)) {
1572
    $message = t('The specified file %name could not be uploaded.', array('%name' => $file->filename));
1573
    if (count($errors) > 1) {
1574
      $message .= theme('item_list', array('items' => $errors));
1575
    }
1576
    else {
1577
      $message .= ' ' . array_pop($errors);
1578
    }
1579
    form_set_error($form_field_name, $message);
1580
    return FALSE;
1581
  }
1582

    
1583
  // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary
1584
  // directory. This overcomes open_basedir restrictions for future file
1585
  // operations.
1586
  $file->uri = $file->destination;
1587
  if (!drupal_move_uploaded_file($_FILES['files']['tmp_name'][$form_field_name], $file->uri)) {
1588
    form_set_error($form_field_name, t('File upload error. Could not move uploaded file.'));
1589
    watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->uri));
1590
    return FALSE;
1591
  }
1592

    
1593
  // Set the permissions on the new file.
1594
  drupal_chmod($file->uri);
1595

    
1596
  // If we are replacing an existing file re-use its database record.
1597
  if ($replace == FILE_EXISTS_REPLACE) {
1598
    $existing_files = file_load_multiple(array(), array('uri' => $file->uri));
1599
    if (count($existing_files)) {
1600
      $existing = reset($existing_files);
1601
      $file->fid = $existing->fid;
1602
    }
1603
  }
1604

    
1605
  // If we made it this far it's safe to record this file in the database.
1606
  if ($file = file_save($file)) {
1607
    // Add file to the cache.
1608
    $upload_cache[$form_field_name] = $file;
1609
    return $file;
1610
  }
1611
  return FALSE;
1612
}
1613

    
1614
/**
1615
 * Moves an uploaded file to a new location.
1616
 *
1617
 * PHP's move_uploaded_file() does not properly support streams if safe_mode
1618
 * or open_basedir are enabled, so this function fills that gap.
1619
 *
1620
 * Compatibility: normal paths and stream wrappers.
1621
 *
1622
 * @param $filename
1623
 *   The filename of the uploaded file.
1624
 * @param $uri
1625
 *   A string containing the destination URI of the file.
1626
 *
1627
 * @return
1628
 *   TRUE on success, or FALSE on failure.
1629
 *
1630
 * @see move_uploaded_file()
1631
 * @see http://drupal.org/node/515192
1632
 * @ingroup php_wrappers
1633
 */
1634
function drupal_move_uploaded_file($filename, $uri) {
1635
  $result = @move_uploaded_file($filename, $uri);
1636
  // PHP's move_uploaded_file() does not properly support streams if safe_mode
1637
  // or open_basedir are enabled so if the move failed, try finding a real path
1638
  // and retry the move operation.
1639
  if (!$result) {
1640
    if ($realpath = drupal_realpath($uri)) {
1641
      $result = move_uploaded_file($filename, $realpath);
1642
    }
1643
    else {
1644
      $result = move_uploaded_file($filename, $uri);
1645
    }
1646
  }
1647

    
1648
  return $result;
1649
}
1650

    
1651
/**
1652
 * Checks that a file meets the criteria specified by the validators.
1653
 *
1654
 * After executing the validator callbacks specified hook_file_validate() will
1655
 * also be called to allow other modules to report errors about the file.
1656
 *
1657
 * @param $file
1658
 *   A Drupal file object.
1659
 * @param $validators
1660
 *   An optional, associative array of callback functions used to validate the
1661
 *   file. The keys are function names and the values arrays of callback
1662
 *   parameters which will be passed in after the file object. The
1663
 *   functions should return an array of error messages; an empty array
1664
 *   indicates that the file passed validation. The functions will be called in
1665
 *   the order specified.
1666
 *
1667
 * @return
1668
 *   An array containing validation error messages.
1669
 *
1670
 * @see hook_file_validate()
1671
 */
1672
function file_validate(stdClass &$file, $validators = array()) {
1673
  // Call the validation functions specified by this function's caller.
1674
  $errors = array();
1675
  foreach ($validators as $function => $args) {
1676
    if (function_exists($function)) {
1677
      array_unshift($args, $file);
1678
      $errors = array_merge($errors, call_user_func_array($function, $args));
1679
    }
1680
  }
1681

    
1682
  // Let other modules perform validation on the new file.
1683
  return array_merge($errors, module_invoke_all('file_validate', $file));
1684
}
1685

    
1686
/**
1687
 * Checks for files with names longer than we can store in the database.
1688
 *
1689
 * @param $file
1690
 *   A Drupal file object.
1691
 *
1692
 * @return
1693
 *   An array. If the file name is too long, it will contain an error message.
1694
 */
1695
function file_validate_name_length(stdClass $file) {
1696
  $errors = array();
1697

    
1698
  if (empty($file->filename)) {
1699
    $errors[] = t("The file's name is empty. Please give a name to the file.");
1700
  }
1701
  if (strlen($file->filename) > 240) {
1702
    $errors[] = t("The file's name exceeds the 240 characters limit. Please rename the file and try again.");
1703
  }
1704
  return $errors;
1705
}
1706

    
1707
/**
1708
 * Checks that the filename ends with an allowed extension.
1709
 *
1710
 * @param $file
1711
 *   A Drupal file object.
1712
 * @param $extensions
1713
 *   A string with a space separated list of allowed extensions.
1714
 *
1715
 * @return
1716
 *   An array. If the file extension is not allowed, it will contain an error
1717
 *   message.
1718
 *
1719
 * @see hook_file_validate()
1720
 */
1721
function file_validate_extensions(stdClass $file, $extensions) {
1722
  $errors = array();
1723

    
1724
  $regex = '/\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
1725
  if (!preg_match($regex, $file->filename)) {
1726
    $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions));
1727
  }
1728
  return $errors;
1729
}
1730

    
1731
/**
1732
 * Checks that the file's size is below certain limits.
1733
 *
1734
 * @param $file
1735
 *   A Drupal file object.
1736
 * @param $file_limit
1737
 *   An integer specifying the maximum file size in bytes. Zero indicates that
1738
 *   no limit should be enforced.
1739
 * @param $user_limit
1740
 *   An integer specifying the maximum number of bytes the user is allowed.
1741
 *   Zero indicates that no limit should be enforced.
1742
 *
1743
 * @return
1744
 *   An array. If the file size exceeds limits, it will contain an error
1745
 *   message.
1746
 *
1747
 * @see hook_file_validate()
1748
 */
1749
function file_validate_size(stdClass $file, $file_limit = 0, $user_limit = 0) {
1750
  global $user;
1751
  $errors = array();
1752

    
1753
  if ($file_limit && $file->filesize > $file_limit) {
1754
    $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($file_limit)));
1755
  }
1756

    
1757
  // Save a query by only calling file_space_used() when a limit is provided.
1758
  if ($user_limit && (file_space_used($user->uid) + $file->filesize) > $user_limit) {
1759
    $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)));
1760
  }
1761

    
1762
  return $errors;
1763
}
1764

    
1765
/**
1766
 * Checks that the file is recognized by image_get_info() as an image.
1767
 *
1768
 * @param $file
1769
 *   A Drupal file object.
1770
 *
1771
 * @return
1772
 *   An array. If the file is not an image, it will contain an error message.
1773
 *
1774
 * @see hook_file_validate()
1775
 */
1776
function file_validate_is_image(stdClass $file) {
1777
  $errors = array();
1778

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

    
1784
  return $errors;
1785
}
1786

    
1787
/**
1788
 * Verifies that image dimensions are within the specified maximum and minimum.
1789
 *
1790
 * Non-image files will be ignored. If an image toolkit is available the image
1791
 * will be scaled to fit within the desired maximum dimensions.
1792
 *
1793
 * @param $file
1794
 *   A Drupal file object. This function may resize the file affecting its
1795
 *   size.
1796
 * @param $maximum_dimensions
1797
 *   An optional string in the form WIDTHxHEIGHT e.g. '640x480' or '85x85'. If
1798
 *   an image toolkit is installed the image will be resized down to these
1799
 *   dimensions. A value of 0 indicates no restriction on size, so resizing
1800
 *   will be attempted.
1801
 * @param $minimum_dimensions
1802
 *   An optional string in the form WIDTHxHEIGHT. This will check that the
1803
 *   image meets a minimum size. A value of 0 indicates no restriction.
1804
 *
1805
 * @return
1806
 *   An array. If the file is an image and did not meet the requirements, it
1807
 *   will contain an error message.
1808
 *
1809
 * @see hook_file_validate()
1810
 */
1811
function file_validate_image_resolution(stdClass $file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
1812
  $errors = array();
1813

    
1814
  // Check first that the file is an image.
1815
  if ($info = image_get_info($file->uri)) {
1816
    if ($maximum_dimensions) {
1817
      // Check that it is smaller than the given dimensions.
1818
      list($width, $height) = explode('x', $maximum_dimensions);
1819
      if ($info['width'] > $width || $info['height'] > $height) {
1820
        // Try to resize the image to fit the dimensions.
1821
        if ($image = image_load($file->uri)) {
1822
          image_scale($image, $width, $height);
1823
          image_save($image);
1824
          $file->filesize = $image->info['file_size'];
1825
          drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));
1826
        }
1827
        else {
1828
          $errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions));
1829
        }
1830
      }
1831
    }
1832

    
1833
    if ($minimum_dimensions) {
1834
      // Check that it is larger than the given dimensions.
1835
      list($width, $height) = explode('x', $minimum_dimensions);
1836
      if ($info['width'] < $width || $info['height'] < $height) {
1837
        $errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', array('%dimensions' => $minimum_dimensions));
1838
      }
1839
    }
1840
  }
1841

    
1842
  return $errors;
1843
}
1844

    
1845
/**
1846
 * Saves a file to the specified destination and creates a database entry.
1847
 *
1848
 * @param $data
1849
 *   A string containing the contents of the file.
1850
 * @param $destination
1851
 *   A string containing the destination URI. This must be a stream wrapper URI.
1852
 *   If no value is provided, a randomized name will be generated and the file
1853
 *   will be saved using Drupal's default files scheme, usually "public://".
1854
 * @param $replace
1855
 *   Replace behavior when the destination file already exists:
1856
 *   - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
1857
 *       the destination name exists then its database entry will be updated. If
1858
 *       no database entry is found then a new one will be created.
1859
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
1860
 *       unique.
1861
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
1862
 *
1863
 * @return
1864
 *   A file object, or FALSE on error.
1865
 *
1866
 * @see file_unmanaged_save_data()
1867
 */
1868
function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
1869
  global $user;
1870

    
1871
  if (empty($destination)) {
1872
    $destination = file_default_scheme() . '://';
1873
  }
1874
  if (!file_valid_uri($destination)) {
1875
    watchdog('file', 'The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', array('%destination' => $destination));
1876
    drupal_set_message(t('The data could not be saved, because the destination is invalid. More information is available in the system log.'), 'error');
1877
    return FALSE;
1878
  }
1879

    
1880
  if ($uri = file_unmanaged_save_data($data, $destination, $replace)) {
1881
    // Create a file object.
1882
    $file = new stdClass();
1883
    $file->fid = NULL;
1884
    $file->uri = $uri;
1885
    $file->filename = drupal_basename($uri);
1886
    $file->filemime = file_get_mimetype($file->uri);
1887
    $file->uid      = $user->uid;
1888
    $file->status   = FILE_STATUS_PERMANENT;
1889
    // If we are replacing an existing file re-use its database record.
1890
    if ($replace == FILE_EXISTS_REPLACE) {
1891
      $existing_files = file_load_multiple(array(), array('uri' => $uri));
1892
      if (count($existing_files)) {
1893
        $existing = reset($existing_files);
1894
        $file->fid = $existing->fid;
1895
        $file->filename = $existing->filename;
1896
      }
1897
    }
1898
    // If we are renaming around an existing file (rather than a directory),
1899
    // use its basename for the filename.
1900
    elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
1901
      $file->filename = drupal_basename($destination);
1902
    }
1903

    
1904
    return file_save($file);
1905
  }
1906
  return FALSE;
1907
}
1908

    
1909
/**
1910
 * Saves a string to the specified destination without invoking file API.
1911
 *
1912
 * This function is identical to file_save_data() except the file will not be
1913
 * saved to the {file_managed} table and none of the file_* hooks will be
1914
 * called.
1915
 *
1916
 * @param $data
1917
 *   A string containing the contents of the file.
1918
 * @param $destination
1919
 *   A string containing the destination location. This must be a stream wrapper
1920
 *   URI. If no value is provided, a randomized name will be generated and the
1921
 *   file will be saved using Drupal's default files scheme, usually
1922
 *   "public://".
1923
 * @param $replace
1924
 *   Replace behavior when the destination file already exists:
1925
 *   - FILE_EXISTS_REPLACE - Replace the existing file.
1926
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
1927
 *                          unique.
1928
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
1929
 *
1930
 * @return
1931
 *   A string with the path of the resulting file, or FALSE on error.
1932
 *
1933
 * @see file_save_data()
1934
 */
1935
function file_unmanaged_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
1936
  // Write the data to a temporary file.
1937
  $temp_name = drupal_tempnam('temporary://', 'file');
1938
  if (file_put_contents($temp_name, $data) === FALSE) {
1939
    drupal_set_message(t('The file could not be created.'), 'error');
1940
    return FALSE;
1941
  }
1942

    
1943
  // Move the file to its final destination.
1944
  return file_unmanaged_move($temp_name, $destination, $replace);
1945
}
1946

    
1947
/**
1948
 * Transfers a file to the client using HTTP.
1949
 *
1950
 * Pipes a file through Drupal to the client.
1951
 *
1952
 * @param $uri
1953
 *   String specifying the file URI to transfer.
1954
 * @param $headers
1955
 *   An array of HTTP headers to send along with file.
1956
 */
1957
function file_transfer($uri, $headers) {
1958
  if (ob_get_level()) {
1959
    ob_end_clean();
1960
  }
1961

    
1962
  foreach ($headers as $name => $value) {
1963
    drupal_add_http_header($name, $value);
1964
  }
1965
  drupal_send_headers();
1966
  $scheme = file_uri_scheme($uri);
1967
  // Transfer file in 1024 byte chunks to save memory usage.
1968
  if ($scheme && file_stream_wrapper_valid_scheme($scheme) && $fd = fopen($uri, 'rb')) {
1969
    while (!feof($fd)) {
1970
      print fread($fd, 1024);
1971
    }
1972
    fclose($fd);
1973
  }
1974
  else {
1975
    drupal_not_found();
1976
  }
1977
  drupal_exit();
1978
}
1979

    
1980
/**
1981
 * Menu handler for private file transfers.
1982
 *
1983
 * Call modules that implement hook_file_download() to find out if a file is
1984
 * accessible and what headers it should be transferred with. If one or more
1985
 * modules returned headers the download will start with the returned headers.
1986
 * If a module returns -1 drupal_access_denied() will be returned. If the file
1987
 * exists but no modules responded drupal_access_denied() will be returned.
1988
 * If the file does not exist drupal_not_found() will be returned.
1989
 *
1990
 * @see system_menu()
1991
 */
1992
function file_download() {
1993
  // Merge remainder of arguments from GET['q'], into relative file path.
1994
  $args = func_get_args();
1995
  $scheme = array_shift($args);
1996
  $target = implode('/', $args);
1997
  $uri = $scheme . '://' . $target;
1998
  if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {
1999
    $headers = file_download_headers($uri);
2000
    if (count($headers)) {
2001
      file_transfer($uri, $headers);
2002
    }
2003
    drupal_access_denied();
2004
  }
2005
  else {
2006
    drupal_not_found();
2007
  }
2008
  drupal_exit();
2009
}
2010

    
2011
/**
2012
 * Retrieves headers for a private file download.
2013
 *
2014
 * Calls all module implementations of hook_file_download() to retrieve headers
2015
 * for files by the module that originally provided the file. The presence of
2016
 * returned headers indicates the current user has access to the file.
2017
 *
2018
 * @param $uri
2019
 *   The URI for the file whose headers should be retrieved.
2020
 *
2021
 * @return
2022
 *   If access is allowed, headers for the file, suitable for passing to
2023
 *   file_transfer(). If access is not allowed, an empty array will be returned.
2024
 *
2025
 * @see file_transfer()
2026
 * @see file_download_access()
2027
 * @see hook_file_download()
2028
 */
2029
function file_download_headers($uri) {
2030
  // Let other modules provide headers and control access to the file.
2031
  // module_invoke_all() uses array_merge_recursive() which merges header
2032
  // values into a new array. To avoid that and allow modules to override
2033
  // headers instead, use array_merge() to merge the returned arrays.
2034
  $headers = array();
2035
  foreach (module_implements('file_download') as $module) {
2036
    $function = $module . '_file_download';
2037
    $result = $function($uri);
2038
    if ($result == -1) {
2039
      // Throw away the headers received so far.
2040
      $headers = array();
2041
      break;
2042
    }
2043
    if (isset($result) && is_array($result)) {
2044
      $headers = array_merge($headers, $result);
2045
    }
2046
  }
2047
  return $headers;
2048
}
2049

    
2050
/**
2051
 * Checks that the current user has access to a particular file.
2052
 *
2053
 * The return value of this function hinges on the return value from
2054
 * file_download_headers(), which is the function responsible for collecting
2055
 * access information through hook_file_download().
2056
 *
2057
 * If immediately transferring the file to the browser and the headers will
2058
 * need to be retrieved, the return value of file_download_headers() should be
2059
 * used to determine access directly, so that access checks will not be run
2060
 * twice.
2061
 *
2062
 * @param $uri
2063
 *   The URI for the file whose access should be retrieved.
2064
 *
2065
 * @return
2066
 *   Boolean TRUE if access is allowed. FALSE if access is not allowed.
2067
 *
2068
 * @see file_download_headers()
2069
 * @see hook_file_download()
2070
 */
2071
function file_download_access($uri) {
2072
  return count(file_download_headers($uri)) > 0;
2073
}
2074

    
2075
/**
2076
 * Finds all files that match a given mask in a given directory.
2077
 *
2078
 * Directories and files beginning with a period are excluded; this
2079
 * prevents hidden files and directories (such as SVN working directories)
2080
 * from being scanned.
2081
 *
2082
 * @param $dir
2083
 *   The base directory or URI to scan, without trailing slash.
2084
 * @param $mask
2085
 *   The preg_match() regular expression of the files to find.
2086
 * @param $options
2087
 *   An associative array of additional options, with the following elements:
2088
 *   - 'nomask': The preg_match() regular expression of the files to ignore.
2089
 *     Defaults to '/(\.\.?|CVS)$/'.
2090
 *   - 'callback': The callback function to call for each match. There is no
2091
 *     default callback.
2092
 *   - 'recurse': When TRUE, the directory scan will recurse the entire tree
2093
 *     starting at the provided directory. Defaults to TRUE.
2094
 *   - 'key': The key to be used for the returned associative array of files.
2095
 *     Possible values are 'uri', for the file's URI; 'filename', for the
2096
 *     basename of the file; and 'name' for the name of the file without the
2097
 *     extension. Defaults to 'uri'.
2098
 *   - 'min_depth': Minimum depth of directories to return files from. Defaults
2099
 *     to 0.
2100
 * @param $depth
2101
 *   Current depth of recursion. This parameter is only used internally and
2102
 *   should not be passed in.
2103
 *
2104
 * @return
2105
 *   An associative array (keyed on the chosen key) of objects with 'uri',
2106
 *   'filename', and 'name' members corresponding to the matching files.
2107
 */
2108
function file_scan_directory($dir, $mask, $options = array(), $depth = 0) {
2109
  // Merge in defaults.
2110
  $options += array(
2111
    'nomask' => '/(\.\.?|CVS)$/',
2112
    'callback' => 0,
2113
    'recurse' => TRUE,
2114
    'key' => 'uri',
2115
    'min_depth' => 0,
2116
  );
2117

    
2118
  $options['key'] = in_array($options['key'], array('uri', 'filename', 'name')) ? $options['key'] : 'uri';
2119
  $files = array();
2120
  if (is_dir($dir) && $handle = opendir($dir)) {
2121
    while (FALSE !== ($filename = readdir($handle))) {
2122
      if (!preg_match($options['nomask'], $filename) && $filename[0] != '.') {
2123
        $uri = "$dir/$filename";
2124
        $uri = file_stream_wrapper_uri_normalize($uri);
2125
        if (is_dir($uri) && $options['recurse']) {
2126
          // Give priority to files in this folder by merging them in after any subdirectory files.
2127
          $files = array_merge(file_scan_directory($uri, $mask, $options, $depth + 1), $files);
2128
        }
2129
        elseif ($depth >= $options['min_depth'] && preg_match($mask, $filename)) {
2130
          // Always use this match over anything already set in $files with the
2131
          // same $$options['key'].
2132
          $file = new stdClass();
2133
          $file->uri = $uri;
2134
          $file->filename = $filename;
2135
          $file->name = pathinfo($filename, PATHINFO_FILENAME);
2136
          $key = $options['key'];
2137
          $files[$file->$key] = $file;
2138
          if ($options['callback']) {
2139
            $options['callback']($uri);
2140
          }
2141
        }
2142
      }
2143
    }
2144

    
2145
    closedir($handle);
2146
  }
2147

    
2148
  return $files;
2149
}
2150

    
2151
/**
2152
 * Determines the maximum file upload size by querying the PHP settings.
2153
 *
2154
 * @return
2155
 *   A file size limit in bytes based on the PHP upload_max_filesize and
2156
 *   post_max_size
2157
 */
2158
function file_upload_max_size() {
2159
  static $max_size = -1;
2160

    
2161
  if ($max_size < 0) {
2162
    // Start with post_max_size.
2163
    $max_size = parse_size(ini_get('post_max_size'));
2164

    
2165
    // If upload_max_size is less, then reduce. Except if upload_max_size is
2166
    // zero, which indicates no limit.
2167
    $upload_max = parse_size(ini_get('upload_max_filesize'));
2168
    if ($upload_max > 0 && $upload_max < $max_size) {
2169
      $max_size = $upload_max;
2170
    }
2171
  }
2172
  return $max_size;
2173
}
2174

    
2175
/**
2176
 * Determines an Internet Media Type or MIME type from a filename.
2177
 *
2178
 * @param $uri
2179
 *   A string containing the URI, path, or filename.
2180
 * @param $mapping
2181
 *   An optional map of extensions to their mimetypes, in the form:
2182
 *    - 'mimetypes': a list of mimetypes, keyed by an identifier,
2183
 *    - 'extensions': the mapping itself, an associative array in which
2184
 *      the key is the extension (lowercase) and the value is the mimetype
2185
 *      identifier. If $mapping is NULL file_mimetype_mapping() is called.
2186
 *
2187
 * @return
2188
 *   The internet media type registered for the extension or
2189
 *   application/octet-stream for unknown extensions.
2190
 *
2191
 * @see file_default_mimetype_mapping()
2192
 */
2193
function file_get_mimetype($uri, $mapping = NULL) {
2194
  if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
2195
    return $wrapper->getMimeType($uri, $mapping);
2196
  }
2197
  else {
2198
    // getMimeType() is not implementation specific, so we can directly
2199
    // call it without an instance.
2200
    return DrupalLocalStreamWrapper::getMimeType($uri, $mapping);
2201
  }
2202
}
2203

    
2204
/**
2205
 * Sets the permissions on a file or directory.
2206
 *
2207
 * This function will use the 'file_chmod_directory' and 'file_chmod_file'
2208
 * variables for the default modes for directories and uploaded/generated
2209
 * files. By default these will give everyone read access so that users
2210
 * accessing the files with a user account without the webserver group (e.g.
2211
 * via FTP) can read these files, and give group write permissions so webserver
2212
 * group members (e.g. a vhost account) can alter files uploaded and owned by
2213
 * the webserver.
2214
 *
2215
 * PHP's chmod does not support stream wrappers so we use our wrapper
2216
 * implementation which interfaces with chmod() by default. Contrib wrappers
2217
 * may override this behavior in their implementations as needed.
2218
 *
2219
 * @param $uri
2220
 *   A string containing a URI file, or directory path.
2221
 * @param $mode
2222
 *   Integer value for the permissions. Consult PHP chmod() documentation for
2223
 *   more information.
2224
 *
2225
 * @return
2226
 *   TRUE for success, FALSE in the event of an error.
2227
 *
2228
 * @ingroup php_wrappers
2229
 */
2230
function drupal_chmod($uri, $mode = NULL) {
2231
  if (!isset($mode)) {
2232
    if (is_dir($uri)) {
2233
      $mode = variable_get('file_chmod_directory', 0775);
2234
    }
2235
    else {
2236
      $mode = variable_get('file_chmod_file', 0664);
2237
    }
2238
  }
2239

    
2240
  // If this URI is a stream, pass it off to the appropriate stream wrapper.
2241
  // Otherwise, attempt PHP's chmod. This allows use of drupal_chmod even
2242
  // for unmanaged files outside of the stream wrapper interface.
2243
  if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
2244
    if ($wrapper->chmod($mode)) {
2245
      return TRUE;
2246
    }
2247
  }
2248
  else {
2249
    if (@chmod($uri, $mode)) {
2250
      return TRUE;
2251
    }
2252
  }
2253

    
2254
  watchdog('file', 'The file permissions could not be set on %uri.', array('%uri' => $uri), WATCHDOG_ERROR);
2255
  return FALSE;
2256
}
2257

    
2258
/**
2259
 * Deletes a file.
2260
 *
2261
 * PHP's unlink() is broken on Windows, as it can fail to remove a file
2262
 * when it has a read-only flag set.
2263
 *
2264
 * @param $uri
2265
 *   A URI or pathname.
2266
 * @param $context
2267
 *   Refer to http://php.net/manual/ref.stream.php
2268
 *
2269
 * @return
2270
 *   Boolean TRUE on success, or FALSE on failure.
2271
 *
2272
 * @see unlink()
2273
 * @ingroup php_wrappers
2274
 */
2275
function drupal_unlink($uri, $context = NULL) {
2276
  $scheme = file_uri_scheme($uri);
2277
  if ((!$scheme || !file_stream_wrapper_valid_scheme($scheme)) && (substr(PHP_OS, 0, 3) == 'WIN')) {
2278
    chmod($uri, 0600);
2279
  }
2280
  if ($context) {
2281
    return unlink($uri, $context);
2282
  }
2283
  else {
2284
    return unlink($uri);
2285
  }
2286
}
2287

    
2288
/**
2289
 * Resolves the absolute filepath of a local URI or filepath.
2290
 *
2291
 * The use of drupal_realpath() is discouraged, because it does not work for
2292
 * remote URIs. Except in rare cases, URIs should not be manually resolved.
2293
 *
2294
 * Only use this function if you know that the stream wrapper in the URI uses
2295
 * the local file system, and you need to pass an absolute path to a function
2296
 * that is incompatible with stream URIs.
2297
 *
2298
 * @param string $uri
2299
 *   A stream wrapper URI or a filepath, possibly including one or more symbolic
2300
 *   links.
2301
 *
2302
 * @return string|false
2303
 *   The absolute local filepath (with no symbolic links), or FALSE on failure.
2304
 *
2305
 * @see DrupalStreamWrapperInterface::realpath()
2306
 * @see http://php.net/manual/function.realpath.php
2307
 * @ingroup php_wrappers
2308
 */
2309
function drupal_realpath($uri) {
2310
  // If this URI is a stream, pass it off to the appropriate stream wrapper.
2311
  // Otherwise, attempt PHP's realpath. This allows use of drupal_realpath even
2312
  // for unmanaged files outside of the stream wrapper interface.
2313
  if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
2314
    return $wrapper->realpath();
2315
  }
2316
  // Check that the URI has a value. There is a bug in PHP 5.2 on *BSD systems
2317
  // that makes realpath not return FALSE as expected when passing an empty
2318
  // variable.
2319
  // @todo Remove when Drupal drops support for PHP 5.2.
2320
  elseif (!empty($uri)) {
2321
    return realpath($uri);
2322
  }
2323
  return FALSE;
2324
}
2325

    
2326
/**
2327
 * Gets the name of the directory from a given path.
2328
 *
2329
 * PHP's dirname() does not properly pass streams, so this function fills
2330
 * that gap. It is backwards compatible with normal paths and will use
2331
 * PHP's dirname() as a fallback.
2332
 *
2333
 * Compatibility: normal paths and stream wrappers.
2334
 *
2335
 * @param $uri
2336
 *   A URI or path.
2337
 *
2338
 * @return
2339
 *   A string containing the directory name.
2340
 *
2341
 * @see dirname()
2342
 * @see http://drupal.org/node/515192
2343
 * @ingroup php_wrappers
2344
 */
2345
function drupal_dirname($uri) {
2346
  $scheme = file_uri_scheme($uri);
2347

    
2348
  if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
2349
    return file_stream_wrapper_get_instance_by_scheme($scheme)->dirname($uri);
2350
  }
2351
  else {
2352
    return dirname($uri);
2353
  }
2354
}
2355

    
2356
/**
2357
 * Gets the filename from a given path.
2358
 *
2359
 * PHP's basename() does not properly support streams or filenames beginning
2360
 * with a non-US-ASCII character.
2361
 *
2362
 * @see http://bugs.php.net/bug.php?id=37738
2363
 * @see basename()
2364
 *
2365
 * @ingroup php_wrappers
2366
 */
2367
function drupal_basename($uri, $suffix = NULL) {
2368
  $separators = '/';
2369
  if (DIRECTORY_SEPARATOR != '/') {
2370
    // For Windows OS add special separator.
2371
    $separators .= DIRECTORY_SEPARATOR;
2372
  }
2373
  // Remove right-most slashes when $uri points to directory.
2374
  $uri = rtrim($uri, $separators);
2375
  // Returns the trailing part of the $uri starting after one of the directory
2376
  // separators.
2377
  $filename = preg_match('@[^' . preg_quote($separators, '@') . ']+$@', $uri, $matches) ? $matches[0] : '';
2378
  // Cuts off a suffix from the filename.
2379
  if ($suffix) {
2380
    $filename = preg_replace('@' . preg_quote($suffix, '@') . '$@', '', $filename);
2381
  }
2382
  return $filename;
2383
}
2384

    
2385
/**
2386
 * Creates a directory using Drupal's default mode.
2387
 *
2388
 * PHP's mkdir() does not respect Drupal's default permissions mode. If a mode
2389
 * is not provided, this function will make sure that Drupal's is used.
2390
 *
2391
 * Compatibility: normal paths and stream wrappers.
2392
 *
2393
 * @param $uri
2394
 *   A URI or pathname.
2395
 * @param $mode
2396
 *   By default the Drupal mode is used.
2397
 * @param $recursive
2398
 *   Default to FALSE.
2399
 * @param $context
2400
 *   Refer to http://php.net/manual/ref.stream.php
2401
 *
2402
 * @return
2403
 *   Boolean TRUE on success, or FALSE on failure.
2404
 *
2405
 * @see mkdir()
2406
 * @see http://drupal.org/node/515192
2407
 * @ingroup php_wrappers
2408
 */
2409
function drupal_mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL) {
2410
  if (!isset($mode)) {
2411
    $mode = variable_get('file_chmod_directory', 0775);
2412
  }
2413

    
2414
  if (!isset($context)) {
2415
    return mkdir($uri, $mode, $recursive);
2416
  }
2417
  else {
2418
    return mkdir($uri, $mode, $recursive, $context);
2419
  }
2420
}
2421

    
2422
/**
2423
 * Removes a directory.
2424
 *
2425
 * PHP's rmdir() is broken on Windows, as it can fail to remove a directory
2426
 * when it has a read-only flag set.
2427
 *
2428
 * @param $uri
2429
 *   A URI or pathname.
2430
 * @param $context
2431
 *   Refer to http://php.net/manual/ref.stream.php
2432
 *
2433
 * @return
2434
 *   Boolean TRUE on success, or FALSE on failure.
2435
 *
2436
 * @see rmdir()
2437
 * @ingroup php_wrappers
2438
 */
2439
function drupal_rmdir($uri, $context = NULL) {
2440
  $scheme = file_uri_scheme($uri);
2441
  if ((!$scheme || !file_stream_wrapper_valid_scheme($scheme)) && (substr(PHP_OS, 0, 3) == 'WIN')) {
2442
    chmod($uri, 0700);
2443
  }
2444
  if ($context) {
2445
    return rmdir($uri, $context);
2446
  }
2447
  else {
2448
    return rmdir($uri);
2449
  }
2450
}
2451

    
2452
/**
2453
 * Creates a file with a unique filename in the specified directory.
2454
 *
2455
 * PHP's tempnam() does not return a URI like we want. This function
2456
 * will return a URI if given a URI, or it will return a filepath if
2457
 * given a filepath.
2458
 *
2459
 * Compatibility: normal paths and stream wrappers.
2460
 *
2461
 * @param $directory
2462
 *   The directory where the temporary filename will be created.
2463
 * @param $prefix
2464
 *   The prefix of the generated temporary filename.
2465
 *   Note: Windows uses only the first three characters of prefix.
2466
 *
2467
 * @return
2468
 *   The new temporary filename, or FALSE on failure.
2469
 *
2470
 * @see tempnam()
2471
 * @see http://drupal.org/node/515192
2472
 * @ingroup php_wrappers
2473
 */
2474
function drupal_tempnam($directory, $prefix) {
2475
  $scheme = file_uri_scheme($directory);
2476

    
2477
  if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
2478
    $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
2479

    
2480
    if ($filename = tempnam($wrapper->getDirectoryPath(), $prefix)) {
2481
      return $scheme . '://' . drupal_basename($filename);
2482
    }
2483
    else {
2484
      return FALSE;
2485
    }
2486
  }
2487
  else {
2488
    // Handle as a normal tempnam() call.
2489
    return tempnam($directory, $prefix);
2490
  }
2491
}
2492

    
2493
/**
2494
 * Gets the path of system-appropriate temporary directory.
2495
 */
2496
function file_directory_temp() {
2497
  $temporary_directory = variable_get('file_temporary_path', NULL);
2498

    
2499
  if (empty($temporary_directory)) {
2500
    $directories = array();
2501

    
2502
    // Has PHP been set with an upload_tmp_dir?
2503
    if (ini_get('upload_tmp_dir')) {
2504
      $directories[] = ini_get('upload_tmp_dir');
2505
    }
2506

    
2507
    // Operating system specific dirs.
2508
    if (substr(PHP_OS, 0, 3) == 'WIN') {
2509
      $directories[] = 'c:\\windows\\temp';
2510
      $directories[] = 'c:\\winnt\\temp';
2511
    }
2512
    else {
2513
      $directories[] = '/tmp';
2514
    }
2515
    // PHP may be able to find an alternative tmp directory.
2516
    // This function exists in PHP 5 >= 5.2.1, but Drupal
2517
    // requires PHP 5 >= 5.2.0, so we check for it.
2518
    if (function_exists('sys_get_temp_dir')) {
2519
      $directories[] = sys_get_temp_dir();
2520
    }
2521

    
2522
    foreach ($directories as $directory) {
2523
      if (is_dir($directory) && is_writable($directory)) {
2524
        $temporary_directory = $directory;
2525
        break;
2526
      }
2527
    }
2528

    
2529
    if (empty($temporary_directory)) {
2530
      // If no directory has been found default to 'files/tmp'.
2531
      $temporary_directory = variable_get('file_public_path', conf_path() . '/files') . '/tmp';
2532

    
2533
      // Windows accepts paths with either slash (/) or backslash (\), but will
2534
      // not accept a path which contains both a slash and a backslash. Since
2535
      // the 'file_public_path' variable may have either format, we sanitize
2536
      // everything to use slash which is supported on all platforms.
2537
      $temporary_directory = str_replace('\\', '/', $temporary_directory);
2538
    }
2539
    // Save the path of the discovered directory.
2540
    variable_set('file_temporary_path', $temporary_directory);
2541
  }
2542

    
2543
  return $temporary_directory;
2544
}
2545

    
2546
/**
2547
 * Examines a file object and returns appropriate content headers for download.
2548
 *
2549
 * @param $file
2550
 *   A file object.
2551
 *
2552
 * @return
2553
 *   An associative array of headers, as expected by file_transfer().
2554
 */
2555
function file_get_content_headers($file) {
2556
  $name = mime_header_encode($file->filename);
2557
  $type = mime_header_encode($file->filemime);
2558

    
2559
  return array(
2560
    'Content-Type' => $type,
2561
    'Content-Length' => $file->filesize,
2562
    'Cache-Control' => 'private',
2563
  );
2564
}
2565

    
2566
/**
2567
 * @} End of "defgroup file".
2568
 */