Projet

Général

Profil

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

root / drupal7 / includes / file.inc @ cee0424c

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
<IfModule mod_php7.c>
536
  php_flag engine off
537
</IfModule>
538
EOF;
539

    
540
  if ($private) {
541
    $lines = <<<EOF
542
# Deny all requests from Apache 2.4+.
543
<IfModule mod_authz_core.c>
544
  Require all denied
545
</IfModule>
546

    
547
# Deny all requests from Apache 2.0-2.2.
548
<IfModule !mod_authz_core.c>
549
  Deny from all
550
</IfModule>
551
EOF
552
    . "\n\n" . $lines;
553
  }
554

    
555
  return $lines;
556
}
557

    
558
/**
559
 * Loads file objects from the database.
560
 *
561
 * @param $fids
562
 *   An array of file IDs.
563
 * @param $conditions
564
 *   (deprecated) An associative array of conditions on the {file_managed}
565
 *   table, where the keys are the database fields and the values are the
566
 *   values those fields must have. Instead, it is preferable to use
567
 *   EntityFieldQuery to retrieve a list of entity IDs loadable by
568
 *   this function.
569
 *
570
 * @return
571
 *   An array of file objects, indexed by fid.
572
 *
573
 * @todo Remove $conditions in Drupal 8.
574
 *
575
 * @see hook_file_load()
576
 * @see file_load()
577
 * @see entity_load()
578
 * @see EntityFieldQuery
579
 */
580
function file_load_multiple($fids = array(), $conditions = array()) {
581
  return entity_load('file', $fids, $conditions);
582
}
583

    
584
/**
585
 * Loads a single file object from the database.
586
 *
587
 * @param $fid
588
 *   A file ID.
589
 *
590
 * @return
591
 *   An object representing the file, or FALSE if the file was not found.
592
 *
593
 * @see hook_file_load()
594
 * @see file_load_multiple()
595
 */
596
function file_load($fid) {
597
  $files = file_load_multiple(array($fid), array());
598
  return reset($files);
599
}
600

    
601
/**
602
 * Saves a file object to the database.
603
 *
604
 * If the $file->fid is not set a new record will be added.
605
 *
606
 * @param $file
607
 *   A file object returned by file_load().
608
 *
609
 * @return
610
 *   The updated file object.
611
 *
612
 * @see hook_file_insert()
613
 * @see hook_file_update()
614
 */
615
function file_save(stdClass $file) {
616
  $file->timestamp = REQUEST_TIME;
617
  $file->filesize = filesize($file->uri);
618

    
619
  // Load the stored entity, if any.
620
  if (!empty($file->fid) && !isset($file->original)) {
621
    $file->original = entity_load_unchanged('file', $file->fid);
622
  }
623

    
624
  module_invoke_all('file_presave', $file);
625
  module_invoke_all('entity_presave', $file, 'file');
626

    
627
  if (empty($file->fid)) {
628
    drupal_write_record('file_managed', $file);
629
    // Inform modules about the newly added file.
630
    module_invoke_all('file_insert', $file);
631
    module_invoke_all('entity_insert', $file, 'file');
632
  }
633
  else {
634
    drupal_write_record('file_managed', $file, 'fid');
635
    // Inform modules that the file has been updated.
636
    module_invoke_all('file_update', $file);
637
    module_invoke_all('entity_update', $file, 'file');
638
  }
639

    
640
  // Clear internal properties.
641
  unset($file->original);
642
  // Clear the static loading cache.
643
  entity_get_controller('file')->resetCache(array($file->fid));
644

    
645
  return $file;
646
}
647

    
648
/**
649
 * Determines where a file is used.
650
 *
651
 * @param $file
652
 *   A file object.
653
 *
654
 * @return
655
 *   A nested array with usage data. The first level is keyed by module name,
656
 *   the second by object type and the third by the object id. The value
657
 *   of the third level contains the usage count.
658
 *
659
 * @see file_usage_add()
660
 * @see file_usage_delete()
661
 */
662
function file_usage_list(stdClass $file) {
663
  $result = db_select('file_usage', 'f')
664
    ->fields('f', array('module', 'type', 'id', 'count'))
665
    ->condition('fid', $file->fid)
666
    ->condition('count', 0, '>')
667
    ->execute();
668
  $references = array();
669
  foreach ($result as $usage) {
670
    $references[$usage->module][$usage->type][$usage->id] = $usage->count;
671
  }
672
  return $references;
673
}
674

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

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

    
755
  // If the row has more than the specified count decrement it by that number.
756
  if (!$result && $count > 0) {
757
    $query = db_update('file_usage')
758
      ->condition('module', $module)
759
      ->condition('fid', $file->fid);
760
    if ($type && $id) {
761
      $query
762
        ->condition('type', $type)
763
        ->condition('id', $id);
764
    }
765
    $query->expression('count', 'count - :count', array(':count' => $count));
766
    $query->execute();
767
  }
768
}
769

    
770
/**
771
 * Copies a file to a new location and adds a file record to the database.
772
 *
773
 * This function should be used when manipulating files that have records
774
 * stored in the database. This is a powerful function that in many ways
775
 * performs like an advanced version of copy().
776
 * - Checks if $source and $destination are valid and readable/writable.
777
 * - If file already exists in $destination either the call will error out,
778
 *   replace the file or rename the file based on the $replace parameter.
779
 * - If the $source and $destination are equal, the behavior depends on the
780
 *   $replace parameter. FILE_EXISTS_REPLACE will error out. FILE_EXISTS_RENAME
781
 *   will rename the file until the $destination is unique.
782
 * - Adds the new file to the files database. If the source file is a
783
 *   temporary file, the resulting file will also be a temporary file. See
784
 *   file_save_upload() for details on temporary files.
785
 *
786
 * @param $source
787
 *   A file object.
788
 * @param $destination
789
 *   A string containing the destination that $source should be copied to.
790
 *   This must be a stream wrapper URI.
791
 * @param $replace
792
 *   Replace behavior when the destination file already exists:
793
 *   - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
794
 *       the destination name exists then its database entry will be updated. If
795
 *       no database entry is found then a new one will be created.
796
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
797
 *       unique.
798
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
799
 *
800
 * @return
801
 *   File object if the copy is successful, or FALSE in the event of an error.
802
 *
803
 * @see file_unmanaged_copy()
804
 * @see hook_file_copy()
805
 */
806
function file_copy(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
807
  if (!file_valid_uri($destination)) {
808
    if (($realpath = drupal_realpath($source->uri)) !== FALSE) {
809
      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));
810
    }
811
    else {
812
      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));
813
    }
814
    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');
815
    return FALSE;
816
  }
817

    
818
  if ($uri = file_unmanaged_copy($source->uri, $destination, $replace)) {
819
    $file = clone $source;
820
    $file->fid = NULL;
821
    $file->uri = $uri;
822
    $file->filename = drupal_basename($uri);
823
    // If we are replacing an existing file re-use its database record.
824
    if ($replace == FILE_EXISTS_REPLACE) {
825
      $existing_files = file_load_multiple(array(), array('uri' => $uri));
826
      if (count($existing_files)) {
827
        $existing = reset($existing_files);
828
        $file->fid = $existing->fid;
829
        $file->filename = $existing->filename;
830
      }
831
    }
832
    // If we are renaming around an existing file (rather than a directory),
833
    // use its basename for the filename.
834
    elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
835
      $file->filename = drupal_basename($destination);
836
    }
837

    
838
    $file = file_save($file);
839

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

    
843
    return $file;
844
  }
845
  return FALSE;
846
}
847

    
848
/**
849
 * Determines whether the URI has a valid scheme for file API operations.
850
 *
851
 * There must be a scheme and it must be a Drupal-provided scheme like
852
 * 'public', 'private', 'temporary', or an extension provided with
853
 * hook_stream_wrappers().
854
 *
855
 * @param $uri
856
 *   The URI to be tested.
857
 *
858
 * @return
859
 *   TRUE if the URI is allowed.
860
 */
861
function file_valid_uri($uri) {
862
  // Assert that the URI has an allowed scheme. Barepaths are not allowed.
863
  $uri_scheme = file_uri_scheme($uri);
864
  if (empty($uri_scheme) || !file_stream_wrapper_valid_scheme($uri_scheme)) {
865
    return FALSE;
866
  }
867
  return TRUE;
868
}
869

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

    
907
  // Assert that the source file actually exists.
908
  if (!file_exists($source)) {
909
    // @todo Replace drupal_set_message() calls with exceptions instead.
910
    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');
911
    if (($realpath = drupal_realpath($original_source)) !== FALSE) {
912
      watchdog('file', 'File %file (%realpath) could not be copied because it does not exist.', array('%file' => $original_source, '%realpath' => $realpath));
913
    }
914
    else {
915
      watchdog('file', 'File %file could not be copied because it does not exist.', array('%file' => $original_source));
916
    }
917
    return FALSE;
918
  }
919

    
920
  // Build a destination URI if necessary.
921
  if (!isset($destination)) {
922
    $destination = file_build_uri(drupal_basename($source));
923
  }
924

    
925

    
926
  // Prepare the destination directory.
927
  if (file_prepare_directory($destination)) {
928
    // The destination is already a directory, so append the source basename.
929
    $destination = file_stream_wrapper_uri_normalize($destination . '/' . drupal_basename($source));
930
  }
931
  else {
932
    // Perhaps $destination is a dir/file?
933
    $dirname = drupal_dirname($destination);
934
    if (!file_prepare_directory($dirname)) {
935
      // The destination is not valid.
936
      watchdog('file', 'File %file could not be copied, because the destination directory %destination is not configured correctly.', array('%file' => $original_source, '%destination' => $dirname));
937
      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');
938
      return FALSE;
939
    }
940
  }
941

    
942
  // Determine whether we can perform this operation based on overwrite rules.
943
  $destination = file_destination($destination, $replace);
944
  if ($destination === FALSE) {
945
    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');
946
    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));
947
    return FALSE;
948
  }
949

    
950
  // Assert that the source and destination filenames are not the same.
951
  $real_source = drupal_realpath($source);
952
  $real_destination = drupal_realpath($destination);
953
  if ($source == $destination || ($real_source !== FALSE) && ($real_source == $real_destination)) {
954
    drupal_set_message(t('The specified file %file was not copied because it would overwrite itself.', array('%file' => $source)), 'error');
955
    watchdog('file', 'File %file could not be copied because it would overwrite itself.', array('%file' => $source));
956
    return FALSE;
957
  }
958
  // Make sure the .htaccess files are present.
959
  file_ensure_htaccess();
960
  // Perform the copy operation.
961
  if (!@copy($source, $destination)) {
962
    // If the copy failed and realpaths exist, retry the operation using them
963
    // instead.
964
    if ($real_source === FALSE || $real_destination === FALSE || !@copy($real_source, $real_destination)) {
965
      watchdog('file', 'The specified file %file could not be copied to %destination.', array('%file' => $source, '%destination' => $destination), WATCHDOG_ERROR);
966
      return FALSE;
967
    }
968
  }
969

    
970
  // Set the permissions on the new file.
971
  drupal_chmod($destination);
972

    
973
  return $destination;
974
}
975

    
976
/**
977
 * Constructs a URI to Drupal's default files location given a relative path.
978
 */
979
function file_build_uri($path) {
980
  $uri = file_default_scheme() . '://' . $path;
981
  return file_stream_wrapper_uri_normalize($uri);
982
}
983

    
984
/**
985
 * Determines the destination path for a file.
986
 *
987
 * @param $destination
988
 *   A string specifying the desired final URI or filepath.
989
 * @param $replace
990
 *   Replace behavior when the destination file already exists.
991
 *   - FILE_EXISTS_REPLACE - Replace the existing file.
992
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
993
 *       unique.
994
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
995
 *
996
 * @return
997
 *   The destination filepath, or FALSE if the file already exists
998
 *   and FILE_EXISTS_ERROR is specified.
999
 *
1000
 * @throws RuntimeException
1001
 *   Thrown if the filename contains invalid UTF-8.
1002
 */
1003
function file_destination($destination, $replace) {
1004
  $basename = drupal_basename($destination);
1005
  if (!drupal_validate_utf8($basename)) {
1006
    throw new RuntimeException(sprintf("Invalid filename '%s'", $basename));
1007
  }
1008
  if (file_exists($destination)) {
1009
    switch ($replace) {
1010
      case FILE_EXISTS_REPLACE:
1011
        // Do nothing here, we want to overwrite the existing file.
1012
        break;
1013

    
1014
      case FILE_EXISTS_RENAME:
1015
        $directory = drupal_dirname($destination);
1016
        $destination = file_create_filename($basename, $directory);
1017
        break;
1018

    
1019
      case FILE_EXISTS_ERROR:
1020
        // Error reporting handled by calling function.
1021
        return FALSE;
1022
    }
1023
  }
1024
  return $destination;
1025
}
1026

    
1027
/**
1028
 * Moves a file to a new location and update the file's database entry.
1029
 *
1030
 * Moving a file is performed by copying the file to the new location and then
1031
 * deleting the original.
1032
 * - Checks if $source and $destination are valid and readable/writable.
1033
 * - Performs a file move if $source is not equal to $destination.
1034
 * - If file already exists in $destination either the call will error out,
1035
 *   replace the file or rename the file based on the $replace parameter.
1036
 * - Adds the new file to the files database.
1037
 *
1038
 * @param $source
1039
 *   A file object.
1040
 * @param $destination
1041
 *   A string containing the destination that $source should be moved to.
1042
 *   This must be a stream wrapper URI.
1043
 * @param $replace
1044
 *   Replace behavior when the destination file already exists:
1045
 *   - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
1046
 *       the destination name exists then its database entry will be updated and
1047
 *       file_delete() called on the source file after hook_file_move is called.
1048
 *       If no database entry is found then the source files record will be
1049
 *       updated.
1050
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
1051
 *       unique.
1052
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
1053
 *
1054
 * @return
1055
 *   Resulting file object for success, or FALSE in the event of an error.
1056
 *
1057
 * @see file_unmanaged_move()
1058
 * @see hook_file_move()
1059
 */
1060
function file_move(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
1061
  if (!file_valid_uri($destination)) {
1062
    if (($realpath = drupal_realpath($source->uri)) !== FALSE) {
1063
      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));
1064
    }
1065
    else {
1066
      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));
1067
    }
1068
    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');
1069
    return FALSE;
1070
  }
1071

    
1072
  if ($uri = file_unmanaged_move($source->uri, $destination, $replace)) {
1073
    $delete_source = FALSE;
1074

    
1075
    $file = clone $source;
1076
    $file->uri = $uri;
1077
    // If we are replacing an existing file re-use its database record.
1078
    if ($replace == FILE_EXISTS_REPLACE) {
1079
      $existing_files = file_load_multiple(array(), array('uri' => $uri));
1080
      if (count($existing_files)) {
1081
        $existing = reset($existing_files);
1082
        $delete_source = TRUE;
1083
        $file->fid = $existing->fid;
1084
      }
1085
    }
1086
    // If we are renaming around an existing file (rather than a directory),
1087
    // use its basename for the filename.
1088
    elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
1089
      $file->filename = drupal_basename($destination);
1090
    }
1091

    
1092
    $file = file_save($file);
1093

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

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

    
1102
    return $file;
1103
  }
1104
  return FALSE;
1105
}
1106

    
1107
/**
1108
 * Moves a file to a new location without database changes or hook invocation.
1109
 *
1110
 * @param $source
1111
 *   A string specifying the filepath or URI of the original file.
1112
 * @param $destination
1113
 *   A string containing the destination that $source should be moved to.
1114
 *   This must be a stream wrapper URI. If this value is omitted, Drupal's
1115
 *   default files scheme will be used, usually "public://".
1116
 * @param $replace
1117
 *   Replace behavior when the destination file already exists:
1118
 *   - FILE_EXISTS_REPLACE - Replace the existing file.
1119
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
1120
 *       unique.
1121
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
1122
 *
1123
 * @return
1124
 *   The URI of the moved file, or FALSE in the event of an error.
1125
 *
1126
 * @see file_move()
1127
 */
1128
function file_unmanaged_move($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
1129
  $filepath = file_unmanaged_copy($source, $destination, $replace);
1130
  if ($filepath == FALSE || file_unmanaged_delete($source) == FALSE) {
1131
    return FALSE;
1132
  }
1133
  return $filepath;
1134
}
1135

    
1136
/**
1137
 * Modifies a filename as needed for security purposes.
1138
 *
1139
 * Munging a file name prevents unknown file extensions from masking exploit
1140
 * files. When web servers such as Apache decide how to process a URL request,
1141
 * they use the file extension. If the extension is not recognized, Apache
1142
 * skips that extension and uses the previous file extension. For example, if
1143
 * the file being requested is exploit.php.pps, and Apache does not recognize
1144
 * the '.pps' extension, it treats the file as PHP and executes it. To make
1145
 * this file name safe for Apache and prevent it from executing as PHP, the
1146
 * .php extension is "munged" into .php_, making the safe file name
1147
 * exploit.php_.pps.
1148
 *
1149
 * Specifically, this function adds an underscore to all extensions that are
1150
 * between 2 and 5 characters in length, internal to the file name, and either
1151
 * included in the list of unsafe extensions, or not included in $extensions.
1152
 *
1153
 * Function behavior is also controlled by the Drupal variable
1154
 * 'allow_insecure_uploads'. If 'allow_insecure_uploads' evaluates to TRUE, no
1155
 * alterations will be made, if it evaluates to FALSE, the filename is 'munged'.
1156
 *
1157
 * @param $filename
1158
 *   File name to modify.
1159
 * @param $extensions
1160
 *   A space-separated list of extensions that should not be altered. Note that
1161
 *   extensions that are unsafe will be altered regardless of this parameter.
1162
 * @param $alerts
1163
 *   If TRUE, drupal_set_message() will be called to display a message if the
1164
 *   file name was changed.
1165
 *
1166
 * @return
1167
 *   The potentially modified $filename.
1168
 */
1169
function file_munge_filename($filename, $extensions, $alerts = TRUE) {
1170
  $original = $filename;
1171

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

    
1177
    $whitelist = array_unique(explode(' ', strtolower(trim($extensions))));
1178

    
1179
    // Remove unsafe extensions from the list of allowed extensions. The list is
1180
    // copied from file_save_upload().
1181
    $whitelist = array_diff($whitelist, explode('|', 'php|phar|pl|py|cgi|asp|js'));
1182

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

    
1189
    // Loop through the middle parts of the name and add an underscore to the
1190
    // end of each section that could be a file extension but isn't in the list
1191
    // of allowed extensions.
1192
    foreach ($filename_parts as $filename_part) {
1193
      $new_filename .= '.' . $filename_part;
1194
      if (!in_array(strtolower($filename_part), $whitelist) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $filename_part)) {
1195
        $new_filename .= '_';
1196
      }
1197
    }
1198
    $filename = $new_filename . '.' . $final_extension;
1199

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

    
1205
  return $filename;
1206
}
1207

    
1208
/**
1209
 * Undoes the effect of file_munge_filename().
1210
 *
1211
 * @param $filename
1212
 *   String with the filename to be unmunged.
1213
 *
1214
 * @return
1215
 *   An unmunged filename string.
1216
 */
1217
function file_unmunge_filename($filename) {
1218
  return str_replace('_.', '.', $filename);
1219
}
1220

    
1221
/**
1222
 * Creates a full file path from a directory and filename.
1223
 *
1224
 * If a file with the specified name already exists, an alternative will be
1225
 * used.
1226
 *
1227
 * @param $basename
1228
 *   String filename
1229
 * @param $directory
1230
 *   String containing the directory or parent URI.
1231
 *
1232
 * @return
1233
 *   File path consisting of $directory and a unique filename based off
1234
 *   of $basename.
1235
 *
1236
 * @throws RuntimeException
1237
 *   Thrown if the $basename is not valid UTF-8 or another error occurs
1238
 *   stripping control characters.
1239
 */
1240
function file_create_filename($basename, $directory) {
1241
  $original = $basename;
1242
  // Strip control characters (ASCII value < 32). Though these are allowed in
1243
  // some filesystems, not many applications handle them well.
1244
  $basename = preg_replace('/[\x00-\x1F]/u', '_', $basename);
1245
  if (preg_last_error() !== PREG_NO_ERROR) {
1246
    throw new RuntimeException(sprintf("Invalid filename '%s'", $original));
1247
  }
1248

    
1249
  if (substr(PHP_OS, 0, 3) == 'WIN') {
1250
    // These characters are not allowed in Windows filenames
1251
    $basename = str_replace(array(':', '*', '?', '"', '<', '>', '|'), '_', $basename);
1252
  }
1253

    
1254
  // A URI or path may already have a trailing slash or look like "public://".
1255
  if (substr($directory, -1) == '/') {
1256
    $separator = '';
1257
  }
1258
  else {
1259
    $separator = '/';
1260
  }
1261

    
1262
  $destination = $directory . $separator . $basename;
1263

    
1264
  if (file_exists($destination)) {
1265
    // Destination file already exists, generate an alternative.
1266
    $pos = strrpos($basename, '.');
1267
    if ($pos !== FALSE) {
1268
      $name = substr($basename, 0, $pos);
1269
      $ext = substr($basename, $pos);
1270
    }
1271
    else {
1272
      $name = $basename;
1273
      $ext = '';
1274
    }
1275

    
1276
    $counter = 0;
1277
    do {
1278
      $destination = $directory . $separator . $name . '_' . $counter++ . $ext;
1279
    } while (file_exists($destination));
1280
  }
1281

    
1282
  return $destination;
1283
}
1284

    
1285
/**
1286
 * Deletes a file and its database record.
1287
 *
1288
 * If the $force parameter is not TRUE, file_usage_list() will be called to
1289
 * determine if the file is being used by any modules. If the file is being
1290
 * used the delete will be canceled.
1291
 *
1292
 * @param $file
1293
 *   A file object.
1294
 * @param $force
1295
 *   Boolean indicating that the file should be deleted even if the file is
1296
 *   reported as in use by the file_usage table.
1297
 *
1298
 * @return mixed
1299
 *   TRUE for success, FALSE in the event of an error, or an array if the file
1300
 *   is being used by any modules.
1301
 *
1302
 * @see file_unmanaged_delete()
1303
 * @see file_usage_list()
1304
 * @see file_usage_delete()
1305
 * @see hook_file_delete()
1306
 */
1307
function file_delete(stdClass $file, $force = FALSE) {
1308
  if (!file_valid_uri($file->uri)) {
1309
    if (($realpath = drupal_realpath($file->uri)) !== FALSE) {
1310
      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));
1311
    }
1312
    else {
1313
      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));
1314
    }
1315
    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');
1316
    return FALSE;
1317
  }
1318

    
1319
  // If any module still has a usage entry in the file_usage table, the file
1320
  // will not be deleted, but file_delete() will return a populated array
1321
  // that tests as TRUE.
1322
  if (!$force && ($references = file_usage_list($file))) {
1323
    return $references;
1324
  }
1325

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

    
1330
  // Make sure the file is deleted before removing its row from the
1331
  // database, so UIs can still find the file in the database.
1332
  if (file_unmanaged_delete($file->uri)) {
1333
    db_delete('file_managed')->condition('fid', $file->fid)->execute();
1334
    db_delete('file_usage')->condition('fid', $file->fid)->execute();
1335
    entity_get_controller('file')->resetCache();
1336
    return TRUE;
1337
  }
1338
  return FALSE;
1339
}
1340

    
1341
/**
1342
 * Deletes a file without database changes or hook invocations.
1343
 *
1344
 * This function should be used when the file to be deleted does not have an
1345
 * entry recorded in the files table.
1346
 *
1347
 * @param $path
1348
 *   A string containing a file path or (streamwrapper) URI.
1349
 *
1350
 * @return
1351
 *   TRUE for success or path does not exist, or FALSE in the event of an
1352
 *   error.
1353
 *
1354
 * @see file_delete()
1355
 * @see file_unmanaged_delete_recursive()
1356
 */
1357
function file_unmanaged_delete($path) {
1358
  if (is_dir($path)) {
1359
    watchdog('file', '%path is a directory and cannot be removed using file_unmanaged_delete().', array('%path' => $path), WATCHDOG_ERROR);
1360
    return FALSE;
1361
  }
1362
  if (is_file($path)) {
1363
    return drupal_unlink($path);
1364
  }
1365
  // Return TRUE for non-existent file, but log that nothing was actually
1366
  // deleted, as the current state is the intended result.
1367
  if (!file_exists($path)) {
1368
    watchdog('file', 'The file %path was not deleted, because it does not exist.', array('%path' => $path), WATCHDOG_NOTICE);
1369
    return TRUE;
1370
  }
1371
  // We cannot handle anything other than files and directories. Log an error
1372
  // for everything else (sockets, symbolic links, etc).
1373
  watchdog('file', 'The file %path is not of a recognized type so it was not deleted.', array('%path' => $path), WATCHDOG_ERROR);
1374
  return FALSE;
1375
}
1376

    
1377
/**
1378
 * Deletes all files and directories in the specified filepath recursively.
1379
 *
1380
 * If the specified path is a directory then the function will call itself
1381
 * recursively to process the contents. Once the contents have been removed the
1382
 * directory will also be removed.
1383
 *
1384
 * If the specified path is a file then it will be passed to
1385
 * file_unmanaged_delete().
1386
 *
1387
 * Note that this only deletes visible files with write permission.
1388
 *
1389
 * @param $path
1390
 *   A string containing either an URI or a file or directory path.
1391
 *
1392
 * @return
1393
 *   TRUE for success or if path does not exist, FALSE in the event of an
1394
 *   error.
1395
 *
1396
 * @see file_unmanaged_delete()
1397
 */
1398
function file_unmanaged_delete_recursive($path) {
1399
  if (is_dir($path)) {
1400
    $dir = dir($path);
1401
    while (($entry = $dir->read()) !== FALSE) {
1402
      if ($entry == '.' || $entry == '..') {
1403
        continue;
1404
      }
1405
      $entry_path = $path . '/' . $entry;
1406
      file_unmanaged_delete_recursive($entry_path);
1407
    }
1408
    $dir->close();
1409

    
1410
    return drupal_rmdir($path);
1411
  }
1412
  return file_unmanaged_delete($path);
1413
}
1414

    
1415
/**
1416
 * Determines total disk space used by a single user or the whole filesystem.
1417
 *
1418
 * @param $uid
1419
 *   Optional. A user id, specifying NULL returns the total space used by all
1420
 *   non-temporary files.
1421
 * @param $status
1422
 *   Optional. The file status to consider. The default is to only
1423
 *   consider files in status FILE_STATUS_PERMANENT.
1424
 *
1425
 * @return
1426
 *   An integer containing the number of bytes used.
1427
 */
1428
function file_space_used($uid = NULL, $status = FILE_STATUS_PERMANENT) {
1429
  $query = db_select('file_managed', 'f');
1430
  $query->condition('f.status', $status);
1431
  $query->addExpression('SUM(f.filesize)', 'filesize');
1432
  if (isset($uid)) {
1433
    $query->condition('f.uid', $uid);
1434
  }
1435
  return $query->execute()->fetchField();
1436
}
1437

    
1438
/**
1439
 * Saves a file upload to a new location.
1440
 *
1441
 * The file will be added to the {file_managed} table as a temporary file.
1442
 * Temporary files are periodically cleaned. To make the file a permanent file,
1443
 * assign the status and use file_save() to save the changes.
1444
 *
1445
 * @param $form_field_name
1446
 *   A string that is the associative array key of the upload form element in
1447
 *   the form array.
1448
 * @param $validators
1449
 *   An optional, associative array of callback functions used to validate the
1450
 *   file. See file_validate() for a full discussion of the array format.
1451
 *   If no extension validator is provided it will default to a limited safe
1452
 *   list of extensions which is as follows: "jpg jpeg gif png txt
1453
 *   doc xls pdf ppt pps odt ods odp". To allow all extensions you must
1454
 *   explicitly set the 'file_validate_extensions' validator to an empty array
1455
 *   (Beware: this is not safe and should only be allowed for trusted users, if
1456
 *   at all).
1457
 * @param $destination
1458
 *   A string containing the URI that the file should be copied to. This must
1459
 *   be a stream wrapper URI. If this value is omitted, Drupal's temporary
1460
 *   files scheme will be used ("temporary://").
1461
 * @param $replace
1462
 *   Replace behavior when the destination file already exists:
1463
 *   - FILE_EXISTS_REPLACE: Replace the existing file.
1464
 *   - FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is
1465
 *     unique.
1466
 *   - FILE_EXISTS_ERROR: Do nothing and return FALSE.
1467
 *
1468
 * @return
1469
 *   An object containing the file information if the upload succeeded, FALSE
1470
 *   in the event of an error, or NULL if no file was uploaded. The
1471
 *   documentation for the "File interface" group, which you can find under
1472
 *   Related topics, or the header at the top of this file, documents the
1473
 *   components of a file object. In addition to the standard components,
1474
 *   this function adds:
1475
 *   - source: Path to the file before it is moved.
1476
 *   - destination: Path to the file after it is moved (same as 'uri').
1477
 */
1478
function file_save_upload($form_field_name, $validators = array(), $destination = FALSE, $replace = FILE_EXISTS_RENAME) {
1479
  global $user;
1480
  static $upload_cache;
1481

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

    
1488
  // Make sure there's an upload to process.
1489
  if (empty($_FILES['files']['name'][$form_field_name])) {
1490
    return NULL;
1491
  }
1492

    
1493
  // Check for file upload errors and return FALSE if a lower level system
1494
  // error occurred. For a complete list of errors:
1495
  // See http://php.net/manual/features.file-upload.errors.php.
1496
  switch ($_FILES['files']['error'][$form_field_name]) {
1497
    case UPLOAD_ERR_INI_SIZE:
1498
    case UPLOAD_ERR_FORM_SIZE:
1499
      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');
1500
      return FALSE;
1501

    
1502
    case UPLOAD_ERR_PARTIAL:
1503
    case UPLOAD_ERR_NO_FILE:
1504
      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');
1505
      return FALSE;
1506

    
1507
    case UPLOAD_ERR_OK:
1508
      // Final check that this is a valid upload, if it isn't, use the
1509
      // default error handler.
1510
      if (is_uploaded_file($_FILES['files']['tmp_name'][$form_field_name])) {
1511
        break;
1512
      }
1513

    
1514
    // Unknown error
1515
    default:
1516
      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');
1517
      return FALSE;
1518
  }
1519

    
1520
  // Begin building file object.
1521
  $file = new stdClass();
1522
  $file->uid      = $user->uid;
1523
  $file->status   = 0;
1524
  $file->filename = trim(drupal_basename($_FILES['files']['name'][$form_field_name]), '.');
1525
  $file->uri      = $_FILES['files']['tmp_name'][$form_field_name];
1526
  $file->filemime = file_get_mimetype($file->filename);
1527
  $file->filesize = $_FILES['files']['size'][$form_field_name];
1528

    
1529
  $extensions = '';
1530
  if (isset($validators['file_validate_extensions'])) {
1531
    if (isset($validators['file_validate_extensions'][0])) {
1532
      // Build the list of non-munged extensions if the caller provided them.
1533
      $extensions = $validators['file_validate_extensions'][0];
1534
    }
1535
    else {
1536
      // If 'file_validate_extensions' is set and the list is empty then the
1537
      // caller wants to allow any extension. In this case we have to remove the
1538
      // validator or else it will reject all extensions.
1539
      unset($validators['file_validate_extensions']);
1540
    }
1541
  }
1542
  else {
1543
    // No validator was provided, so add one using the default list.
1544
    // Build a default non-munged safe list for file_munge_filename().
1545
    $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp';
1546
    $validators['file_validate_extensions'] = array();
1547
    $validators['file_validate_extensions'][0] = $extensions;
1548
  }
1549

    
1550
  if (!variable_get('allow_insecure_uploads', 0)) {
1551
    if (!empty($extensions)) {
1552
      // Munge the filename to protect against possible malicious extension hiding
1553
      // within an unknown file type (ie: filename.html.foo).
1554
      $file->filename = file_munge_filename($file->filename, $extensions);
1555
    }
1556

    
1557
    // Rename potentially executable files, to help prevent exploits (i.e. will
1558
    // rename filename.php.foo and filename.php to filename.php_.foo_.txt and
1559
    // filename.php_.txt, respectively). Don't rename if 'allow_insecure_uploads'
1560
    // evaluates to TRUE.
1561
    if (preg_match('/\.(php|phar|pl|py|cgi|asp|js)(\.|$)/i', $file->filename)) {
1562
      // If the file will be rejected anyway due to a disallowed extension, it
1563
      // should not be renamed; rather, we'll let file_validate_extensions()
1564
      // reject it below.
1565
      if (!isset($validators['file_validate_extensions']) || !file_validate_extensions($file, $extensions)) {
1566
        $file->filemime = 'text/plain';
1567
        if (substr($file->filename, -4) != '.txt') {
1568
          // The destination filename will also later be used to create the URI.
1569
          $file->filename .= '.txt';
1570
        }
1571
        $file->filename = file_munge_filename($file->filename, $extensions, FALSE);
1572
        drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $file->filename)));
1573
        // The .txt extension may not be in the allowed list of extensions. We have
1574
        // to add it here or else the file upload will fail.
1575
        if (!empty($validators['file_validate_extensions'][0])) {
1576
          $validators['file_validate_extensions'][0] .= ' txt';
1577
        }
1578
      }
1579
    }
1580
  }
1581

    
1582
  // If the destination is not provided, use the temporary directory.
1583
  if (empty($destination)) {
1584
    $destination = 'temporary://';
1585
  }
1586

    
1587
  // Assert that the destination contains a valid stream.
1588
  $destination_scheme = file_uri_scheme($destination);
1589
  if (!$destination_scheme || !file_stream_wrapper_valid_scheme($destination_scheme)) {
1590
    drupal_set_message(t('The file could not be uploaded, because the destination %destination is invalid.', array('%destination' => $destination)), 'error');
1591
    return FALSE;
1592
  }
1593

    
1594
  $file->source = $form_field_name;
1595
  // A URI may already have a trailing slash or look like "public://".
1596
  if (substr($destination, -1) != '/') {
1597
    $destination .= '/';
1598
  }
1599
  try {
1600
    $file->destination = file_destination($destination . $file->filename, $replace);
1601
  }
1602
  catch (RuntimeException $e) {
1603
    drupal_set_message(t('The file %source could not be uploaded because the name is invalid.', array('%source' => $form_field_name)), 'error');
1604
    return FALSE;
1605
  }
1606
  // If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and
1607
  // there's an existing file so we need to bail.
1608
  if ($file->destination === FALSE) {
1609
    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');
1610
    return FALSE;
1611
  }
1612

    
1613
  // Add in our check of the file name length.
1614
  $validators['file_validate_name_length'] = array();
1615

    
1616
  // Call the validation functions specified by this function's caller.
1617
  $errors = file_validate($file, $validators);
1618

    
1619
  // Check for errors.
1620
  if (!empty($errors)) {
1621
    $message = t('The specified file %name could not be uploaded.', array('%name' => $file->filename));
1622
    if (count($errors) > 1) {
1623
      $message .= theme('item_list', array('items' => $errors));
1624
    }
1625
    else {
1626
      $message .= ' ' . array_pop($errors);
1627
    }
1628
    form_set_error($form_field_name, $message);
1629
    return FALSE;
1630
  }
1631

    
1632
  // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary
1633
  // directory. This overcomes open_basedir restrictions for future file
1634
  // operations.
1635
  $file->uri = $file->destination;
1636
  if (!drupal_move_uploaded_file($_FILES['files']['tmp_name'][$form_field_name], $file->uri)) {
1637
    form_set_error($form_field_name, t('File upload error. Could not move uploaded file.'));
1638
    watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->uri));
1639
    return FALSE;
1640
  }
1641

    
1642
  // Set the permissions on the new file.
1643
  drupal_chmod($file->uri);
1644

    
1645
  // If we are replacing an existing file re-use its database record.
1646
  if ($replace == FILE_EXISTS_REPLACE) {
1647
    $existing_files = file_load_multiple(array(), array('uri' => $file->uri));
1648
    if (count($existing_files)) {
1649
      $existing = reset($existing_files);
1650
      $file->fid = $existing->fid;
1651
    }
1652
  }
1653

    
1654
  // If we made it this far it's safe to record this file in the database.
1655
  if ($file = file_save($file)) {
1656
    // Track non-public files in the session if they were uploaded by an
1657
    // anonymous user. This allows modules such as the File module to only
1658
    // grant view access to the specific anonymous user who uploaded the file.
1659
    // See file_file_download().
1660
    // The 'file_public_schema' variable is used to allow other publicly
1661
    // accessible file schemes to be treated the same as the public:// scheme
1662
    // provided by Drupal core and to avoid adding unnecessary data to the
1663
    // session (and the resulting bypass of the page cache) in those cases. For
1664
    // security reasons, only schemes that are completely publicly accessible,
1665
    // with no download restrictions, should be added to this variable. See
1666
    // file_managed_file_value().
1667
    if (!$user->uid && !in_array($destination_scheme, variable_get('file_public_schema', array('public')))) {
1668
      $_SESSION['anonymous_allowed_file_ids'][$file->fid] = $file->fid;
1669
    }
1670
    // Add file to the cache.
1671
    $upload_cache[$form_field_name] = $file;
1672
    return $file;
1673
  }
1674
  return FALSE;
1675
}
1676

    
1677
/**
1678
 * Moves an uploaded file to a new location.
1679
 *
1680
 * PHP's move_uploaded_file() does not properly support streams if safe_mode
1681
 * or open_basedir are enabled, so this function fills that gap.
1682
 *
1683
 * Compatibility: normal paths and stream wrappers.
1684
 *
1685
 * @param $filename
1686
 *   The filename of the uploaded file.
1687
 * @param $uri
1688
 *   A string containing the destination URI of the file.
1689
 *
1690
 * @return
1691
 *   TRUE on success, or FALSE on failure.
1692
 *
1693
 * @see move_uploaded_file()
1694
 * @see http://drupal.org/node/515192
1695
 * @ingroup php_wrappers
1696
 */
1697
function drupal_move_uploaded_file($filename, $uri) {
1698
  $result = @move_uploaded_file($filename, $uri);
1699
  // PHP's move_uploaded_file() does not properly support streams if safe_mode
1700
  // or open_basedir are enabled so if the move failed, try finding a real path
1701
  // and retry the move operation.
1702
  if (!$result) {
1703
    if ($realpath = drupal_realpath($uri)) {
1704
      $result = move_uploaded_file($filename, $realpath);
1705
    }
1706
    else {
1707
      $result = move_uploaded_file($filename, $uri);
1708
    }
1709
  }
1710

    
1711
  return $result;
1712
}
1713

    
1714
/**
1715
 * Checks that a file meets the criteria specified by the validators.
1716
 *
1717
 * After executing the validator callbacks specified hook_file_validate() will
1718
 * also be called to allow other modules to report errors about the file.
1719
 *
1720
 * @param $file
1721
 *   A Drupal file object.
1722
 * @param $validators
1723
 *   An optional, associative array of callback functions used to validate the
1724
 *   file. The keys are function names and the values arrays of callback
1725
 *   parameters which will be passed in after the file object. The
1726
 *   functions should return an array of error messages; an empty array
1727
 *   indicates that the file passed validation. The functions will be called in
1728
 *   the order specified.
1729
 *
1730
 * @return
1731
 *   An array containing validation error messages.
1732
 *
1733
 * @see hook_file_validate()
1734
 */
1735
function file_validate(stdClass &$file, $validators = array()) {
1736
  // Call the validation functions specified by this function's caller.
1737
  $errors = array();
1738
  foreach ($validators as $function => $args) {
1739
    if (function_exists($function)) {
1740
      array_unshift($args, $file);
1741
      $errors = array_merge($errors, call_user_func_array($function, $args));
1742
    }
1743
  }
1744

    
1745
  // Let other modules perform validation on the new file.
1746
  $errors = array_merge($errors, module_invoke_all('file_validate', $file));
1747

    
1748
  // Ensure the file does not contain a malicious extension. At this point
1749
  // file_save_upload() will have munged the file so it does not contain a
1750
  // malicious extension. Contributed and custom code that calls this method
1751
  // needs to take similar steps if they need to permit files with malicious
1752
  // extensions to be uploaded.
1753
  if (empty($errors) && !variable_get('allow_insecure_uploads', 0) && preg_match('/\.(php|phar|pl|py|cgi|asp|js)(\.|$)/i', $file->filename)) {
1754
    $errors[] = t('For security reasons, your upload has been rejected.');
1755
  }
1756

    
1757
  return $errors;
1758
}
1759

    
1760
/**
1761
 * Checks for files with names longer than we can store in the database.
1762
 *
1763
 * @param $file
1764
 *   A Drupal file object.
1765
 *
1766
 * @return
1767
 *   An array. If the file name is too long, it will contain an error message.
1768
 */
1769
function file_validate_name_length(stdClass $file) {
1770
  $errors = array();
1771

    
1772
  if (empty($file->filename)) {
1773
    $errors[] = t("The file's name is empty. Please give a name to the file.");
1774
  }
1775
  if (strlen($file->filename) > 240) {
1776
    $errors[] = t("The file's name exceeds the 240 characters limit. Please rename the file and try again.");
1777
  }
1778
  return $errors;
1779
}
1780

    
1781
/**
1782
 * Checks that the filename ends with an allowed extension.
1783
 *
1784
 * @param $file
1785
 *   A Drupal file object.
1786
 * @param $extensions
1787
 *   A string with a space separated list of allowed extensions.
1788
 *
1789
 * @return
1790
 *   An array. If the file extension is not allowed, it will contain an error
1791
 *   message.
1792
 *
1793
 * @see hook_file_validate()
1794
 */
1795
function file_validate_extensions(stdClass $file, $extensions) {
1796
  $errors = array();
1797

    
1798
  $regex = '/\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
1799
  if (!preg_match($regex, $file->filename)) {
1800
    $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions));
1801
  }
1802
  return $errors;
1803
}
1804

    
1805
/**
1806
 * Checks that the file's size is below certain limits.
1807
 *
1808
 * @param $file
1809
 *   A Drupal file object.
1810
 * @param $file_limit
1811
 *   An integer specifying the maximum file size in bytes. Zero indicates that
1812
 *   no limit should be enforced.
1813
 * @param $user_limit
1814
 *   An integer specifying the maximum number of bytes the user is allowed.
1815
 *   Zero indicates that no limit should be enforced.
1816
 *
1817
 * @return
1818
 *   An array. If the file size exceeds limits, it will contain an error
1819
 *   message.
1820
 *
1821
 * @see hook_file_validate()
1822
 */
1823
function file_validate_size(stdClass $file, $file_limit = 0, $user_limit = 0) {
1824
  global $user;
1825
  $errors = array();
1826

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

    
1831
  // Save a query by only calling file_space_used() when a limit is provided.
1832
  if ($user_limit && (file_space_used($user->uid) + $file->filesize) > $user_limit) {
1833
    $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)));
1834
  }
1835

    
1836
  return $errors;
1837
}
1838

    
1839
/**
1840
 * Checks that the file is recognized by image_get_info() as an image.
1841
 *
1842
 * @param $file
1843
 *   A Drupal file object.
1844
 *
1845
 * @return
1846
 *   An array. If the file is not an image, it will contain an error message.
1847
 *
1848
 * @see hook_file_validate()
1849
 */
1850
function file_validate_is_image(stdClass $file) {
1851
  $errors = array();
1852

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

    
1858
  return $errors;
1859
}
1860

    
1861
/**
1862
 * Verifies that image dimensions are within the specified maximum and minimum.
1863
 *
1864
 * Non-image files will be ignored. If an image toolkit is available the image
1865
 * will be scaled to fit within the desired maximum dimensions.
1866
 *
1867
 * @param $file
1868
 *   A Drupal file object. This function may resize the file affecting its
1869
 *   size.
1870
 * @param $maximum_dimensions
1871
 *   An optional string in the form WIDTHxHEIGHT e.g. '640x480' or '85x85'. If
1872
 *   an image toolkit is installed the image will be resized down to these
1873
 *   dimensions. A value of 0 indicates no restriction on size, so resizing
1874
 *   will be attempted.
1875
 * @param $minimum_dimensions
1876
 *   An optional string in the form WIDTHxHEIGHT. This will check that the
1877
 *   image meets a minimum size. A value of 0 indicates no restriction.
1878
 *
1879
 * @return
1880
 *   An array. If the file is an image and did not meet the requirements, it
1881
 *   will contain an error message.
1882
 *
1883
 * @see hook_file_validate()
1884
 */
1885
function file_validate_image_resolution(stdClass $file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
1886
  $errors = array();
1887

    
1888
  // Check first that the file is an image.
1889
  if ($info = image_get_info($file->uri)) {
1890
    if ($maximum_dimensions) {
1891
      // Check that it is smaller than the given dimensions.
1892
      list($width, $height) = explode('x', $maximum_dimensions);
1893
      if ($info['width'] > $width || $info['height'] > $height) {
1894
        // Try to resize the image to fit the dimensions.
1895
        if ($image = image_load($file->uri)) {
1896
          image_scale($image, $width, $height);
1897
          image_save($image);
1898
          $file->filesize = $image->info['file_size'];
1899
          drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));
1900
        }
1901
        else {
1902
          $errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions));
1903
        }
1904
      }
1905
    }
1906

    
1907
    if ($minimum_dimensions) {
1908
      // Check that it is larger than the given dimensions.
1909
      list($width, $height) = explode('x', $minimum_dimensions);
1910
      if ($info['width'] < $width || $info['height'] < $height) {
1911
        $errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', array('%dimensions' => $minimum_dimensions));
1912
      }
1913
    }
1914
  }
1915

    
1916
  return $errors;
1917
}
1918

    
1919
/**
1920
 * Saves a file to the specified destination and creates a database entry.
1921
 *
1922
 * @param $data
1923
 *   A string containing the contents of the file.
1924
 * @param $destination
1925
 *   A string containing the destination URI. This must be a stream wrapper URI.
1926
 *   If no value is provided, a randomized name will be generated and the file
1927
 *   will be saved using Drupal's default files scheme, usually "public://".
1928
 * @param $replace
1929
 *   Replace behavior when the destination file already exists:
1930
 *   - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
1931
 *       the destination name exists then its database entry will be updated. If
1932
 *       no database entry is found then a new one will be created.
1933
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
1934
 *       unique.
1935
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
1936
 *
1937
 * @return
1938
 *   A file object, or FALSE on error.
1939
 *
1940
 * @see file_unmanaged_save_data()
1941
 */
1942
function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
1943
  global $user;
1944

    
1945
  if (empty($destination)) {
1946
    $destination = file_default_scheme() . '://';
1947
  }
1948
  if (!file_valid_uri($destination)) {
1949
    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));
1950
    drupal_set_message(t('The data could not be saved, because the destination is invalid. More information is available in the system log.'), 'error');
1951
    return FALSE;
1952
  }
1953

    
1954
  if ($uri = file_unmanaged_save_data($data, $destination, $replace)) {
1955
    // Create a file object.
1956
    $file = new stdClass();
1957
    $file->fid = NULL;
1958
    $file->uri = $uri;
1959
    $file->filename = drupal_basename($uri);
1960
    $file->filemime = file_get_mimetype($file->uri);
1961
    $file->uid      = $user->uid;
1962
    $file->status   = FILE_STATUS_PERMANENT;
1963
    // If we are replacing an existing file re-use its database record.
1964
    if ($replace == FILE_EXISTS_REPLACE) {
1965
      $existing_files = file_load_multiple(array(), array('uri' => $uri));
1966
      if (count($existing_files)) {
1967
        $existing = reset($existing_files);
1968
        $file->fid = $existing->fid;
1969
        $file->filename = $existing->filename;
1970
      }
1971
    }
1972
    // If we are renaming around an existing file (rather than a directory),
1973
    // use its basename for the filename.
1974
    elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
1975
      $file->filename = drupal_basename($destination);
1976
    }
1977

    
1978
    return file_save($file);
1979
  }
1980
  return FALSE;
1981
}
1982

    
1983
/**
1984
 * Saves a string to the specified destination without invoking file API.
1985
 *
1986
 * This function is identical to file_save_data() except the file will not be
1987
 * saved to the {file_managed} table and none of the file_* hooks will be
1988
 * called.
1989
 *
1990
 * @param $data
1991
 *   A string containing the contents of the file.
1992
 * @param $destination
1993
 *   A string containing the destination location. This must be a stream wrapper
1994
 *   URI. If no value is provided, a randomized name will be generated and the
1995
 *   file will be saved using Drupal's default files scheme, usually
1996
 *   "public://".
1997
 * @param $replace
1998
 *   Replace behavior when the destination file already exists:
1999
 *   - FILE_EXISTS_REPLACE - Replace the existing file.
2000
 *   - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
2001
 *                          unique.
2002
 *   - FILE_EXISTS_ERROR - Do nothing and return FALSE.
2003
 *
2004
 * @return
2005
 *   A string with the path of the resulting file, or FALSE on error.
2006
 *
2007
 * @see file_save_data()
2008
 */
2009
function file_unmanaged_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
2010
  // Write the data to a temporary file.
2011
  $temp_name = drupal_tempnam('temporary://', 'file');
2012
  if (file_put_contents($temp_name, $data) === FALSE) {
2013
    drupal_set_message(t('The file could not be created.'), 'error');
2014
    return FALSE;
2015
  }
2016

    
2017
  // Move the file to its final destination.
2018
  return file_unmanaged_move($temp_name, $destination, $replace);
2019
}
2020

    
2021
/**
2022
 * Transfers a file to the client using HTTP.
2023
 *
2024
 * Pipes a file through Drupal to the client.
2025
 *
2026
 * @param $uri
2027
 *   String specifying the file URI to transfer.
2028
 * @param $headers
2029
 *   An array of HTTP headers to send along with file.
2030
 */
2031
function file_transfer($uri, $headers) {
2032
  if (ob_get_level()) {
2033
    ob_end_clean();
2034
  }
2035

    
2036
  foreach ($headers as $name => $value) {
2037
    drupal_add_http_header($name, $value);
2038
  }
2039
  drupal_send_headers();
2040
  $scheme = file_uri_scheme($uri);
2041
  // Transfer file in 1024 byte chunks to save memory usage.
2042
  if ($scheme && file_stream_wrapper_valid_scheme($scheme) && $fd = fopen($uri, 'rb')) {
2043
    while (!feof($fd)) {
2044
      print fread($fd, 1024);
2045
    }
2046
    fclose($fd);
2047
  }
2048
  else {
2049
    drupal_not_found();
2050
  }
2051
  drupal_exit();
2052
}
2053

    
2054
/**
2055
 * Menu handler for private file transfers.
2056
 *
2057
 * Call modules that implement hook_file_download() to find out if a file is
2058
 * accessible and what headers it should be transferred with. If one or more
2059
 * modules returned headers the download will start with the returned headers.
2060
 * If a module returns -1 drupal_access_denied() will be returned. If the file
2061
 * exists but no modules responded drupal_access_denied() will be returned.
2062
 * If the file does not exist drupal_not_found() will be returned.
2063
 *
2064
 * @see system_menu()
2065
 */
2066
function file_download() {
2067
  // Merge remainder of arguments from GET['q'], into relative file path.
2068
  $args = func_get_args();
2069
  $scheme = array_shift($args);
2070
  $target = implode('/', $args);
2071
  $uri = $scheme . '://' . $target;
2072
  if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {
2073
    $headers = file_download_headers($uri);
2074
    if (count($headers)) {
2075
      file_transfer($uri, $headers);
2076
    }
2077
    drupal_access_denied();
2078
  }
2079
  else {
2080
    drupal_not_found();
2081
  }
2082
  drupal_exit();
2083
}
2084

    
2085
/**
2086
 * Retrieves headers for a private file download.
2087
 *
2088
 * Calls all module implementations of hook_file_download() to retrieve headers
2089
 * for files by the module that originally provided the file. The presence of
2090
 * returned headers indicates the current user has access to the file.
2091
 *
2092
 * @param $uri
2093
 *   The URI for the file whose headers should be retrieved.
2094
 *
2095
 * @return
2096
 *   If access is allowed, headers for the file, suitable for passing to
2097
 *   file_transfer(). If access is not allowed, an empty array will be returned.
2098
 *
2099
 * @see file_transfer()
2100
 * @see file_download_access()
2101
 * @see hook_file_download()
2102
 */
2103
function file_download_headers($uri) {
2104
  // Let other modules provide headers and control access to the file.
2105
  // module_invoke_all() uses array_merge_recursive() which merges header
2106
  // values into a new array. To avoid that and allow modules to override
2107
  // headers instead, use array_merge() to merge the returned arrays.
2108
  $headers = array();
2109
  foreach (module_implements('file_download') as $module) {
2110
    $function = $module . '_file_download';
2111
    $result = $function($uri);
2112
    if ($result == -1) {
2113
      // Throw away the headers received so far.
2114
      $headers = array();
2115
      break;
2116
    }
2117
    if (isset($result) && is_array($result)) {
2118
      $headers = array_merge($headers, $result);
2119
    }
2120
  }
2121
  return $headers;
2122
}
2123

    
2124
/**
2125
 * Checks that the current user has access to a particular file.
2126
 *
2127
 * The return value of this function hinges on the return value from
2128
 * file_download_headers(), which is the function responsible for collecting
2129
 * access information through hook_file_download().
2130
 *
2131
 * If immediately transferring the file to the browser and the headers will
2132
 * need to be retrieved, the return value of file_download_headers() should be
2133
 * used to determine access directly, so that access checks will not be run
2134
 * twice.
2135
 *
2136
 * @param $uri
2137
 *   The URI for the file whose access should be retrieved.
2138
 *
2139
 * @return
2140
 *   Boolean TRUE if access is allowed. FALSE if access is not allowed.
2141
 *
2142
 * @see file_download_headers()
2143
 * @see hook_file_download()
2144
 */
2145
function file_download_access($uri) {
2146
  return count(file_download_headers($uri)) > 0;
2147
}
2148

    
2149
/**
2150
 * Finds all files that match a given mask in a given directory.
2151
 *
2152
 * Directories and files beginning with a period are excluded; this
2153
 * prevents hidden files and directories (such as SVN working directories)
2154
 * from being scanned.
2155
 *
2156
 * @param $dir
2157
 *   The base directory or URI to scan, without trailing slash.
2158
 * @param $mask
2159
 *   The preg_match() regular expression of the files to find.
2160
 * @param $options
2161
 *   An associative array of additional options, with the following elements:
2162
 *   - 'nomask': The preg_match() regular expression of the files to ignore.
2163
 *     Defaults to '/(\.\.?|CVS)$/'.
2164
 *   - 'callback': The callback function to call for each match. There is no
2165
 *     default callback.
2166
 *   - 'recurse': When TRUE, the directory scan will recurse the entire tree
2167
 *     starting at the provided directory. Defaults to TRUE.
2168
 *   - 'key': The key to be used for the returned associative array of files.
2169
 *     Possible values are 'uri', for the file's URI; 'filename', for the
2170
 *     basename of the file; and 'name' for the name of the file without the
2171
 *     extension. Defaults to 'uri'.
2172
 *   - 'min_depth': Minimum depth of directories to return files from. Defaults
2173
 *     to 0.
2174
 * @param $depth
2175
 *   Current depth of recursion. This parameter is only used internally and
2176
 *   should not be passed in.
2177
 *
2178
 * @return
2179
 *   An associative array (keyed on the chosen key) of objects with 'uri',
2180
 *   'filename', and 'name' members corresponding to the matching files.
2181
 */
2182
function file_scan_directory($dir, $mask, $options = array(), $depth = 0) {
2183
  // Default nomask option.
2184
  $nomask = '/(\.\.?|CVS)$/';
2185

    
2186
  // Overrides the $nomask variable accordingly if $options['nomask'] is set.
2187
  //
2188
  // Allow directories specified in settings.php to be ignored. You can use this
2189
  // to not check for files in common special-purpose directories. For example,
2190
  // node_modules and bower_components. Ignoring irrelevant directories is a
2191
  // performance boost.
2192
  if (!isset($options['nomask'])) {
2193
    $ignore_directories = variable_get(
2194
      'file_scan_ignore_directories',
2195
      array()
2196
    );
2197

    
2198
    foreach ($ignore_directories as $index => $ignore_directory) {
2199
      $ignore_directories[$index] = preg_quote($ignore_directory, '/');
2200
    }
2201

    
2202
    if (!empty($ignore_directories)) {
2203
      $nomask = '/^(\.\.?)|CVS|' . implode('|', $ignore_directories) . '$/';
2204
    }
2205
  }
2206

    
2207
  // Merge in defaults.
2208
  $options += array(
2209
    'nomask' => $nomask,
2210
    'callback' => 0,
2211
    'recurse' => TRUE,
2212
    'key' => 'uri',
2213
    'min_depth' => 0,
2214
  );
2215

    
2216
  $options['key'] = in_array($options['key'], array('uri', 'filename', 'name')) ? $options['key'] : 'uri';
2217
  $files = array();
2218
  if (is_dir($dir) && $handle = opendir($dir)) {
2219
    while (FALSE !== ($filename = readdir($handle))) {
2220
      if (!preg_match($options['nomask'], $filename) && $filename[0] != '.') {
2221
        $uri = "$dir/$filename";
2222
        $uri = file_stream_wrapper_uri_normalize($uri);
2223
        if (is_dir($uri) && $options['recurse']) {
2224
          // Give priority to files in this folder by merging them in after any subdirectory files.
2225
          $files = array_merge(file_scan_directory($uri, $mask, $options, $depth + 1), $files);
2226
        }
2227
        elseif ($depth >= $options['min_depth'] && preg_match($mask, $filename)) {
2228
          // Always use this match over anything already set in $files with the
2229
          // same $$options['key'].
2230
          $file = new stdClass();
2231
          $file->uri = $uri;
2232
          $file->filename = $filename;
2233
          $file->name = pathinfo($filename, PATHINFO_FILENAME);
2234
          $key = $options['key'];
2235
          $files[$file->$key] = $file;
2236
          if ($options['callback']) {
2237
            $options['callback']($uri);
2238
          }
2239
        }
2240
      }
2241
    }
2242

    
2243
    closedir($handle);
2244
  }
2245

    
2246
  return $files;
2247
}
2248

    
2249
/**
2250
 * Determines the maximum file upload size by querying the PHP settings.
2251
 *
2252
 * @return
2253
 *   A file size limit in bytes based on the PHP upload_max_filesize and
2254
 *   post_max_size
2255
 */
2256
function file_upload_max_size() {
2257
  static $max_size = -1;
2258

    
2259
  if ($max_size < 0) {
2260
    // Start with post_max_size.
2261
    $max_size = parse_size(ini_get('post_max_size'));
2262

    
2263
    // If upload_max_size is less, then reduce. Except if upload_max_size is
2264
    // zero, which indicates no limit.
2265
    $upload_max = parse_size(ini_get('upload_max_filesize'));
2266
    if ($upload_max > 0 && $upload_max < $max_size) {
2267
      $max_size = $upload_max;
2268
    }
2269
  }
2270
  return $max_size;
2271
}
2272

    
2273
/**
2274
 * Determines an Internet Media Type or MIME type from a filename.
2275
 *
2276
 * @param $uri
2277
 *   A string containing the URI, path, or filename.
2278
 * @param $mapping
2279
 *   An optional map of extensions to their mimetypes, in the form:
2280
 *    - 'mimetypes': a list of mimetypes, keyed by an identifier,
2281
 *    - 'extensions': the mapping itself, an associative array in which
2282
 *      the key is the extension (lowercase) and the value is the mimetype
2283
 *      identifier. If $mapping is NULL file_mimetype_mapping() is called.
2284
 *
2285
 * @return
2286
 *   The internet media type registered for the extension or
2287
 *   application/octet-stream for unknown extensions.
2288
 *
2289
 * @see file_default_mimetype_mapping()
2290
 */
2291
function file_get_mimetype($uri, $mapping = NULL) {
2292
  if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
2293
    return $wrapper->getMimeType($uri, $mapping);
2294
  }
2295
  else {
2296
    // getMimeType() is not implementation specific, so we can directly
2297
    // call it without an instance.
2298
    return DrupalLocalStreamWrapper::getMimeType($uri, $mapping);
2299
  }
2300
}
2301

    
2302
/**
2303
 * Sets the permissions on a file or directory.
2304
 *
2305
 * This function will use the 'file_chmod_directory' and 'file_chmod_file'
2306
 * variables for the default modes for directories and uploaded/generated
2307
 * files. By default these will give everyone read access so that users
2308
 * accessing the files with a user account without the webserver group (e.g.
2309
 * via FTP) can read these files, and give group write permissions so webserver
2310
 * group members (e.g. a vhost account) can alter files uploaded and owned by
2311
 * the webserver.
2312
 *
2313
 * PHP's chmod does not support stream wrappers so we use our wrapper
2314
 * implementation which interfaces with chmod() by default. Contrib wrappers
2315
 * may override this behavior in their implementations as needed.
2316
 *
2317
 * @param $uri
2318
 *   A string containing a URI file, or directory path.
2319
 * @param $mode
2320
 *   Integer value for the permissions. Consult PHP chmod() documentation for
2321
 *   more information.
2322
 *
2323
 * @return
2324
 *   TRUE for success, FALSE in the event of an error.
2325
 *
2326
 * @ingroup php_wrappers
2327
 */
2328
function drupal_chmod($uri, $mode = NULL) {
2329
  if (!isset($mode)) {
2330
    if (is_dir($uri)) {
2331
      $mode = variable_get('file_chmod_directory', 0775);
2332
    }
2333
    else {
2334
      $mode = variable_get('file_chmod_file', 0664);
2335
    }
2336
  }
2337

    
2338
  // If this URI is a stream, pass it off to the appropriate stream wrapper.
2339
  // Otherwise, attempt PHP's chmod. This allows use of drupal_chmod even
2340
  // for unmanaged files outside of the stream wrapper interface.
2341
  if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
2342
    if ($wrapper->chmod($mode)) {
2343
      return TRUE;
2344
    }
2345
  }
2346
  else {
2347
    if (@chmod($uri, $mode)) {
2348
      return TRUE;
2349
    }
2350
  }
2351

    
2352
  watchdog('file', 'The file permissions could not be set on %uri.', array('%uri' => $uri), WATCHDOG_ERROR);
2353
  return FALSE;
2354
}
2355

    
2356
/**
2357
 * Deletes a file.
2358
 *
2359
 * PHP's unlink() is broken on Windows, as it can fail to remove a file
2360
 * when it has a read-only flag set.
2361
 *
2362
 * @param $uri
2363
 *   A URI or pathname.
2364
 * @param $context
2365
 *   Refer to http://php.net/manual/ref.stream.php
2366
 *
2367
 * @return
2368
 *   Boolean TRUE on success, or FALSE on failure.
2369
 *
2370
 * @see unlink()
2371
 * @ingroup php_wrappers
2372
 */
2373
function drupal_unlink($uri, $context = NULL) {
2374
  $scheme = file_uri_scheme($uri);
2375
  if ((!$scheme || !file_stream_wrapper_valid_scheme($scheme)) && (substr(PHP_OS, 0, 3) == 'WIN')) {
2376
    chmod($uri, 0600);
2377
  }
2378
  if ($context) {
2379
    return unlink($uri, $context);
2380
  }
2381
  else {
2382
    return unlink($uri);
2383
  }
2384
}
2385

    
2386
/**
2387
 * Resolves the absolute filepath of a local URI or filepath.
2388
 *
2389
 * The use of drupal_realpath() is discouraged, because it does not work for
2390
 * remote URIs. Except in rare cases, URIs should not be manually resolved.
2391
 *
2392
 * Only use this function if you know that the stream wrapper in the URI uses
2393
 * the local file system, and you need to pass an absolute path to a function
2394
 * that is incompatible with stream URIs.
2395
 *
2396
 * @param string $uri
2397
 *   A stream wrapper URI or a filepath, possibly including one or more symbolic
2398
 *   links.
2399
 *
2400
 * @return string|false
2401
 *   The absolute local filepath (with no symbolic links), or FALSE on failure.
2402
 *
2403
 * @see DrupalStreamWrapperInterface::realpath()
2404
 * @see http://php.net/manual/function.realpath.php
2405
 * @ingroup php_wrappers
2406
 */
2407
function drupal_realpath($uri) {
2408
  // If this URI is a stream, pass it off to the appropriate stream wrapper.
2409
  // Otherwise, attempt PHP's realpath. This allows use of drupal_realpath even
2410
  // for unmanaged files outside of the stream wrapper interface.
2411
  if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
2412
    return $wrapper->realpath();
2413
  }
2414
  // Check that the URI has a value. There is a bug in PHP 5.2 on *BSD systems
2415
  // that makes realpath not return FALSE as expected when passing an empty
2416
  // variable.
2417
  // @todo Remove when Drupal drops support for PHP 5.2.
2418
  elseif (!empty($uri)) {
2419
    return realpath($uri);
2420
  }
2421
  return FALSE;
2422
}
2423

    
2424
/**
2425
 * Gets the name of the directory from a given path.
2426
 *
2427
 * PHP's dirname() does not properly pass streams, so this function fills
2428
 * that gap. It is backwards compatible with normal paths and will use
2429
 * PHP's dirname() as a fallback.
2430
 *
2431
 * Compatibility: normal paths and stream wrappers.
2432
 *
2433
 * @param $uri
2434
 *   A URI or path.
2435
 *
2436
 * @return
2437
 *   A string containing the directory name.
2438
 *
2439
 * @see dirname()
2440
 * @see http://drupal.org/node/515192
2441
 * @ingroup php_wrappers
2442
 */
2443
function drupal_dirname($uri) {
2444
  $scheme = file_uri_scheme($uri);
2445

    
2446
  if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
2447
    return file_stream_wrapper_get_instance_by_scheme($scheme)->dirname($uri);
2448
  }
2449
  else {
2450
    return dirname($uri);
2451
  }
2452
}
2453

    
2454
/**
2455
 * Gets the filename from a given path.
2456
 *
2457
 * PHP's basename() does not properly support streams or filenames beginning
2458
 * with a non-US-ASCII character.
2459
 *
2460
 * @see http://bugs.php.net/bug.php?id=37738
2461
 * @see basename()
2462
 *
2463
 * @ingroup php_wrappers
2464
 */
2465
function drupal_basename($uri, $suffix = NULL) {
2466
  $separators = '/';
2467
  if (DIRECTORY_SEPARATOR != '/') {
2468
    // For Windows OS add special separator.
2469
    $separators .= DIRECTORY_SEPARATOR;
2470
  }
2471
  // Remove right-most slashes when $uri points to directory.
2472
  $uri = rtrim($uri, $separators);
2473
  // Returns the trailing part of the $uri starting after one of the directory
2474
  // separators.
2475
  $filename = preg_match('@[^' . preg_quote($separators, '@') . ']+$@', $uri, $matches) ? $matches[0] : '';
2476
  // Cuts off a suffix from the filename.
2477
  if ($suffix) {
2478
    $filename = preg_replace('@' . preg_quote($suffix, '@') . '$@', '', $filename);
2479
  }
2480
  return $filename;
2481
}
2482

    
2483
/**
2484
 * Creates a directory using Drupal's default mode.
2485
 *
2486
 * PHP's mkdir() does not respect Drupal's default permissions mode. If a mode
2487
 * is not provided, this function will make sure that Drupal's is used.
2488
 *
2489
 * Compatibility: normal paths and stream wrappers.
2490
 *
2491
 * @param $uri
2492
 *   A URI or pathname.
2493
 * @param $mode
2494
 *   By default the Drupal mode is used.
2495
 * @param $recursive
2496
 *   Default to FALSE.
2497
 * @param $context
2498
 *   Refer to http://php.net/manual/ref.stream.php
2499
 *
2500
 * @return
2501
 *   Boolean TRUE on success, or FALSE on failure.
2502
 *
2503
 * @see mkdir()
2504
 * @see http://drupal.org/node/515192
2505
 * @ingroup php_wrappers
2506
 */
2507
function drupal_mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL) {
2508
  if (!isset($mode)) {
2509
    $mode = variable_get('file_chmod_directory', 0775);
2510
  }
2511

    
2512
  if (!isset($context)) {
2513
    return mkdir($uri, $mode, $recursive);
2514
  }
2515
  else {
2516
    return mkdir($uri, $mode, $recursive, $context);
2517
  }
2518
}
2519

    
2520
/**
2521
 * Removes a directory.
2522
 *
2523
 * PHP's rmdir() is broken on Windows, as it can fail to remove a directory
2524
 * when it has a read-only flag set.
2525
 *
2526
 * @param $uri
2527
 *   A URI or pathname.
2528
 * @param $context
2529
 *   Refer to http://php.net/manual/ref.stream.php
2530
 *
2531
 * @return
2532
 *   Boolean TRUE on success, or FALSE on failure.
2533
 *
2534
 * @see rmdir()
2535
 * @ingroup php_wrappers
2536
 */
2537
function drupal_rmdir($uri, $context = NULL) {
2538
  $scheme = file_uri_scheme($uri);
2539
  if ((!$scheme || !file_stream_wrapper_valid_scheme($scheme)) && (substr(PHP_OS, 0, 3) == 'WIN')) {
2540
    chmod($uri, 0700);
2541
  }
2542
  if ($context) {
2543
    return rmdir($uri, $context);
2544
  }
2545
  else {
2546
    return rmdir($uri);
2547
  }
2548
}
2549

    
2550
/**
2551
 * Creates a file with a unique filename in the specified directory.
2552
 *
2553
 * PHP's tempnam() does not return a URI like we want. This function
2554
 * will return a URI if given a URI, or it will return a filepath if
2555
 * given a filepath.
2556
 *
2557
 * Compatibility: normal paths and stream wrappers.
2558
 *
2559
 * @param $directory
2560
 *   The directory where the temporary filename will be created.
2561
 * @param $prefix
2562
 *   The prefix of the generated temporary filename.
2563
 *   Note: Windows uses only the first three characters of prefix.
2564
 *
2565
 * @return
2566
 *   The new temporary filename, or FALSE on failure.
2567
 *
2568
 * @see tempnam()
2569
 * @see http://drupal.org/node/515192
2570
 * @ingroup php_wrappers
2571
 */
2572
function drupal_tempnam($directory, $prefix) {
2573
  $scheme = file_uri_scheme($directory);
2574

    
2575
  if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
2576
    $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
2577

    
2578
    if ($filename = tempnam($wrapper->getDirectoryPath(), $prefix)) {
2579
      return $scheme . '://' . drupal_basename($filename);
2580
    }
2581
    else {
2582
      return FALSE;
2583
    }
2584
  }
2585
  else {
2586
    // Handle as a normal tempnam() call.
2587
    return tempnam($directory, $prefix);
2588
  }
2589
}
2590

    
2591
/**
2592
 * Gets the path of system-appropriate temporary directory.
2593
 */
2594
function file_directory_temp() {
2595
  $temporary_directory = variable_get('file_temporary_path', NULL);
2596

    
2597
  if (empty($temporary_directory)) {
2598
    $directories = array();
2599

    
2600
    // Has PHP been set with an upload_tmp_dir?
2601
    if (ini_get('upload_tmp_dir')) {
2602
      $directories[] = ini_get('upload_tmp_dir');
2603
    }
2604

    
2605
    // Operating system specific dirs.
2606
    if (substr(PHP_OS, 0, 3) == 'WIN') {
2607
      $directories[] = 'c:\\windows\\temp';
2608
      $directories[] = 'c:\\winnt\\temp';
2609
    }
2610
    else {
2611
      $directories[] = '/tmp';
2612
    }
2613
    // PHP may be able to find an alternative tmp directory.
2614
    // This function exists in PHP 5 >= 5.2.1, but Drupal
2615
    // requires PHP 5 >= 5.2.0, so we check for it.
2616
    if (function_exists('sys_get_temp_dir')) {
2617
      $directories[] = sys_get_temp_dir();
2618
    }
2619

    
2620
    foreach ($directories as $directory) {
2621
      if (is_dir($directory) && is_writable($directory)) {
2622
        $temporary_directory = $directory;
2623
        break;
2624
      }
2625
    }
2626

    
2627
    if (empty($temporary_directory)) {
2628
      // If no directory has been found default to 'files/tmp'.
2629
      $temporary_directory = variable_get('file_public_path', conf_path() . '/files') . '/tmp';
2630

    
2631
      // Windows accepts paths with either slash (/) or backslash (\), but will
2632
      // not accept a path which contains both a slash and a backslash. Since
2633
      // the 'file_public_path' variable may have either format, we sanitize
2634
      // everything to use slash which is supported on all platforms.
2635
      $temporary_directory = str_replace('\\', '/', $temporary_directory);
2636
    }
2637
    // Save the path of the discovered directory.
2638
    variable_set('file_temporary_path', $temporary_directory);
2639
  }
2640

    
2641
  return $temporary_directory;
2642
}
2643

    
2644
/**
2645
 * Examines a file object and returns appropriate content headers for download.
2646
 *
2647
 * @param $file
2648
 *   A file object.
2649
 *
2650
 * @return
2651
 *   An associative array of headers, as expected by file_transfer().
2652
 */
2653
function file_get_content_headers($file) {
2654
  $type = mime_header_encode($file->filemime);
2655

    
2656
  return array(
2657
    'Content-Type' => $type,
2658
    'Content-Length' => $file->filesize,
2659
    'Cache-Control' => 'private',
2660
  );
2661
}
2662

    
2663
/**
2664
 * @} End of "defgroup file".
2665
 */