Skip navigation
Help

file.inc

  1. drupal
    1. 6 drupal/includes/file.inc
    2. 7 drupal/includes/file.inc

API for handling file uploads and server file management.

Functions & methods

NameDescription
drupal_chmodSet the permissions on a file or directory.
drupal_dirnameGets the name of the directory from a given path.
drupal_mkdirCreates a directory using Drupal's default mode.
drupal_realpathReturns the absolute path of a file or directory
drupal_rmdirRemove a directory.
drupal_tempnamCreates a file with a unique filename in the specified directory.
drupal_unlinkDeletes a file.
file_build_uriGiven a relative path, construct a URI into Drupal's default files location.
file_copyCopies a file to a new location and adds a file record to the database.
file_create_filenameCreate a full file path from a directory and filename.
file_create_htaccessCreates an .htaccess file in the given directory.
file_create_urlCreates a web-accessible URL for a stream to an external or local file.
file_default_schemeGet the default file stream implementation.
file_deleteDelete a file and its database record.
file_destinationDetermines the destination path for a file depending on how replacement of existing files should be handled.
file_directory_tempGet the path of system-appropriate temporary directory.
file_downloadMenu handler for private file transfers.
file_ensure_htaccessIf missing, create a .htaccess file in each Drupal files directory.
file_get_content_headersExamines a file object and returns appropriate content headers for download.
file_get_mimetypeDetermine an Internet Media Type, or MIME type from a filename.
file_get_stream_wrappersDrupal stream wrapper registry.
file_loadLoad a file object from the database.
file_load_multipleLoads file objects from the database.
file_moveMove a file to a new location and update the file's database entry.
file_munge_filenameModify a filename as needed for security purposes.
file_prepare_directoryCheck that the directory exists and is writable.
file_saveSave a file object to the database.
file_save_dataSave a string to the specified destination and create a database file entry.
file_save_uploadSaves a file upload to a new location.
file_scan_directoryFinds all files that match a given mask in a given directory.
file_space_usedDetermine total disk space used by a single user or the whole filesystem.
file_stream_wrapper_get_classReturns the stream wrapper class name for a given scheme.
file_stream_wrapper_get_instance_by_schemeReturns a reference to the stream wrapper class responsible for a given scheme.
file_stream_wrapper_get_instance_by_uriReturns a reference to the stream wrapper class responsible for a given URI.
file_stream_wrapper_uri_normalizeNormalizes a URI by making it syntactically correct.
file_stream_wrapper_valid_schemeCheck that the scheme of a stream URI is valid.
file_transferTransfer file using HTTP to client.
file_unmanaged_copyCopies a file to a new location without invoking the file API.
file_unmanaged_deleteDelete a file without calling any hooks or making any changes to the database.
file_unmanaged_delete_recursiveRecursively delete all files and directories in the specified filepath.
file_unmanaged_moveMove a file to a new location without calling any hooks or making any changes to the database.
file_unmanaged_save_dataSave a string to the specified destination without invoking file API.
file_unmunge_filenameUndo the effect of upload_munge_filename().
file_upload_max_sizeDetermine the maximum file upload size by querying the PHP settings.
file_uri_schemeReturns the scheme of a URI (e.g. a stream).
file_uri_targetReturns the part of an URI after the schema.
file_usage_addRecords that a module is using a file.
file_usage_deleteRemoves a record to indicate that a module is no longer using a file.
file_usage_listDetermines where a file is used.
file_validateCheck that a file meets the criteria specified by the validators.
file_validate_extensionsCheck that the filename ends with an allowed extension.
file_validate_image_resolutionVerify that image dimensions are within the specified maximum and minimum.
file_validate_is_imageCheck that the file is recognized by image_get_info() as an image.
file_validate_name_lengthCheck for files with names longer than we can store in the database.
file_validate_sizeCheck that the file's size is below certain limits.
file_valid_uriDetermine whether the URI has a valid scheme for file API operations.

Constants

NameDescription
FILE_CREATE_DIRECTORYFlag used by file_prepare_directory() -- create directory if not present.
FILE_EXISTS_ERRORFlag for dealing with existing files: Do nothing and return FALSE.
FILE_EXISTS_RENAMEFlag for dealing with existing files: Appends number until name is unique.
FILE_EXISTS_REPLACEFlag for dealing with existing files: Replace the existing file.
FILE_MODIFY_PERMISSIONSFlag used by file_prepare_directory() -- file permissions may be changed.
FILE_STATUS_PERMANENTIndicates that the file is permanent and should not be deleted.

File

drupal/includes/file.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * API for handling file uploads and server file management.
  5. */
  6. /**
  7. * Manually include stream wrapper code.
  8. *
  9. * Stream wrapper code is included here because there are cases where
  10. * File API is needed before a bootstrap, or in an alternate order (e.g.
  11. * maintenance theme).
  12. */
  13. require_once DRUPAL_ROOT . '/includes/stream_wrappers.inc';
  14. /**
  15. * @defgroup file File interface
  16. * @{
  17. * Common file handling functions.
  18. *
  19. * Fields on the file object:
  20. * - fid: File ID
  21. * - uid: The {users}.uid of the user who is associated with the file.
  22. * - filename: Name of the file with no path components. This may differ from
  23. * the basename of the filepath if the file is renamed to avoid overwriting
  24. * an existing file.
  25. * - uri: URI of the file.
  26. * - filemime: The file's MIME type.
  27. * - filesize: The size of the file in bytes.
  28. * - status: A bitmapped field indicating the status of the file. The first 8
  29. * bits are reserved for Drupal core. The least significant bit indicates
  30. * temporary (0) or permanent (1). Temporary files older than
  31. * DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed during cron runs.
  32. * - timestamp: UNIX timestamp for the date the file was added to the database.
  33. */
  34. /**
  35. * Flag used by file_prepare_directory() -- create directory if not present.
  36. */
  37. define('FILE_CREATE_DIRECTORY', 1);
  38. /**
  39. * Flag used by file_prepare_directory() -- file permissions may be changed.
  40. */
  41. define('FILE_MODIFY_PERMISSIONS', 2);
  42. /**
  43. * Flag for dealing with existing files: Appends number until name is unique.
  44. */
  45. define('FILE_EXISTS_RENAME', 0);
  46. /**
  47. * Flag for dealing with existing files: Replace the existing file.
  48. */
  49. define('FILE_EXISTS_REPLACE', 1);
  50. /**
  51. * Flag for dealing with existing files: Do nothing and return FALSE.
  52. */
  53. define('FILE_EXISTS_ERROR', 2);
  54. /**
  55. * Indicates that the file is permanent and should not be deleted.
  56. *
  57. * Temporary files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed
  58. * during cron runs, but permanent files will not be removed during the file
  59. * garbage collection process.
  60. */
  61. define('FILE_STATUS_PERMANENT', 1);
  62. /**
  63. * Methods to manage a registry of stream wrappers.
  64. */
  65. /**
  66. * Drupal stream wrapper registry.
  67. *
  68. * A stream wrapper is an abstraction of a file system that allows Drupal to
  69. * use the same set of methods to access both local files and remote resources.
  70. *
  71. * Provide a facility for managing and querying user-defined stream wrappers
  72. * in PHP. PHP's internal stream_get_wrappers() doesn't return the class
  73. * registered to handle a stream, which we need to be able to find the handler
  74. * for class instantiation.
  75. *
  76. * If a module registers a scheme that is already registered with PHP, the
  77. * existing scheme will be unregistered and replaced with the specified class.
  78. *
  79. * A stream is referenced as "scheme://target".
  80. *
  81. * The optional $filter parameter can be used to retrieve only the stream
  82. * wrappers that are appropriate for particular usage. For example, this returns
  83. * only stream wrappers that use local file storage:
  84. * @code
  85. * $local_stream_wrappers = file_get_stream_wrappers(STEAM_WRAPPERS_LOCAL);
  86. * @endcode
  87. *
  88. * The $filter parameter can only filter to types containing a particular flag.
  89. * In some cases, you may want to filter to types that do not contain a
  90. * particular flag. For example, you may want to retrieve all stream wrappers
  91. * that are not writable, or all stream wrappers that are not local. PHP's
  92. * array_diff_key() function can be used to help with this. For example, this
  93. * returns only stream wrappers that do not use local file storage:
  94. * @code
  95. * $remote_stream_wrappers = array_diff_key(file_get_stream_wrappers(STREAM_WRAPPERS_ALL), file_get_stream_wrappers(STEAM_WRAPPERS_LOCAL));
  96. * @endcode
  97. *
  98. * @param $filter
  99. * (Optional) Filters out all types except those with an on bit for each on
  100. * bit in $filter. For example, if $filter is STREAM_WRAPPERS_WRITE_VISIBLE,
  101. * which is equal to (STREAM_WRAPPERS_READ | STREAM_WRAPPERS_WRITE |
  102. * STREAM_WRAPPERS_VISIBLE), then only stream wrappers with all three of these
  103. * bits set are returned. Defaults to STREAM_WRAPPERS_ALL, which returns all
  104. * registered stream wrappers.
  105. *
  106. * @return
  107. * An array keyed by scheme, with values containing an array of information
  108. * about the stream wrapper, as returned by hook_stream_wrappers(). If $filter
  109. * is omitted or set to STREAM_WRAPPERS_ALL, the entire Drupal stream wrapper
  110. * registry is returned. Otherwise only the stream wrappers whose 'type'
  111. * bitmask has an on bit for each bit specified in $filter are returned.
  112. *
  113. * @see hook_stream_wrappers()
  114. * @see hook_stream_wrappers_alter()
  115. */
  116. function file_get_stream_wrappers($filter = STREAM_WRAPPERS_ALL) {
  117. $wrappers_storage = &drupal_static(__FUNCTION__);
  118. if (!isset($wrappers_storage)) {
  119. $wrappers = module_invoke_all('stream_wrappers');
  120. foreach ($wrappers as $scheme => $info) {
  121. // Add defaults.
  122. $wrappers[$scheme] += array('type' => STREAM_WRAPPERS_NORMAL);
  123. }
  124. drupal_alter('stream_wrappers', $wrappers);
  125. $existing = stream_get_wrappers();
  126. foreach ($wrappers as $scheme => $info) {
  127. // We only register classes that implement our interface.
  128. if (in_array('DrupalStreamWrapperInterface', class_implements($info['class']), TRUE)) {
  129. // Record whether we are overriding an existing scheme.
  130. if (in_array($scheme, $existing, TRUE)) {
  131. $wrappers[$scheme]['override'] = TRUE;
  132. stream_wrapper_unregister($scheme);
  133. }
  134. else {
  135. $wrappers[$scheme]['override'] = FALSE;
  136. }
  137. if (($info['type'] & STREAM_WRAPPERS_LOCAL) == STREAM_WRAPPERS_LOCAL) {
  138. stream_wrapper_register($scheme, $info['class']);
  139. }
  140. else {
  141. stream_wrapper_register($scheme, $info['class'], STREAM_IS_URL);
  142. }
  143. }
  144. // Pre-populate the static cache with the filters most typically used.
  145. $wrappers_storage[STREAM_WRAPPERS_ALL][$scheme] = $wrappers[$scheme];
  146. if (($info['type'] & STREAM_WRAPPERS_WRITE_VISIBLE) == STREAM_WRAPPERS_WRITE_VISIBLE) {
  147. $wrappers_storage[STREAM_WRAPPERS_WRITE_VISIBLE][$scheme] = $wrappers[$scheme];
  148. }
  149. }
  150. }
  151. if (!isset($wrappers_storage[$filter])) {
  152. $wrappers_storage[$filter] = array();
  153. foreach ($wrappers_storage[STREAM_WRAPPERS_ALL] as $scheme => $info) {
  154. // Bit-wise filter.
  155. if (($info['type'] & $filter) == $filter) {
  156. $wrappers_storage[$filter][$scheme] = $info;
  157. }
  158. }
  159. }
  160. return $wrappers_storage[$filter];
  161. }
  162. /**
  163. * Returns the stream wrapper class name for a given scheme.
  164. *
  165. * @param $scheme
  166. * Stream scheme.
  167. *
  168. * @return
  169. * Return string if a scheme has a registered handler, or FALSE.
  170. */
  171. function file_stream_wrapper_get_class($scheme) {
  172. $wrappers = file_get_stream_wrappers();
  173. return empty($wrappers[$scheme]) ? FALSE : $wrappers[$scheme]['class'];
  174. }
  175. /**
  176. * Returns the scheme of a URI (e.g. a stream).
  177. *
  178. * @param $uri
  179. * A stream, referenced as "scheme://target".
  180. *
  181. * @return
  182. * A string containing the name of the scheme, or FALSE if none. For example,
  183. * the URI "public://example.txt" would return "public".
  184. *
  185. * @see file_uri_target()
  186. */
  187. function file_uri_scheme($uri) {
  188. $position = strpos($uri, '://');
  189. return $position ? substr($uri, 0, $position) : FALSE;
  190. }
  191. /**
  192. * Check that the scheme of a stream URI is valid.
  193. *
  194. * Confirms that there is a registered stream handler for the provided scheme
  195. * and that it is callable. This is useful if you want to confirm a valid
  196. * scheme without creating a new instance of the registered handler.
  197. *
  198. * @param $scheme
  199. * A URI scheme, a stream is referenced as "scheme://target".
  200. *
  201. * @return
  202. * Returns TRUE if the string is the name of a validated stream,
  203. * or FALSE if the scheme does not have a registered handler.
  204. */
  205. function file_stream_wrapper_valid_scheme($scheme) {
  206. // Does the scheme have a registered handler that is callable?
  207. $class = file_stream_wrapper_get_class($scheme);
  208. if (class_exists($class)) {
  209. return TRUE;
  210. }
  211. else {
  212. return FALSE;
  213. }
  214. }
  215. /**
  216. * Returns the part of an URI after the schema.
  217. *
  218. * @param $uri
  219. * A stream, referenced as "scheme://target".
  220. *
  221. * @return
  222. * A string containing the target (path), or FALSE if none.
  223. * For example, the URI "public://sample/test.txt" would return
  224. * "sample/test.txt".
  225. *
  226. * @see file_uri_scheme()
  227. */
  228. function file_uri_target($uri) {
  229. $data = explode('://', $uri, 2);
  230. // Remove erroneous leading or trailing, forward-slashes and backslashes.
  231. return count($data) == 2 ? trim($data[1], '\/') : FALSE;
  232. }
  233. /**
  234. * Get the default file stream implementation.
  235. *
  236. * @return
  237. * 'public', 'private' or any other file scheme defined as the default.
  238. */
  239. function file_default_scheme() {
  240. return variable_get('file_default_scheme', 'public');
  241. }
  242. /**
  243. * Normalizes a URI by making it syntactically correct.
  244. *
  245. * A stream is referenced as "scheme://target".
  246. *
  247. * The following actions are taken:
  248. * - Remove trailing slashes from target
  249. * - Trim erroneous leading slashes from target. e.g. ":///" becomes "://".
  250. *
  251. * @param $uri
  252. * String reference containing the URI to normalize.
  253. *
  254. * @return
  255. * The normalized URI.
  256. */
  257. function file_stream_wrapper_uri_normalize($uri) {
  258. $scheme = file_uri_scheme($uri);
  259. if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
  260. $target = file_uri_target($uri);
  261. if ($target !== FALSE) {
  262. $uri = $scheme . '://' . $target;
  263. }
  264. }
  265. else {
  266. // The default scheme is file://
  267. $url = 'file://' . $uri;
  268. }
  269. return $uri;
  270. }
  271. /**
  272. * Returns a reference to the stream wrapper class responsible for a given URI.
  273. *
  274. * The scheme determines the stream wrapper class that should be
  275. * used by consulting the stream wrapper registry.
  276. *
  277. * @param $uri
  278. * A stream, referenced as "scheme://target".
  279. *
  280. * @return
  281. * Returns a new stream wrapper object appropriate for the given URI or FALSE
  282. * if no registered handler could be found. For example, a URI of
  283. * "private://example.txt" would return a new private stream wrapper object
  284. * (DrupalPrivateStreamWrapper).
  285. */
  286. function file_stream_wrapper_get_instance_by_uri($uri) {
  287. $scheme = file_uri_scheme($uri);
  288. $class = file_stream_wrapper_get_class($scheme);
  289. if (class_exists($class)) {
  290. $instance = new $class();
  291. $instance->setUri($uri);
  292. return $instance;
  293. }
  294. else {
  295. return FALSE;
  296. }
  297. }
  298. /**
  299. * Returns a reference to the stream wrapper class responsible for a given scheme.
  300. *
  301. * This helper method returns a stream instance using a scheme. That is, the
  302. * passed string does not contain a "://". For example, "public" is a scheme
  303. * but "public://" is a URI (stream). This is because the later contains both
  304. * a scheme and target despite target being empty.
  305. *
  306. * Note: the instance URI will be initialized to "scheme://" so that you can
  307. * make the customary method calls as if you had retrieved an instance by URI.
  308. *
  309. * @param $scheme
  310. * If the stream was "public://target", "public" would be the scheme.
  311. *
  312. * @return
  313. * Returns a new stream wrapper object appropriate for the given $scheme.
  314. * For example, for the public scheme a stream wrapper object
  315. * (DrupalPublicStreamWrapper).
  316. * FALSE is returned if no registered handler could be found.
  317. */
  318. function file_stream_wrapper_get_instance_by_scheme($scheme) {
  319. $class = file_stream_wrapper_get_class($scheme);
  320. if (class_exists($class)) {
  321. $instance = new $class();
  322. $instance->setUri($scheme . '://');
  323. return $instance;
  324. }
  325. else {
  326. return FALSE;
  327. }
  328. }
  329. /**
  330. * Creates a web-accessible URL for a stream to an external or local file.
  331. *
  332. * Compatibility: normal paths and stream wrappers.
  333. * @see http://drupal.org/node/515192
  334. *
  335. * There are two kinds of local files:
  336. * - "managed files", i.e. those stored by a Drupal-compatible stream wrapper.
  337. * These are files that have either been uploaded by users or were generated
  338. * automatically (for example through CSS aggregation).
  339. * - "shipped files", i.e. those outside of the files directory, which ship as
  340. * part of Drupal core or contributed modules or themes.
  341. *
  342. * @param $uri
  343. * The URI to a file for which we need an external URL, or the path to a
  344. * shipped file.
  345. *
  346. * @return
  347. * A string containing a URL that may be used to access the file.
  348. * If the provided string already contains a preceding 'http', 'https', or
  349. * '/', nothing is done and the same string is returned. If a stream wrapper
  350. * could not be found to generate an external URL, then FALSE is returned.
  351. */
  352. function file_create_url($uri) {
  353. // Allow the URI to be altered, e.g. to serve a file from a CDN or static
  354. // file server.
  355. drupal_alter('file_url', $uri);
  356. $scheme = file_uri_scheme($uri);
  357. if (!$scheme) {
  358. // Allow for:
  359. // - root-relative URIs (e.g. /foo.jpg in http://example.com/foo.jpg)
  360. // - protocol-relative URIs (e.g. //bar.jpg, which is expanded to
  361. // http://example.com/bar.jpg by the browser when viewing a page over
  362. // HTTP and to https://example.com/bar.jpg when viewing a HTTPS page)
  363. // Both types of relative URIs are characterized by a leading slash, hence
  364. // we can use a single check.
  365. if (drupal_substr($uri, 0, 1) == '/') {
  366. return $uri;
  367. }
  368. else {
  369. // If this is not a properly formatted stream, then it is a shipped file.
  370. // Therefore, return the urlencoded URI with the base URL prepended.
  371. return $GLOBALS['base_url'] . '/' . drupal_encode_path($uri);
  372. }
  373. }
  374. elseif ($scheme == 'http' || $scheme == 'https') {
  375. // Check for http so that we don't have to implement getExternalUrl() for
  376. // the http wrapper.
  377. return $uri;
  378. }
  379. else {
  380. // Attempt to return an external URL using the appropriate wrapper.
  381. if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  382. return $wrapper->getExternalUrl();
  383. }
  384. else {
  385. return FALSE;
  386. }
  387. }
  388. }
  389. /**
  390. * Check that the directory exists and is writable.
  391. *
  392. * Directories need to have execute permissions to be considered a directory by
  393. * FTP servers, etc.
  394. *
  395. * @param $directory
  396. * A string reference containing the name of a directory path or URI. A
  397. * trailing slash will be trimmed from a path.
  398. * @param $options
  399. * A bitmask to indicate if the directory should be created if it does
  400. * not exist (FILE_CREATE_DIRECTORY) or made writable if it is read-only
  401. * (FILE_MODIFY_PERMISSIONS).
  402. *
  403. * @return
  404. * TRUE if the directory exists (or was created) and is writable. FALSE
  405. * otherwise.
  406. */
  407. function file_prepare_directory(&$directory, $options = FILE_MODIFY_PERMISSIONS) {
  408. if (!file_stream_wrapper_valid_scheme(file_uri_scheme($directory))) {
  409. // Only trim if we're not dealing with a stream.
  410. $directory = rtrim($directory, '/\\');
  411. }
  412. // Check if directory exists.
  413. if (!is_dir($directory)) {
  414. // Let mkdir() recursively create directories and use the default directory
  415. // permissions.
  416. if (($options & FILE_CREATE_DIRECTORY) && @drupal_mkdir($directory, NULL, TRUE)) {
  417. return drupal_chmod($directory);
  418. }
  419. return FALSE;
  420. }
  421. // The directory exists, so check to see if it is writable.
  422. $writable = is_writable($directory);
  423. if (!$writable && ($options & FILE_MODIFY_PERMISSIONS)) {
  424. return drupal_chmod($directory);
  425. }
  426. return $writable;
  427. }
  428. /**
  429. * If missing, create a .htaccess file in each Drupal files directory.
  430. */
  431. function file_ensure_htaccess() {
  432. file_create_htaccess('public://', FALSE);
  433. if (variable_get('file_private_path', FALSE)) {
  434. file_create_htaccess('private://', TRUE);
  435. }
  436. file_create_htaccess('temporary://', TRUE);
  437. }
  438. /**
  439. * Creates an .htaccess file in the given directory.
  440. *
  441. * @param $directory
  442. * The directory.
  443. * @param $private
  444. * FALSE indicates that $directory should be an open and public directory.
  445. * The default is TRUE which indicates a private and protected directory.
  446. */
  447. function file_create_htaccess($directory, $private = TRUE) {
  448. if (file_uri_scheme($directory)) {
  449. $directory = file_stream_wrapper_uri_normalize($directory);
  450. }
  451. else {
  452. $directory = rtrim($directory, '/\\');
  453. }
  454. $htaccess_path = $directory . '/.htaccess';
  455. if (file_exists($htaccess_path)) {
  456. // Short circuit if the .htaccess file already exists.
  457. return;
  458. }
  459. if ($private) {
  460. // Private .htaccess file.
  461. $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nDeny from all\nOptions None\nOptions +FollowSymLinks";
  462. }
  463. else {
  464. // Public .htaccess file.
  465. $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
  466. }
  467. // Write the .htaccess file.
  468. if (file_put_contents($htaccess_path, $htaccess_lines)) {
  469. drupal_chmod($htaccess_path, 0444);
  470. }
  471. else {
  472. $variables = array('%directory' => $directory, '!htaccess' => '<br />' . nl2br(check_plain($htaccess_lines)));
  473. 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);
  474. }
  475. }
  476. /**
  477. * Loads file objects from the database.
  478. *
  479. * @param $fids
  480. * An array of file IDs.
  481. * @param $conditions
  482. * (deprecated) An associative array of conditions on the {file_managed}
  483. * table, where the keys are the database fields and the values are the
  484. * values those fields must have. Instead, it is preferable to use
  485. * EntityFieldQuery to retrieve a list of entity IDs loadable by
  486. * this function.
  487. *
  488. * @return
  489. * An array of file objects, indexed by fid.
  490. *
  491. * @see hook_file_load()
  492. * @see file_load()
  493. * @see entity_load()
  494. * @see EntityFieldQuery
  495. *
  496. * @todo Remove $conditions in Drupal 8.
  497. */
  498. function file_load_multiple($fids = array(), $conditions = array()) {
  499. return entity_load('file', $fids, $conditions);
  500. }
  501. /**
  502. * Load a file object from the database.
  503. *
  504. * @param $fid
  505. * A file ID.
  506. *
  507. * @return
  508. * A file object.
  509. *
  510. * @see hook_file_load()
  511. * @see file_load_multiple()
  512. */
  513. function file_load($fid) {
  514. $files = file_load_multiple(array($fid), array());
  515. return reset($files);
  516. }
  517. /**
  518. * Save a file object to the database.
  519. *
  520. * If the $file->fid is not set a new record will be added.
  521. *
  522. * @param $file
  523. * A file object returned by file_load().
  524. *
  525. * @return
  526. * The updated file object.
  527. *
  528. * @see hook_file_insert()
  529. * @see hook_file_update()
  530. */
  531. function file_save(stdClass $file) {
  532. $file->timestamp = REQUEST_TIME;
  533. $file->filesize = filesize($file->uri);
  534. // Load the stored entity, if any.
  535. if (!empty($file->fid) && !isset($file->original)) {
  536. $file->original = entity_load_unchanged('file', $file->fid);
  537. }
  538. module_invoke_all('file_presave', $file);
  539. module_invoke_all('entity_presave', $file, 'file');
  540. if (empty($file->fid)) {
  541. drupal_write_record('file_managed', $file);
  542. // Inform modules about the newly added file.
  543. module_invoke_all('file_insert', $file);
  544. module_invoke_all('entity_insert', $file, 'file');
  545. }
  546. else {
  547. drupal_write_record('file_managed', $file, 'fid');
  548. // Inform modules that the file has been updated.
  549. module_invoke_all('file_update', $file);
  550. module_invoke_all('entity_update', $file, 'file');
  551. }
  552. unset($file->original);
  553. return $file;
  554. }
  555. /**
  556. * Determines where a file is used.
  557. *
  558. * @param $file
  559. * A file object.
  560. *
  561. * @return
  562. * A nested array with usage data. The first level is keyed by module name,
  563. * the second by object type, the third has 'id' and 'count' keys.
  564. *
  565. * @see file_usage_add()
  566. * @see file_usage_delete()
  567. */
  568. function file_usage_list(stdClass $file) {
  569. $result = db_select('file_usage', 'f')
  570. ->fields('f', array('module', 'type', 'id', 'count'))
  571. ->condition('fid', $file->fid)
  572. ->condition('count', 0, '>')
  573. ->execute();
  574. $references = array();
  575. foreach ($result as $usage) {
  576. $references[$usage->module][$usage->type] = array('id' => $usage->id, 'count' => $usage->count);
  577. }
  578. return $references;
  579. }
  580. /**
  581. * Records that a module is using a file.
  582. *
  583. * This usage information will be queried during file_delete() to ensure that
  584. * a file is not in use before it is physically removed from disk.
  585. *
  586. * Examples:
  587. * - A module that associates files with nodes, so $type would be
  588. * 'node' and $id would be the node's nid. Files for all revisions are stored
  589. * within a single nid.
  590. * - The User module associates an image with a user, so $type would be 'user'
  591. * and the $id would be the user's uid.
  592. *
  593. * @param $file
  594. * A file object.
  595. * @param $module
  596. * The name of the module using the file.
  597. * @param $type
  598. * The type of the object that contains the referenced file.
  599. * @param $id
  600. * The unique, numeric ID of the object containing the referenced file.
  601. * @param $count
  602. * (optional) The number of references to add to the object. Defaults to 1.
  603. *
  604. * @see file_usage_list()
  605. * @see file_usage_delete()
  606. */
  607. function file_usage_add(stdClass $file, $module, $type, $id, $count = 1) {
  608. db_merge('file_usage')
  609. ->key(array(
  610. 'fid' => $file->fid,
  611. 'module' => $module,
  612. 'type' => $type,
  613. 'id' => $id,
  614. ))
  615. ->fields(array('count' => $count))
  616. ->expression('count', 'count + :count', array(':count' => $count))
  617. ->execute();
  618. }
  619. /**
  620. * Removes a record to indicate that a module is no longer using a file.
  621. *
  622. * The file_delete() function is typically called after removing a file usage
  623. * to remove the record from the file_managed table and delete the file itself.
  624. *
  625. * @param $file
  626. * A file object.
  627. * @param $module
  628. * The name of the module using the file.
  629. * @param $type
  630. * (optional) The type of the object that contains the referenced file. May
  631. * be omitted if all module references to a file are being deleted.
  632. * @param $id
  633. * (optional) The unique, numeric ID of the object containing the referenced
  634. * file. May be omitted if all module references to a file are being deleted.
  635. * @param $count
  636. * (optional) The number of references to delete from the object. Defaults to
  637. * 1. 0 may be specified to delete all references to the file within a
  638. * specific object.
  639. *
  640. * @see file_usage_add()
  641. * @see file_usage_list()
  642. * @see file_delete()
  643. */
  644. function file_usage_delete(stdClass $file, $module, $type = NULL, $id = NULL, $count = 1) {
  645. // Delete rows that have a exact or less value to prevent empty rows.
  646. $query = db_delete('file_usage')
  647. ->condition('module', $module)
  648. ->condition('fid', $file->fid);
  649. if ($type && $id) {
  650. $query
  651. ->condition('type', $type)
  652. ->condition('id', $id);
  653. }
  654. if ($count) {
  655. $query->condition('count', $count, '<=');
  656. }
  657. $result = $query->execute();
  658. // If the row has more than the specified count decrement it by that number.
  659. if (!$result && $count > 0) {
  660. $query = db_update('file_usage')
  661. ->condition('module', $module)
  662. ->condition('fid', $file->fid);
  663. if ($type && $id) {
  664. $query
  665. ->condition('type', $type)
  666. ->condition('id', $id);
  667. }
  668. $query->expression('count', 'count - :count', array(':count' => $count));
  669. $query->execute();
  670. }
  671. }
  672. /**
  673. * Copies a file to a new location and adds a file record to the database.
  674. *
  675. * This function should be used when manipulating files that have records
  676. * stored in the database. This is a powerful function that in many ways
  677. * performs like an advanced version of copy().
  678. * - Checks if $source and $destination are valid and readable/writable.
  679. * - Checks that $source is not equal to $destination; if they are an error
  680. * is reported.
  681. * - If file already exists in $destination either the call will error out,
  682. * replace the file or rename the file based on the $replace parameter.
  683. * - Adds the new file to the files database. If the source file is a
  684. * temporary file, the resulting file will also be a temporary file. See
  685. * file_save_upload() for details on temporary files.
  686. *
  687. * @param $source
  688. * A file object.
  689. * @param $destination
  690. * A string containing the destination that $source should be copied to.
  691. * This must be a stream wrapper URI.
  692. * @param $replace
  693. * Replace behavior when the destination file already exists:
  694. * - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
  695. * the destination name exists then its database entry will be updated. If
  696. * no database entry is found then a new one will be created.
  697. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  698. * unique.
  699. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  700. *
  701. * @return
  702. * File object if the copy is successful, or FALSE in the event of an error.
  703. *
  704. * @see file_unmanaged_copy()
  705. * @see hook_file_copy()
  706. */
  707. function file_copy(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  708. if (!file_valid_uri($destination)) {
  709. if (($realpath = drupal_realpath($source->uri)) !== FALSE) {
  710. 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));
  711. }
  712. else {
  713. 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));
  714. }
  715. 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');
  716. return FALSE;
  717. }
  718. if ($uri = file_unmanaged_copy($source->uri, $destination, $replace)) {
  719. $file = clone $source;
  720. $file->fid = NULL;
  721. $file->uri = $uri;
  722. $file->filename = basename($uri);
  723. // If we are replacing an existing file re-use its database record.
  724. if ($replace == FILE_EXISTS_REPLACE) {
  725. $existing_files = file_load_multiple(array(), array('uri' => $uri));
  726. if (count($existing_files)) {
  727. $existing = reset($existing_files);
  728. $file->fid = $existing->fid;
  729. $file->filename = $existing->filename;
  730. }
  731. }
  732. // If we are renaming around an existing file (rather than a directory),
  733. // use its basename for the filename.
  734. elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
  735. $file->filename = basename($destination);
  736. }
  737. $file = file_save($file);
  738. // Inform modules that the file has been copied.
  739. module_invoke_all('file_copy', $file, $source);
  740. return $file;
  741. }
  742. return FALSE;
  743. }
  744. /**
  745. * Determine whether the URI has a valid scheme for file API operations.
  746. *
  747. * There must be a scheme and it must be a Drupal-provided scheme like
  748. * 'public', 'private', 'temporary', or an extension provided with
  749. * hook_stream_wrappers().
  750. *
  751. * @param $uri
  752. * The URI to be tested.
  753. *
  754. * @return
  755. * TRUE if the URI is allowed.
  756. */
  757. function file_valid_uri($uri) {
  758. // Assert that the URI has an allowed scheme. Barepaths are not allowed.
  759. $uri_scheme = file_uri_scheme($uri);
  760. if (empty($uri_scheme) || !file_stream_wrapper_valid_scheme($uri_scheme)) {
  761. return FALSE;
  762. }
  763. return TRUE;
  764. }
  765. /**
  766. * Copies a file to a new location without invoking the file API.
  767. *
  768. * This is a powerful function that in many ways performs like an advanced
  769. * version of copy().
  770. * - Checks if $source and $destination are valid and readable/writable.
  771. * - Checks that $source is not equal to $destination; if they are an error
  772. * is reported.
  773. * - If file already exists in $destination either the call will error out,
  774. * replace the file or rename the file based on the $replace parameter.
  775. *
  776. * @param $source
  777. * A string specifying the filepath or URI of the source file.
  778. * @param $destination
  779. * A URI containing the destination that $source should be copied to. The
  780. * URI may be a bare filepath (without a scheme) and in that case the default
  781. * scheme (file://) will be used. If this value is omitted, Drupal's default
  782. * files scheme will be used, usually "public://".
  783. * @param $replace
  784. * Replace behavior when the destination file already exists:
  785. * - FILE_EXISTS_REPLACE - Replace the existing file.
  786. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  787. * unique.
  788. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  789. *
  790. * @return
  791. * The path to the new file, or FALSE in the event of an error.
  792. *
  793. * @see file_copy()
  794. */
  795. function file_unmanaged_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  796. $original_source = $source;
  797. $original_destination = $destination;
  798. // Assert that the source file actually exists.
  799. if (!file_exists($source)) {
  800. // @todo Replace drupal_set_message() calls with exceptions instead.
  801. 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');
  802. if (($realpath = drupal_realpath($original_source)) !== FALSE) {
  803. watchdog('file', 'File %file (%realpath) could not be copied because it does not exist.', array('%file' => $original_source, '%realpath' => $realpath));
  804. }
  805. else {
  806. watchdog('file', 'File %file could not be copied because it does not exist.', array('%file' => $original_source));
  807. }
  808. return FALSE;
  809. }
  810. // Build a destination URI if necessary.
  811. if (!isset($destination)) {
  812. $destination = file_build_uri(basename($source));
  813. }
  814. // Prepare the destination directory.
  815. if (file_prepare_directory($destination)) {
  816. // The destination is already a directory, so append the source basename.
  817. $destination = file_stream_wrapper_uri_normalize($destination . '/' . basename($source));
  818. }
  819. else {
  820. // Perhaps $destination is a dir/file?
  821. $dirname = drupal_dirname($destination);
  822. if (!file_prepare_directory($dirname)) {
  823. // The destination is not valid.
  824. watchdog('file', 'File %file could not be copied, because the destination directory %destination is not configured correctly.', array('%file' => $original_source, '%destination' => $dirname));
  825. 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');
  826. return FALSE;
  827. }
  828. }
  829. // Determine whether we can perform this operation based on overwrite rules.
  830. $destination = file_destination($destination, $replace);
  831. if ($destination === FALSE) {
  832. 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');
  833. 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, '%destination' => $destination));
  834. return FALSE;
  835. }
  836. // Assert that the source and destination filenames are not the same.
  837. $real_source = drupal_realpath($source);
  838. $real_destination = drupal_realpath($destination);
  839. if ($source == $destination || ($real_source !== FALSE) && ($real_source == $real_destination)) {
  840. drupal_set_message(t('The specified file %file was not copied because it would overwrite itself.', array('%file' => $source)), 'error');
  841. watchdog('file', 'File %file could not be copied because it would overwrite itself.', array('%file' => $source));
  842. return FALSE;
  843. }
  844. // Make sure the .htaccess files are present.
  845. file_ensure_htaccess();
  846. // Perform the copy operation.
  847. if (!@copy($source, $destination)) {
  848. watchdog('file', 'The specified file %file could not be copied to %destination.', array('%file' => $source, '%destination' => $destination), WATCHDOG_ERROR);
  849. return FALSE;
  850. }
  851. // Set the permissions on the new file.
  852. drupal_chmod($destination);
  853. return $destination;
  854. }
  855. /**
  856. * Given a relative path, construct a URI into Drupal's default files location.
  857. */
  858. function file_build_uri($path) {
  859. $uri = file_default_scheme() . '://' . $path;
  860. return file_stream_wrapper_uri_normalize($uri);
  861. }
  862. /**
  863. * Determines the destination path for a file depending on how replacement of
  864. * existing files should be handled.
  865. *
  866. * @param $destination
  867. * A string specifying the desired final URI or filepath.
  868. * @param $replace
  869. * Replace behavior when the destination file already exists.
  870. * - FILE_EXISTS_REPLACE - Replace the existing file.
  871. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  872. * unique.
  873. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  874. *
  875. * @return
  876. * The destination filepath, or FALSE if the file already exists
  877. * and FILE_EXISTS_ERROR is specified.
  878. */
  879. function file_destination($destination, $replace) {
  880. if (file_exists($destination)) {
  881. switch ($replace) {
  882. case FILE_EXISTS_REPLACE:
  883. // Do nothing here, we want to overwrite the existing file.
  884. break;
  885. case FILE_EXISTS_RENAME:
  886. $basename = basename($destination);
  887. $directory = drupal_dirname($destination);
  888. $destination = file_create_filename($basename, $directory);
  889. break;
  890. case FILE_EXISTS_ERROR:
  891. // Error reporting handled by calling function.
  892. return FALSE;
  893. }
  894. }
  895. return $destination;
  896. }
  897. /**
  898. * Move a file to a new location and update the file's database entry.
  899. *
  900. * Moving a file is performed by copying the file to the new location and then
  901. * deleting the original.
  902. * - Checks if $source and $destination are valid and readable/writable.
  903. * - Performs a file move if $source is not equal to $destination.
  904. * - If file already exists in $destination either the call will error out,
  905. * replace the file or rename the file based on the $replace parameter.
  906. * - Adds the new file to the files database.
  907. *
  908. * @param $source
  909. * A file object.
  910. * @param $destination
  911. * A string containing the destination that $source should be moved to.
  912. * This must be a stream wrapper URI.
  913. * @param $replace
  914. * Replace behavior when the destination file already exists:
  915. * - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
  916. * the destination name exists then its database entry will be updated and
  917. * file_delete() called on the source file after hook_file_move is called.
  918. * If no database entry is found then the source files record will be
  919. * updated.
  920. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  921. * unique.
  922. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  923. *
  924. * @return
  925. * Resulting file object for success, or FALSE in the event of an error.
  926. *
  927. * @see file_unmanaged_move()
  928. * @see hook_file_move()
  929. */
  930. function file_move(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  931. if (!file_valid_uri($destination)) {
  932. if (($realpath = drupal_realpath($source->uri)) !== FALSE) {
  933. 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));
  934. }
  935. else {
  936. 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));
  937. }
  938. 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');
  939. return FALSE;
  940. }
  941. if ($uri = file_unmanaged_move($source->uri, $destination, $replace)) {
  942. $delete_source = FALSE;
  943. $file = clone $source;
  944. $file->uri = $uri;
  945. // If we are replacing an existing file re-use its database record.
  946. if ($replace == FILE_EXISTS_REPLACE) {
  947. $existing_files = file_load_multiple(array(), array('uri' => $uri));
  948. if (count($existing_files)) {
  949. $existing = reset($existing_files);
  950. $delete_source = TRUE;
  951. $file->fid = $existing->fid;
  952. }
  953. }
  954. // If we are renaming around an existing file (rather than a directory),
  955. // use its basename for the filename.
  956. elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
  957. $file->filename = basename($destination);
  958. }
  959. $file = file_save($file);
  960. // Inform modules that the file has been moved.
  961. module_invoke_all('file_move', $file, $source);
  962. if ($delete_source) {
  963. // Try a soft delete to remove original if it's not in use elsewhere.
  964. file_delete($source);
  965. }
  966. return $file;
  967. }
  968. return FALSE;
  969. }
  970. /**
  971. * Move a file to a new location without calling any hooks or making any
  972. * changes to the database.
  973. *
  974. * @param $source
  975. * A string specifying the filepath or URI of the original file.
  976. * @param $destination
  977. * A string containing the destination that $source should be moved to.
  978. * This must be a stream wrapper URI. If this value is omitted, Drupal's
  979. * default files scheme will be used, usually "public://".
  980. * @param $replace
  981. * Replace behavior when the destination file already exists:
  982. * - FILE_EXISTS_REPLACE - Replace the existing file.
  983. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  984. * unique.
  985. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  986. *
  987. * @return
  988. * The URI of the moved file, or FALSE in the event of an error.
  989. *
  990. * @see file_move()
  991. */
  992. function file_unmanaged_move($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  993. $filepath = file_unmanaged_copy($source, $destination, $replace);
  994. if ($filepath == FALSE || file_unmanaged_delete($source) == FALSE) {
  995. return FALSE;
  996. }
  997. return $filepath;
  998. }
  999. /**
  1000. * Modify a filename as needed for security purposes.
  1001. *
  1002. * Munging a file name prevents unknown file extensions from masking exploit
  1003. * files. When web servers such as Apache decide how to process a URL request,
  1004. * they use the file extension. If the extension is not recognized, Apache
  1005. * skips that extension and uses the previous file extension. For example, if
  1006. * the file being requested is exploit.php.pps, and Apache does not recognize
  1007. * the '.pps' extension, it treats the file as PHP and executes it. To make
  1008. * this file name safe for Apache and prevent it from executing as PHP, the
  1009. * .php extension is "munged" into .php_, making the safe file name
  1010. * exploit.php_.pps.
  1011. *
  1012. * Specifically, this function adds an underscore to all extensions that are
  1013. * between 2 and 5 characters in length, internal to the file name, and not
  1014. * included in $extensions.
  1015. *
  1016. * Function behavior is also controlled by the Drupal variable
  1017. * 'allow_insecure_uploads'. If 'allow_insecure_uploads' evaluates to TRUE, no
  1018. * alterations will be made, if it evaluates to FALSE, the filename is 'munged'.
  1019. *
  1020. * @param $filename
  1021. * File name to modify.
  1022. * @param $extensions
  1023. * A space-separated list of extensions that should not be altered.
  1024. * @param $alerts
  1025. * If TRUE, drupal_set_message() will be called to display a message if the
  1026. * file name was changed.
  1027. *
  1028. * @return
  1029. * The potentially modified $filename.
  1030. */
  1031. function file_munge_filename($filename, $extensions, $alerts = TRUE) {
  1032. $original = $filename;
  1033. // Allow potentially insecure uploads for very savvy users and admin
  1034. if (!variable_get('allow_insecure_uploads', 0)) {
  1035. $whitelist = array_unique(explode(' ', trim($extensions)));
  1036. // Split the filename up by periods. The first part becomes the basename
  1037. // the last part the final extension.
  1038. $filename_parts = explode('.', $filename);
  1039. $new_filename = array_shift($filename_parts); // Remove file basename.
  1040. $final_extension = array_pop($filename_parts); // Remove final extension.
  1041. // Loop through the middle parts of the name and add an underscore to the
  1042. // end of each section that could be a file extension but isn't in the list
  1043. // of allowed extensions.
  1044. foreach ($filename_parts as $filename_part) {
  1045. $new_filename .= '.' . $filename_part;
  1046. if (!in_array($filename_part, $whitelist) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $filename_part)) {
  1047. $new_filename .= '_';
  1048. }
  1049. }
  1050. $filename = $new_filename . '.' . $final_extension;
  1051. if ($alerts && $original != $filename) {
  1052. drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $filename)));
  1053. }
  1054. }
  1055. return $filename;
  1056. }
  1057. /**
  1058. * Undo the effect of upload_munge_filename().
  1059. *
  1060. * @param $filename
  1061. * String with the filename to be unmunged.
  1062. *
  1063. * @return
  1064. * An unmunged filename string.
  1065. */
  1066. function file_unmunge_filename($filename) {
  1067. return str_replace('_.', '.', $filename);
  1068. }
  1069. /**
  1070. * Create a full file path from a directory and filename.
  1071. *
  1072. * If a file with the specified name already exists, an alternative will be
  1073. * used.
  1074. *
  1075. * @param $basename
  1076. * String filename
  1077. * @param $directory
  1078. * String containing the directory or parent URI.
  1079. *
  1080. * @return
  1081. * File path consisting of $directory and a unique filename based off
  1082. * of $basename.
  1083. */
  1084. function file_create_filename($basename, $directory) {
  1085. // Strip control characters (ASCII value < 32). Though these are allowed in
  1086. // some filesystems, not many applications handle them well.
  1087. $basename = preg_replace('/[\x00-\x1F]/u', '_', $basename);
  1088. if (substr(PHP_OS, 0, 3) == 'WIN') {
  1089. // These characters are not allowed in Windows filenames
  1090. $basename = str_replace(array(':', '*', '?', '"', '<', '>', '|'), '_', $basename);
  1091. }
  1092. // A URI or path may already have a trailing slash or look like "public://".
  1093. if (substr($directory, -1) == '/') {
  1094. $separator = '';
  1095. }
  1096. else {
  1097. $separator = '/';
  1098. }
  1099. $destination = $directory . $separator . $basename;
  1100. if (file_exists($destination)) {
  1101. // Destination file already exists, generate an alternative.
  1102. $pos = strrpos($basename, '.');
  1103. if ($pos !== FALSE) {
  1104. $name = substr($basename, 0, $pos);
  1105. $ext = substr($basename, $pos);
  1106. }
  1107. else {
  1108. $name = $basename;
  1109. $ext = '';
  1110. }
  1111. $counter = 0;
  1112. do {
  1113. $destination = $directory . $separator . $name . '_' . $counter++ . $ext;
  1114. } while (file_exists($destination));
  1115. }
  1116. return $destination;
  1117. }
  1118. /**
  1119. * Delete a file and its database record.
  1120. *
  1121. * If the $force parameter is not TRUE, file_usage_list() will be called to
  1122. * determine if the file is being used by any modules. If the file is being
  1123. * used the delete will be canceled.
  1124. *
  1125. * @param $file
  1126. * A file object.
  1127. * @param $force
  1128. * Boolean indicating that the file should be deleted even if the file is
  1129. * reported as in use by the file_usage table.
  1130. *
  1131. * @return mixed
  1132. * TRUE for success, FALSE in the event of an error, or an array if the file
  1133. * is being used by any modules.
  1134. *
  1135. * @see file_unmanaged_delete()
  1136. * @see file_usage_list()
  1137. * @see file_usage_delete()
  1138. * @see hook_file_delete()
  1139. */
  1140. function file_delete(stdClass $file, $force = FALSE) {
  1141. if (!file_valid_uri($file->uri)) {
  1142. if (($realpath = drupal_realpath($file->uri)) !== FALSE) {
  1143. 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));
  1144. }
  1145. else {
  1146. 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));
  1147. }
  1148. 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');
  1149. return FALSE;
  1150. }
  1151. // If any module still has a usage entry in the file_usage table, the file
  1152. // will not be deleted, but file_delete() will return a populated array
  1153. // that tests as TRUE.
  1154. if (!$force && ($references = file_usage_list($file))) {
  1155. return $references;
  1156. }
  1157. // Let other modules clean up any references to the deleted file.
  1158. module_invoke_all('file_delete', $file);
  1159. module_invoke_all('entity_delete', $file, 'file');
  1160. // Make sure the file is deleted before removing its row from the
  1161. // database, so UIs can still find the file in the database.
  1162. if (file_unmanaged_delete($file->uri)) {
  1163. db_delete('file_managed')->condition('fid', $file->fid)->execute();
  1164. db_delete('file_usage')->condition('fid', $file->fid)->execute();
  1165. return TRUE;
  1166. }
  1167. return FALSE;
  1168. }
  1169. /**
  1170. * Delete a file without calling any hooks or making any changes to the
  1171. * database.
  1172. *
  1173. * This function should be used when the file to be deleted does not have an
  1174. * entry recorded in the files table.
  1175. *
  1176. * @param $path
  1177. * A string containing a file path or (streamwrapper) URI.
  1178. *
  1179. * @return
  1180. * TRUE for success or path does not exist, or FALSE in the event of an
  1181. * error.
  1182. *
  1183. * @see file_delete()
  1184. * @see file_unmanaged_delete_recursive()
  1185. */
  1186. function file_unmanaged_delete($path) {
  1187. if (is_dir($path)) {
  1188. watchdog('file', '%path is a directory and cannot be removed using file_unmanaged_delete().', array('%path' => $path), WATCHDOG_ERROR);
  1189. return FALSE;
  1190. }
  1191. if (is_file($path)) {
  1192. return drupal_unlink($path);
  1193. }
  1194. // Return TRUE for non-existent file, but log that nothing was actually
  1195. // deleted, as the current state is the intended result.
  1196. if (!file_exists($path)) {
  1197. watchdog('file', 'The file %path was not deleted, because it does not exist.', array('%path' => $path), WATCHDOG_NOTICE);
  1198. return TRUE;
  1199. }
  1200. // We cannot handle anything other than files and directories. Log an error
  1201. // for everything else (sockets, symbolic links, etc).
  1202. watchdog('file', 'The file %path is not of a recognized type so it was not deleted.', array('%path' => $path), WATCHDOG_ERROR);
  1203. return FALSE;
  1204. }
  1205. /**
  1206. * Recursively delete all files and directories in the specified filepath.
  1207. *
  1208. * If the specified path is a directory then the function will call itself
  1209. * recursively to process the contents. Once the contents have been removed the
  1210. * directory will also be removed.
  1211. *
  1212. * If the specified path is a file then it will be passed to
  1213. * file_unmanaged_delete().
  1214. *
  1215. * Note that this only deletes visible files with write permission.
  1216. *
  1217. * @param $path
  1218. * A string containing either an URI or a file or directory path.
  1219. *
  1220. * @return
  1221. * TRUE for success or if path does not exist, FALSE in the event of an
  1222. * error.
  1223. *
  1224. * @see file_unmanaged_delete()
  1225. */
  1226. function file_unmanaged_delete_recursive($path) {
  1227. if (is_dir($path)) {
  1228. $dir = dir($path);
  1229. while (($entry = $dir->read()) !== FALSE) {
  1230. if ($entry == '.' || $entry == '..') {
  1231. continue;
  1232. }
  1233. $entry_path = $path . '/' . $entry;
  1234. file_unmanaged_delete_recursive($entry_path);
  1235. }
  1236. $dir->close();
  1237. return drupal_rmdir($path);
  1238. }
  1239. return file_unmanaged_delete($path);
  1240. }
  1241. /**
  1242. * Determine total disk space used by a single user or the whole filesystem.
  1243. *
  1244. * @param $uid
  1245. * Optional. A user id, specifying NULL returns the total space used by all
  1246. * non-temporary files.
  1247. * @param $status
  1248. * Optional. The file status to consider. The default is to only
  1249. * consider files in status FILE_STATUS_PERMANENT.
  1250. *
  1251. * @return
  1252. * An integer containing the number of bytes used.
  1253. */
  1254. function file_space_used($uid = NULL, $status = FILE_STATUS_PERMANENT) {
  1255. $query = db_select('file_managed', 'f');
  1256. $query->condition('f.status', $status);
  1257. $query->addExpression('SUM(f.filesize)', 'filesize');
  1258. if (isset($uid)) {
  1259. $query->condition('f.uid', $uid);
  1260. }
  1261. return $query->execute()->fetchField();
  1262. }
  1263. /**
  1264. * Saves a file upload to a new location.
  1265. *
  1266. * The file will be added to the {file_managed} table as a temporary file.
  1267. * Temporary files are periodically cleaned. To make the file a permanent file,
  1268. * assign the status and use file_save() to save the changes.
  1269. *
  1270. * @param $source
  1271. * A string specifying the filepath or URI of the uploaded file to save.
  1272. * @param $validators
  1273. * An optional, associative array of callback functions used to validate the
  1274. * file. See file_validate() for a full discussion of the array format.
  1275. * If no extension validator is provided it will default to a limited safe
  1276. * list of extensions which is as follows: "jpg jpeg gif png txt
  1277. * doc xls pdf ppt pps odt ods odp". To allow all extensions you must
  1278. * explicitly set the 'file_validate_extensions' validator to an empty array
  1279. * (Beware: this is not safe and should only be allowed for trusted users, if
  1280. * at all).
  1281. * @param $destination
  1282. * A string containing the URI $source should be copied to.
  1283. * This must be a stream wrapper URI. If this value is omitted, Drupal's
  1284. * temporary files scheme will be used ("temporary://").
  1285. * @param $replace
  1286. * Replace behavior when the destination file already exists:
  1287. * - FILE_EXISTS_REPLACE: Replace the existing file.
  1288. * - FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is
  1289. * unique.
  1290. * - FILE_EXISTS_ERROR: Do nothing and return FALSE.
  1291. *
  1292. * @return
  1293. * An object containing the file information if the upload succeeded, FALSE
  1294. * in the event of an error, or NULL if no file was uploaded. The
  1295. * documentation for the "File interface" group, which you can find under
  1296. * Related topics, or the header at the top of this file, documents the
  1297. * components of a file object. In addition to the standard components,
  1298. * this function adds:
  1299. * - source: Path to the file before it is moved.
  1300. * - destination: Path to the file after it is moved (same as 'uri').
  1301. */
  1302. function file_save_upload($source, $validators = array(), $destination = FALSE, $replace = FILE_EXISTS_RENAME) {
  1303. global $user;
  1304. static $upload_cache;
  1305. // Return cached objects without processing since the file will have
  1306. // already been processed and the paths in _FILES will be invalid.
  1307. if (isset($upload_cache[$source])) {
  1308. return $upload_cache[$source];
  1309. }
  1310. // Make sure there's an upload to process.
  1311. if (empty($_FILES['files']['name'][$source])) {
  1312. return NULL;
  1313. }
  1314. // Check for file upload errors and return FALSE if a lower level system
  1315. // error occurred. For a complete list of errors:
  1316. // See http://php.net/manual/en/features.file-upload.errors.php.
  1317. switch ($_FILES['files']['error'][$source]) {
  1318. case UPLOAD_ERR_INI_SIZE:
  1319. case UPLOAD_ERR_FORM_SIZE:
  1320. drupal_set_message(t('The file %file could not be saved, because it exceeds %maxsize, the maximum allowed size for uploads.', array('%file' => $_FILES['files']['name'][$source], '%maxsize' => format_size(file_upload_max_size()))), 'error');
  1321. return FALSE;
  1322. case UPLOAD_ERR_PARTIAL:
  1323. case UPLOAD_ERR_NO_FILE:
  1324. drupal_set_message(t('The file %file could not be saved, because the upload did not complete.', array('%file' => $_FILES['files']['name'][$source])), 'error');
  1325. return FALSE;
  1326. case UPLOAD_ERR_OK:
  1327. // Final check that this is a valid upload, if it isn't, use the
  1328. // default error handler.
  1329. if (is_uploaded_file($_FILES['files']['tmp_name'][$source])) {
  1330. break;
  1331. }
  1332. // Unknown error
  1333. default:
  1334. drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', array('%file' => $_FILES['files']['name'][$source])), 'error');
  1335. return FALSE;
  1336. }
  1337. // Begin building file object.
  1338. $file = new stdClass();
  1339. $file->uid = $user->uid;
  1340. $file->status = 0;
  1341. $file->filename = trim(basename($_FILES['files']['name'][$source]), '.');
  1342. $file->uri = $_FILES['files']['tmp_name'][$source];
  1343. $file->filemime = file_get_mimetype($file->filename);
  1344. $file->filesize = $_FILES['files']['size'][$source];
  1345. $extensions = '';
  1346. if (isset($validators['file_validate_extensions'])) {
  1347. if (isset($validators['file_validate_extensions'][0])) {
  1348. // Build the list of non-munged extensions if the caller provided them.
  1349. $extensions = $validators['file_validate_extensions'][0];
  1350. }
  1351. else {
  1352. // If 'file_validate_extensions' is set and the list is empty then the
  1353. // caller wants to allow any extension. In this case we have to remove the
  1354. // validator or else it will reject all extensions.
  1355. unset($validators['file_validate_extensions']);
  1356. }
  1357. }
  1358. else {
  1359. // No validator was provided, so add one using the default list.
  1360. // Build a default non-munged safe list for file_munge_filename().
  1361. $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp';
  1362. $validators['file_validate_extensions'] = array();
  1363. $validators['file_validate_extensions'][0] = $extensions;
  1364. }
  1365. if (!empty($extensions)) {
  1366. // Munge the filename to protect against possible malicious extension hiding
  1367. // within an unknown file type (ie: filename.html.foo).
  1368. $file->filename = file_munge_filename($file->filename, $extensions);
  1369. }
  1370. // Rename potentially executable files, to help prevent exploits (i.e. will
  1371. // rename filename.php.foo and filename.php to filename.php.foo.txt and
  1372. // filename.php.txt, respectively). Don't rename if 'allow_insecure_uploads'
  1373. // evaluates to TRUE.
  1374. if (!variable_get('allow_insecure_uploads', 0) && preg_match('/\.(php|pl|py|cgi|asp|js)(\.|$)/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
  1375. $file->filemime = 'text/plain';
  1376. $file->uri .= '.txt';
  1377. $file->filename .= '.txt';
  1378. // The .txt extension may not be in the allowed list of extensions. We have
  1379. // to add it here or else the file upload will fail.
  1380. if (!empty($extensions)) {
  1381. $validators['file_validate_extensions'][0] .= ' txt';
  1382. drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $file->filename)));
  1383. }
  1384. }
  1385. // If the destination is not provided, use the temporary directory.
  1386. if (empty($destination)) {
  1387. $destination = 'temporary://';
  1388. }
  1389. // Assert that the destination contains a valid stream.
  1390. $destination_scheme = file_uri_scheme($destination);
  1391. if (!$destination_scheme || !file_stream_wrapper_valid_scheme($destination_scheme)) {
  1392. drupal_set_message(t('The file could not be uploaded, because the destination %destination is invalid.', array('%destination' => $destination)), 'error');
  1393. return FALSE;
  1394. }
  1395. $file->source = $source;
  1396. // A URI may already have a trailing slash or look like "public://".
  1397. if (substr($destination, -1) != '/') {
  1398. $destination .= '/';
  1399. }
  1400. $file->destination = file_destination($destination . $file->filename, $replace);
  1401. // If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and
  1402. // there's an existing file so we need to bail.
  1403. if ($file->destination === FALSE) {
  1404. 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' => $source, '%directory' => $destination)), 'error');
  1405. return FALSE;
  1406. }
  1407. // Add in our check of the the file name length.
  1408. $validators['file_validate_name_length'] = array();
  1409. // Call the validation functions specified by this function's caller.
  1410. $errors = file_validate($file, $validators);
  1411. // Check for errors.
  1412. if (!empty($errors)) {
  1413. $message = t('The specified file %name could not be uploaded.', array('%name' => $file->filename));
  1414. if (count($errors) > 1) {
  1415. $message .= theme('item_list', array('items' => $errors));
  1416. }
  1417. else {
  1418. $message .= ' ' . array_pop($errors);
  1419. }
  1420. form_set_error($source, $message);
  1421. return FALSE;
  1422. }
  1423. // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary
  1424. // directory. This overcomes open_basedir restrictions for future file
  1425. // operations.
  1426. $file->uri = $file->destination;
  1427. if (!move_uploaded_file($_FILES['files']['tmp_name'][$source], $file->uri)) {
  1428. form_set_error($source, t('File upload error. Could not move uploaded file.'));
  1429. watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->uri));
  1430. return FALSE;
  1431. }
  1432. // Set the permissions on the new file.
  1433. drupal_chmod($file->uri);
  1434. // If we are replacing an existing file re-use its database record.
  1435. if ($replace == FILE_EXISTS_REPLACE) {
  1436. $existing_files = file_load_multiple(array(), array('uri' => $file->uri));
  1437. if (count($existing_files)) {
  1438. $existing = reset($existing_files);
  1439. $file->fid = $existing->fid;
  1440. }
  1441. }
  1442. // If we made it this far it's safe to record this file in the database.
  1443. if ($file = file_save($file)) {
  1444. // Add file to the cache.
  1445. $upload_cache[$source] = $file;
  1446. return $file;
  1447. }
  1448. return FALSE;
  1449. }
  1450. /**
  1451. * Check that a file meets the criteria specified by the validators.
  1452. *
  1453. * After executing the validator callbacks specified hook_file_validate() will
  1454. * also be called to allow other modules to report errors about the file.
  1455. *
  1456. * @param $file
  1457. * A Drupal file object.
  1458. * @param $validators
  1459. * An optional, associative array of callback functions used to validate the
  1460. * file. The keys are function names and the values arrays of callback
  1461. * parameters which will be passed in after the file object. The
  1462. * functions should return an array of error messages; an empty array
  1463. * indicates that the file passed validation. The functions will be called in
  1464. * the order specified.
  1465. *
  1466. * @return
  1467. * An array containing validation error messages.
  1468. *
  1469. * @see hook_file_validate()
  1470. */
  1471. function file_validate(stdClass &$file, $validators = array()) {
  1472. // Call the validation functions specified by this function's caller.
  1473. $errors = array();
  1474. foreach ($validators as $function => $args) {
  1475. if (function_exists($function)) {
  1476. array_unshift($args, $file);
  1477. $errors = array_merge($errors, call_user_func_array($function, $args));
  1478. }
  1479. }
  1480. // Let other modules perform validation on the new file.
  1481. return array_merge($errors, module_invoke_all('file_validate', $file));
  1482. }
  1483. /**
  1484. * Check for files with names longer than we can store in the database.
  1485. *
  1486. * @param $file
  1487. * A Drupal file object.
  1488. * @return
  1489. * An array. If the file name is too long, it will contain an error message.
  1490. */
  1491. function file_validate_name_length(stdClass $file) {
  1492. $errors = array();
  1493. if (empty($file->filename)) {
  1494. $errors[] = t("The file's name is empty. Please give a name to the file.");
  1495. }
  1496. if (strlen($file->filename) > 240) {
  1497. $errors[] = t("The file's name exceeds the 240 characters limit. Please rename the file and try again.");
  1498. }
  1499. return $errors;
  1500. }
  1501. /**
  1502. * Check that the filename ends with an allowed extension.
  1503. *
  1504. * @param $file
  1505. * A Drupal file object.
  1506. * @param $extensions
  1507. * A string with a space separated list of allowed extensions.
  1508. *
  1509. * @return
  1510. * An array. If the file extension is not allowed, it will contain an error
  1511. * message.
  1512. *
  1513. * @see hook_file_validate()
  1514. */
  1515. function file_validate_extensions(stdClass $file, $extensions) {
  1516. $errors = array();
  1517. $regex = '/\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
  1518. if (!preg_match($regex, $file->filename)) {
  1519. $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions));
  1520. }
  1521. return $errors;
  1522. }
  1523. /**
  1524. * Check that the file's size is below certain limits.
  1525. *
  1526. * This check is not enforced for the user #1.
  1527. *
  1528. * @param $file
  1529. * A Drupal file object.
  1530. * @param $file_limit
  1531. * An integer specifying the maximum file size in bytes. Zero indicates that
  1532. * no limit should be enforced.
  1533. * @param $user_limit
  1534. * An integer specifying the maximum number of bytes the user is allowed.
  1535. * Zero indicates that no limit should be enforced.
  1536. *
  1537. * @return
  1538. * An array. If the file size exceeds limits, it will contain an error
  1539. * message.
  1540. *
  1541. * @see hook_file_validate()
  1542. */
  1543. function file_validate_size(stdClass $file, $file_limit = 0, $user_limit = 0) {
  1544. global $user;
  1545. $errors = array();
  1546. // Bypass validation for uid = 1.
  1547. if ($user->uid != 1) {
  1548. if ($file_limit && $file->filesize > $file_limit) {
  1549. $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($file_limit)));
  1550. }
  1551. // Save a query by only calling file_space_used() when a limit is provided.
  1552. if ($user_limit && (file_space_used($user->uid) + $file->filesize) > $user_limit) {
  1553. $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)));
  1554. }
  1555. }
  1556. return $errors;
  1557. }
  1558. /**
  1559. * Check that the file is recognized by image_get_info() as an image.
  1560. *
  1561. * @param $file
  1562. * A Drupal file object.
  1563. *
  1564. * @return
  1565. * An array. If the file is not an image, it will contain an error message.
  1566. *
  1567. * @see hook_file_validate()
  1568. */
  1569. function file_validate_is_image(stdClass $file) {
  1570. $errors = array();
  1571. $info = image_get_info($file->uri);
  1572. if (!$info || empty($info['extension'])) {
  1573. $errors[] = t('Only JPEG, PNG and GIF images are allowed.');
  1574. }
  1575. return $errors;
  1576. }
  1577. /**
  1578. * Verify that image dimensions are within the specified maximum and minimum.
  1579. *
  1580. * Non-image files will be ignored. If a image toolkit is available the image
  1581. * will be scaled to fit within the desired maximum dimensions.
  1582. *
  1583. * @param $file
  1584. * A Drupal file object. This function may resize the file affecting its
  1585. * size.
  1586. * @param $maximum_dimensions
  1587. * An optional string in the form WIDTHxHEIGHT e.g. '640x480' or '85x85'. If
  1588. * an image toolkit is installed the image will be resized down to these
  1589. * dimensions. A value of 0 indicates no restriction on size, so resizing
  1590. * will be attempted.
  1591. * @param $minimum_dimensions
  1592. * An optional string in the form WIDTHxHEIGHT. This will check that the
  1593. * image meets a minimum size. A value of 0 indicates no restriction.
  1594. *
  1595. * @return
  1596. * An array. If the file is an image and did not meet the requirements, it
  1597. * will contain an error message.
  1598. *
  1599. * @see hook_file_validate()
  1600. */
  1601. function file_validate_image_resolution(stdClass $file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
  1602. $errors = array();
  1603. // Check first that the file is an image.
  1604. if ($info = image_get_info($file->uri)) {
  1605. if ($maximum_dimensions) {
  1606. // Check that it is smaller than the given dimensions.
  1607. list($width, $height) = explode('x', $maximum_dimensions);
  1608. if ($info['width'] > $width || $info['height'] > $height) {
  1609. // Try to resize the image to fit the dimensions.
  1610. if ($image = image_load($file->uri)) {
  1611. image_scale($image, $width, $height);
  1612. image_save($image);
  1613. $file->filesize = $image->info['file_size'];
  1614. drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));
  1615. }
  1616. else {
  1617. $errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions));
  1618. }
  1619. }
  1620. }
  1621. if ($minimum_dimensions) {
  1622. // Check that it is larger than the given dimensions.
  1623. list($width, $height) = explode('x', $minimum_dimensions);
  1624. if ($info['width'] < $width || $info['height'] < $height) {
  1625. $errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', array('%dimensions' => $minimum_dimensions));
  1626. }
  1627. }
  1628. }
  1629. return $errors;
  1630. }
  1631. /**
  1632. * Save a string to the specified destination and create a database file entry.
  1633. *
  1634. * @param $data
  1635. * A string containing the contents of the file.
  1636. * @param $destination
  1637. * A string containing the destination URI. This must be a stream wrapper URI.
  1638. * If no value is provided, a randomized name will be generated and the file
  1639. * will be saved using Drupal's default files scheme, usually "public://".
  1640. * @param $replace
  1641. * Replace behavior when the destination file already exists:
  1642. * - FILE_EXISTS_REPLACE - Replace the existing file. If a managed file with
  1643. * the destination name exists then its database entry will be updated. If
  1644. * no database entry is found then a new one will be created.
  1645. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  1646. * unique.
  1647. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  1648. *
  1649. * @return
  1650. * A file object, or FALSE on error.
  1651. *
  1652. * @see file_unmanaged_save_data()
  1653. */
  1654. function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  1655. global $user;
  1656. if (empty($destination)) {
  1657. $destination = file_default_scheme() . '://';
  1658. }
  1659. if (!file_valid_uri($destination)) {
  1660. 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));
  1661. drupal_set_message(t('The data could not be saved, because the destination is invalid. More information is available in the system log.'), 'error');
  1662. return FALSE;
  1663. }
  1664. if ($uri = file_unmanaged_save_data($data, $destination, $replace)) {
  1665. // Create a file object.
  1666. $file = new stdClass();
  1667. $file->fid = NULL;
  1668. $file->uri = $uri;
  1669. $file->filename = basename($uri);
  1670. $file->filemime = file_get_mimetype($file->uri);
  1671. $file->uid = $user->uid;
  1672. $file->status = FILE_STATUS_PERMANENT;
  1673. // If we are replacing an existing file re-use its database record.
  1674. if ($replace == FILE_EXISTS_REPLACE) {
  1675. $existing_files = file_load_multiple(array(), array('uri' => $uri));
  1676. if (count($existing_files)) {
  1677. $existing = reset($existing_files);
  1678. $file->fid = $existing->fid;
  1679. $file->filename = $existing->filename;
  1680. }
  1681. }
  1682. // If we are renaming around an existing file (rather than a directory),
  1683. // use its basename for the filename.
  1684. elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
  1685. $file->filename = basename($destination);
  1686. }
  1687. return file_save($file);
  1688. }
  1689. return FALSE;
  1690. }
  1691. /**
  1692. * Save a string to the specified destination without invoking file API.
  1693. *
  1694. * This function is identical to file_save_data() except the file will not be
  1695. * saved to the {file_managed} table and none of the file_* hooks will be
  1696. * called.
  1697. *
  1698. * @param $data
  1699. * A string containing the contents of the file.
  1700. * @param $destination
  1701. * A string containing the destination location. This must be a stream wrapper
  1702. * URI. If no value is provided, a randomized name will be generated and the
  1703. * file will be saved using Drupal's default files scheme, usually "public://".
  1704. * @param $replace
  1705. * Replace behavior when the destination file already exists:
  1706. * - FILE_EXISTS_REPLACE - Replace the existing file.
  1707. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  1708. * unique.
  1709. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  1710. *
  1711. * @return
  1712. * A string with the path of the resulting file, or FALSE on error.
  1713. *
  1714. * @see file_save_data()
  1715. */
  1716. function file_unmanaged_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  1717. // Write the data to a temporary file.
  1718. $temp_name = drupal_tempnam('temporary://', 'file');
  1719. if (file_put_contents($temp_name, $data) === FALSE) {
  1720. drupal_set_message(t('The file could not be created.'), 'error');
  1721. return FALSE;
  1722. }
  1723. // Move the file to its final destination.
  1724. return file_unmanaged_move($temp_name, $destination, $replace);
  1725. }
  1726. /**
  1727. * Transfer file using HTTP to client.
  1728. *
  1729. * Pipes a file through Drupal to the client.
  1730. *
  1731. * @param $uri
  1732. * String specifying the file URI to transfer.
  1733. * @param $headers
  1734. * An array of HTTP headers to send along with file.
  1735. */
  1736. function file_transfer($uri, $headers) {
  1737. if (ob_get_level()) {
  1738. ob_end_clean();
  1739. }
  1740. foreach ($headers as $name => $value) {
  1741. drupal_add_http_header($name, $value);
  1742. }
  1743. drupal_send_headers();
  1744. $scheme = file_uri_scheme($uri);
  1745. // Transfer file in 1024 byte chunks to save memory usage.
  1746. if ($scheme && file_stream_wrapper_valid_scheme($scheme) && $fd = fopen($uri, 'rb')) {
  1747. while (!feof($fd)) {
  1748. print fread($fd, 1024);
  1749. }
  1750. fclose($fd);
  1751. }
  1752. else {
  1753. drupal_not_found();
  1754. }
  1755. drupal_exit();
  1756. }
  1757. /**
  1758. * Menu handler for private file transfers.
  1759. *
  1760. * Call modules that implement hook_file_download() to find out if a file is
  1761. * accessible and what headers it should be transferred with. If one or more
  1762. * modules returned headers the download will start with the returned headers.
  1763. * If a module returns -1 drupal_access_denied() will be returned. If the file
  1764. * exists but no modules responded drupal_access_denied() will be returned.
  1765. * If the file does not exist drupal_not_found() will be returned.
  1766. *
  1767. * @see hook_file_download()
  1768. */
  1769. function file_download() {
  1770. // Merge remainder of arguments from GET['q'], into relative file path.
  1771. $args = func_get_args();
  1772. $scheme = array_shift($args);
  1773. $target = implode('/', $args);
  1774. $uri = $scheme . '://' . $target;
  1775. if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {
  1776. // Let other modules provide headers and controls access to the file.
  1777. // module_invoke_all() uses array_merge_recursive() which merges header
  1778. // values into a new array. To avoid that and allow modules to override
  1779. // headers instead, use array_merge() to merge the returned arrays.
  1780. $headers = array();
  1781. foreach (module_implements('file_download') as $module) {
  1782. $function = $module . '_file_download';
  1783. $result = $function($uri);
  1784. if ($result == -1) {
  1785. return drupal_access_denied();
  1786. }
  1787. if (isset($result) && is_array($result)) {
  1788. $headers = array_merge($headers, $result);
  1789. }
  1790. }
  1791. if (count($headers)) {
  1792. file_transfer($uri, $headers);
  1793. }
  1794. return drupal_access_denied();
  1795. }
  1796. return drupal_not_found();
  1797. }
  1798. /**
  1799. * Finds all files that match a given mask in a given directory.
  1800. *
  1801. * Directories and files beginning with a period are excluded; this
  1802. * prevents hidden files and directories (such as SVN working directories)
  1803. * from being scanned.
  1804. *
  1805. * @param $dir
  1806. * The base directory or URI to scan, without trailing slash.
  1807. * @param $mask
  1808. * The preg_match() regular expression of the files to find.
  1809. * @param $options
  1810. * An associative array of additional options, with the following elements:
  1811. * - 'nomask': The preg_match() regular expression of the files to ignore.
  1812. * Defaults to '/(\.\.?|CVS)$/'.
  1813. * - 'callback': The callback function to call for each match. There is no
  1814. * default callback.
  1815. * - 'recurse': When TRUE, the directory scan will recurse the entire tree
  1816. * starting at the provided directory. Defaults to TRUE.
  1817. * - 'key': The key to be used for the returned associative array of files.
  1818. * Possible values are 'uri', for the file's URI; 'filename', for the
  1819. * basename of the file; and 'name' for the name of the file without the
  1820. * extension. Defaults to 'uri'.
  1821. * - 'min_depth': Minimum depth of directories to return files from. Defaults
  1822. * to 0.
  1823. * @param $depth
  1824. * Current depth of recursion. This parameter is only used internally and
  1825. * should not be passed in.
  1826. *
  1827. * @return
  1828. * An associative array (keyed on the chosen key) of objects with 'uri',
  1829. * 'filename', and 'name' members corresponding to the matching files.
  1830. */
  1831. function file_scan_directory($dir, $mask, $options = array(), $depth = 0) {
  1832. // Merge in defaults.
  1833. $options += array(
  1834. 'nomask' => '/(\.\.?|CVS)$/',
  1835. 'callback' => 0,
  1836. 'recurse' => TRUE,
  1837. 'key' => 'uri',
  1838. 'min_depth' => 0,
  1839. );
  1840. $options['key'] = in_array($options['key'], array('uri', 'filename', 'name')) ? $options['key'] : 'uri';
  1841. $files = array();
  1842. if (is_dir($dir) && $handle = opendir($dir)) {
  1843. while (FALSE !== ($filename = readdir($handle))) {
  1844. if (!preg_match($options['nomask'], $filename) && $filename[0] != '.') {
  1845. $uri = "$dir/$filename";
  1846. $uri = file_stream_wrapper_uri_normalize($uri);
  1847. if (is_dir($uri) && $options['recurse']) {
  1848. // Give priority to files in this folder by merging them in after any subdirectory files.
  1849. $files = array_merge(file_scan_directory($uri, $mask, $options, $depth + 1), $files);
  1850. }
  1851. elseif ($depth >= $options['min_depth'] && preg_match($mask, $filename)) {
  1852. // Always use this match over anything already set in $files with the
  1853. // same $$options['key'].
  1854. $file = new stdClass();
  1855. $file->uri = $uri;
  1856. $file->filename = $filename;
  1857. $file->name = pathinfo($filename, PATHINFO_FILENAME);
  1858. $key = $options['key'];
  1859. $files[$file->$key] = $file;
  1860. if ($options['callback']) {
  1861. $options['callback']($uri);
  1862. }
  1863. }
  1864. }
  1865. }
  1866. closedir($handle);
  1867. }
  1868. return $files;
  1869. }
  1870. /**
  1871. * Determine the maximum file upload size by querying the PHP settings.
  1872. *
  1873. * @return
  1874. * A file size limit in bytes based on the PHP upload_max_filesize and
  1875. * post_max_size
  1876. */
  1877. function file_upload_max_size() {
  1878. static $max_size = -1;
  1879. if ($max_size < 0) {
  1880. // Start with post_max_size.
  1881. $max_size = parse_size(ini_get('post_max_size'));
  1882. // If upload_max_size is less, then reduce. Except if upload_max_size is
  1883. // zero, which indicates no limit.
  1884. $upload_max = parse_size(ini_get('upload_max_filesize'));
  1885. if ($upload_max > 0 && $upload_max < $max_size) {
  1886. $max_size = $upload_max;
  1887. }
  1888. }
  1889. return $max_size;
  1890. }
  1891. /**
  1892. * Determine an Internet Media Type, or MIME type from a filename.
  1893. *
  1894. * @param $uri
  1895. * A string containing the URI, path, or filename.
  1896. * @param $mapping
  1897. * An optional map of extensions to their mimetypes, in the form:
  1898. * - 'mimetypes': a list of mimetypes, keyed by an identifier,
  1899. * - 'extensions': the mapping itself, an associative array in which
  1900. * the key is the extension (lowercase) and the value is the mimetype
  1901. * identifier. If $mapping is NULL file_mimetype_mapping() is called.
  1902. *
  1903. * @return
  1904. * The internet media type registered for the extension or
  1905. * application/octet-stream for unknown extensions.
  1906. *
  1907. * @see file_default_mimetype_mapping()
  1908. */
  1909. function file_get_mimetype($uri, $mapping = NULL) {
  1910. if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  1911. return $wrapper->getMimeType($uri, $mapping);
  1912. }
  1913. else {
  1914. // getMimeType() is not implementation specific, so we can directly
  1915. // call it without an instance.
  1916. return DrupalLocalStreamWrapper::getMimeType($uri, $mapping);
  1917. }
  1918. }
  1919. /**
  1920. * Set the permissions on a file or directory.
  1921. *
  1922. * This function will use the 'file_chmod_directory' and 'file_chmod_file'
  1923. * variables for the default modes for directories and uploaded/generated
  1924. * files. By default these will give everyone read access so that users
  1925. * accessing the files with a user account without the webserver group (e.g.
  1926. * via FTP) can read these files, and give group write permissions so webserver
  1927. * group members (e.g. a vhost account) can alter files uploaded and owned by
  1928. * the webserver.
  1929. *
  1930. * PHP's chmod does not support stream wrappers so we use our wrapper
  1931. * implementation which interfaces with chmod() by default. Contrib wrappers
  1932. * may override this behavior in their implementations as needed.
  1933. *
  1934. * @param $uri
  1935. * A string containing a URI file, or directory path.
  1936. * @param $mode
  1937. * Integer value for the permissions. Consult PHP chmod() documentation for
  1938. * more information.
  1939. *
  1940. * @return
  1941. * TRUE for success, FALSE in the event of an error.
  1942. *
  1943. * @ingroup php_wrappers
  1944. */
  1945. function drupal_chmod($uri, $mode = NULL) {
  1946. if (!isset($mode)) {
  1947. if (is_dir($uri)) {
  1948. $mode = variable_get('file_chmod_directory', 0775);
  1949. }
  1950. else {
  1951. $mode = variable_get('file_chmod_file', 0664);
  1952. }
  1953. }
  1954. // If this URI is a stream, pass it off to the appropriate stream wrapper.
  1955. // Otherwise, attempt PHP's chmod. This allows use of drupal_chmod even
  1956. // for unmanaged files outside of the stream wrapper interface.
  1957. if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  1958. if ($wrapper->chmod($mode)) {
  1959. return TRUE;
  1960. }
  1961. }
  1962. else {
  1963. if (@chmod($uri, $mode)) {
  1964. return TRUE;
  1965. }
  1966. }
  1967. watchdog('file', 'The file permissions could not be set on %uri.', array('%uri' => $uri), WATCHDOG_ERROR);
  1968. return FALSE;
  1969. }
  1970. /**
  1971. * Deletes a file.
  1972. *
  1973. * PHP's unlink() is broken on Windows, as it can fail to remove a file
  1974. * when it has a read-only flag set.
  1975. *
  1976. * @param $uri
  1977. * A URI or pathname.
  1978. * @param $context
  1979. * Refer to http://php.net/manual/en/ref.stream.php
  1980. *
  1981. * @return
  1982. * Boolean TRUE on success, or FALSE on failure.
  1983. *
  1984. * @see unlink()
  1985. * @ingroup php_wrappers
  1986. */
  1987. function drupal_unlink($uri, $context = NULL) {
  1988. $scheme = file_uri_scheme($uri);
  1989. if ((!$scheme || !file_stream_wrapper_valid_scheme($scheme)) && (substr(PHP_OS, 0, 3) == 'WIN')) {
  1990. chmod($uri, 0600);
  1991. }
  1992. if ($context) {
  1993. return unlink($uri, $context);
  1994. }
  1995. else {
  1996. return unlink($uri);
  1997. }
  1998. }
  1999. /**
  2000. * Returns the absolute path of a file or directory
  2001. *
  2002. * PHP's realpath() does not properly support streams, so this function
  2003. * fills that gap. If a stream wrapped URI is provided, it will be passed
  2004. * to the registered wrapper for handling. If the URI does not contain a
  2005. * scheme or the wrapper implementation does not implement realpath, then
  2006. * FALSE will be returned.
  2007. *
  2008. * @see http://php.net/manual/en/function.realpath.php
  2009. *
  2010. * Compatibility: normal paths and stream wrappers.
  2011. * @see http://drupal.org/node/515192
  2012. *
  2013. * @param $uri
  2014. * A string containing the URI to verify.
  2015. *
  2016. * @return
  2017. * The absolute pathname, or FALSE on failure.
  2018. *
  2019. * @see realpath()
  2020. * @ingroup php_wrappers
  2021. */
  2022. function drupal_realpath($uri) {
  2023. // If this URI is a stream, pass it off to the appropriate stream wrapper.
  2024. // Otherwise, attempt PHP's realpath. This allows use of drupal_realpath even
  2025. // for unmanaged files outside of the stream wrapper interface.
  2026. if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  2027. return $wrapper->realpath();
  2028. }
  2029. // Check that the uri has a value. There is a bug in PHP 5.2 on *BSD systems
  2030. // that makes realpath not return FALSE as expected when passing an empty
  2031. // variable.
  2032. // @todo Remove when Drupal drops support for PHP 5.2.
  2033. elseif (!empty($uri)) {
  2034. return realpath($uri);
  2035. }
  2036. return FALSE;
  2037. }
  2038. /**
  2039. * Gets the name of the directory from a given path.
  2040. *
  2041. * PHP's dirname() does not properly pass streams, so this function fills
  2042. * that gap. It is backwards compatible with normal paths and will use
  2043. * PHP's dirname() as a fallback.
  2044. *
  2045. * Compatibility: normal paths and stream wrappers.
  2046. * @see http://drupal.org/node/515192
  2047. *
  2048. * @param $uri
  2049. * A URI or path.
  2050. *
  2051. * @return
  2052. * A string containing the directory name.
  2053. *
  2054. * @see dirname()
  2055. * @ingroup php_wrappers
  2056. */
  2057. function drupal_dirname($uri) {
  2058. $scheme = file_uri_scheme($uri);
  2059. if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
  2060. return file_stream_wrapper_get_instance_by_scheme($scheme)->dirname($uri);
  2061. }
  2062. else {
  2063. return dirname($uri);
  2064. }
  2065. }
  2066. /**
  2067. * Creates a directory using Drupal's default mode.
  2068. *
  2069. * PHP's mkdir() does not respect Drupal's default permissions mode. If a mode
  2070. * is not provided, this function will make sure that Drupal's is used.
  2071. *
  2072. * Compatibility: normal paths and stream wrappers.
  2073. * @see http://drupal.org/node/515192
  2074. *
  2075. * @param $uri
  2076. * A URI or pathname.
  2077. * @param $mode
  2078. * By default the Drupal mode is used.
  2079. * @param $recursive
  2080. * Default to FALSE.
  2081. * @param $context
  2082. * Refer to http://php.net/manual/en/ref.stream.php
  2083. *
  2084. * @return
  2085. * Boolean TRUE on success, or FALSE on failure.
  2086. *
  2087. * @see mkdir()
  2088. * @ingroup php_wrappers
  2089. */
  2090. function drupal_mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL) {
  2091. if (!isset($mode)) {
  2092. $mode = variable_get('file_chmod_directory', 0775);
  2093. }
  2094. if (!isset($context)) {
  2095. return mkdir($uri, $mode, $recursive);
  2096. }
  2097. else {
  2098. return mkdir($uri, $mode, $recursive, $context);
  2099. }
  2100. }
  2101. /**
  2102. * Remove a directory.
  2103. *
  2104. * PHP's rmdir() is broken on Windows, as it can fail to remove a directory
  2105. * when it has a read-only flag set.
  2106. *
  2107. * @param $uri
  2108. * A URI or pathname.
  2109. * @param $context
  2110. * Refer to http://php.net/manual/en/ref.stream.php
  2111. *
  2112. * @return
  2113. * Boolean TRUE on success, or FALSE on failure.
  2114. *
  2115. * @see rmdir()
  2116. * @ingroup php_wrappers
  2117. */
  2118. function drupal_rmdir($uri, $context = NULL) {
  2119. $scheme = file_uri_scheme($uri);
  2120. if ((!$scheme || !file_stream_wrapper_valid_scheme($scheme)) && (substr(PHP_OS, 0, 3) == 'WIN')) {
  2121. chmod($uri, 0700);
  2122. }
  2123. if ($context) {
  2124. return rmdir($uri, $context);
  2125. }
  2126. else {
  2127. return rmdir($uri);
  2128. }
  2129. }
  2130. /**
  2131. * Creates a file with a unique filename in the specified directory.
  2132. *
  2133. * PHP's tempnam() does not return a URI like we want. This function
  2134. * will return a URI if given a URI, or it will return a filepath if
  2135. * given a filepath.
  2136. *
  2137. * Compatibility: normal paths and stream wrappers.
  2138. * @see http://drupal.org/node/515192
  2139. *
  2140. * @param $directory
  2141. * The directory where the temporary filename will be created.
  2142. * @param $prefix
  2143. * The prefix of the generated temporary filename.
  2144. * Note: Windows uses only the first three characters of prefix.
  2145. *
  2146. * @return
  2147. * The new temporary filename, or FALSE on failure.
  2148. *
  2149. * @see tempnam()
  2150. * @ingroup php_wrappers
  2151. */
  2152. function drupal_tempnam($directory, $prefix) {
  2153. $scheme = file_uri_scheme($directory);
  2154. if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
  2155. $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
  2156. if ($filename = tempnam($wrapper->getDirectoryPath(), $prefix)) {
  2157. return $scheme . '://' . basename($filename);
  2158. }
  2159. else {
  2160. return FALSE;
  2161. }
  2162. }
  2163. else {
  2164. // Handle as a normal tempnam() call.
  2165. return tempnam($directory, $prefix);
  2166. }
  2167. }
  2168. /**
  2169. * Get the path of system-appropriate temporary directory.
  2170. */
  2171. function file_directory_temp() {
  2172. $temporary_directory = variable_get('file_temporary_path', NULL);
  2173. if (empty($temporary_directory)) {
  2174. $directories = array();
  2175. // Has PHP been set with an upload_tmp_dir?
  2176. if (ini_get('upload_tmp_dir')) {
  2177. $directories[] = ini_get('upload_tmp_dir');
  2178. }
  2179. // Operating system specific dirs.
  2180. if (substr(PHP_OS, 0, 3) == 'WIN') {
  2181. $directories[] = 'c:\\windows\\temp';
  2182. $directories[] = 'c:\\winnt\\temp';
  2183. }
  2184. else {
  2185. $directories[] = '/tmp';
  2186. }
  2187. // PHP may be able to find an alternative tmp directory.
  2188. // This function exists in PHP 5 >= 5.2.1, but Drupal
  2189. // requires PHP 5 >= 5.2.0, so we check for it.
  2190. if (function_exists('sys_get_temp_dir')) {
  2191. $directories[] = sys_get_temp_dir();
  2192. }
  2193. foreach ($directories as $directory) {
  2194. if (is_dir($directory) && is_writable($directory)) {
  2195. $temporary_directory = $directory;
  2196. break;
  2197. }
  2198. }
  2199. if (empty($temporary_directory)) {
  2200. // If no directory has been found default to 'files/tmp'.
  2201. $temporary_directory = variable_get('file_public_path', conf_path() . '/files') . '/tmp';
  2202. // Windows accepts paths with either slash (/) or backslash (\), but will
  2203. // not accept a path which contains both a slash and a backslash. Since
  2204. // the 'file_public_path' variable may have either format, we sanitize
  2205. // everything to use slash which is supported on all platforms.
  2206. $temporary_directory = str_replace('\\', '/', $temporary_directory);
  2207. }
  2208. // Save the path of the discovered directory.
  2209. variable_set('file_temporary_path', $temporary_directory);
  2210. }
  2211. return $temporary_directory;
  2212. }
  2213. /**
  2214. * Examines a file object and returns appropriate content headers for download.
  2215. *
  2216. * @param $file
  2217. * A file object.
  2218. * @return
  2219. * An associative array of headers, as expected by file_transfer().
  2220. */
  2221. function file_get_content_headers($file) {
  2222. $name = mime_header_encode($file->filename);
  2223. $type = mime_header_encode($file->filemime);
  2224. // Serve images, text, and flash content for display rather than download.
  2225. $inline_types = variable_get('file_inline_types', array('^text/', '^image/', 'flash$'));
  2226. $disposition = 'attachment';
  2227. foreach ($inline_types as $inline_type) {
  2228. // Exclamation marks are used as delimiters to avoid escaping slashes.
  2229. if (preg_match('!' . $inline_type . '!', $file->filemime)) {
  2230. $disposition = 'inline';
  2231. }
  2232. }
  2233. return array(
  2234. 'Content-Type' => $type . '; name="' . $name . '"',
  2235. 'Content-Length' => $file->filesize,
  2236. 'Content-Disposition' => $disposition . '; filename="' . $name . '"',
  2237. 'Cache-Control' => 'private',
  2238. );
  2239. }
  2240. /**
  2241. * @} End of "defgroup file".
  2242. */