file.inc

  1. drupal
    1. 4.6 includes/file.inc
    2. 4.7 includes/file.inc
    3. 5 includes/file.inc
    4. 6 includes/file.inc
    5. 7 includes/file.inc
    6. 8 core/includes/file.inc

API for handling file uploads and server file management.

Functions & methods

NameDescription
file_check_directoryChecks whether a directory exists and is writable.
file_check_locationCheck if a file is really located inside $directory. Should be used to make sure a file specified is really located within the directory to prevent exploits.
file_check_pathChecks path to see if it is a directory, or a dir/file.
file_copyCopies a file to a new location.
file_create_filenameCreate a full file path from a directory and filename. If a file with the specified name already exists, an alternative will be used.
file_create_pathMake sure the destination is a complete path and resides in the file system directory, if it is not prepend the file system directory.
file_create_urlCreate the download path to a file.
file_deleteDelete a file.
file_destinationDetermines the destination path for a file depending on how replacement of existing files should be handled.
file_directory_pathDetermine the default 'files' directory.
file_directory_tempDetermine the default temporary directory.
file_downloadCall modules that implement hook_file_download() to find out if a file is accessible and what headers it should be transferred with. If a module returns -1 drupal_access_denied() will be returned. If one or more modules returned headers the download…
file_get_mimetypeDetermine an Internet Media Type, or MIME type from a filename.
file_moveMoves a file to a new location.
file_munge_filenameModify a filename as needed for security purposes.
file_save_dataSave a string to the specified destination.
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_set_statusSet the status of a file.
file_space_usedDetermine total disk space used by a single user or the whole filesystem.
file_transferTransfer file using http to client. Pipes a file through Drupal to the client.
file_unmunge_filenameUndo the effect of upload_munge_filename().
file_upload_max_sizeDetermine the maximum file upload size by querying the PHP settings.
file_validate_extensionsCheck that the filename ends with an allowed extension. This check is not enforced for the user #1.
file_validate_image_resolutionIf the file is an image verify that its dimensions are within the specified maximum and minimum dimensions. Non-image files will be ignored.
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. This check is not enforced for the user #1.

Constants

NameDescription
FILE_CREATE_DIRECTORY
FILE_DOWNLOADS_PRIVATE
FILE_DOWNLOADS_PUBLIC
FILE_EXISTS_ERROR
FILE_EXISTS_RENAME
FILE_EXISTS_REPLACE
FILE_MODIFY_PERMISSIONS
FILE_STATUS_PERMANENT
FILE_STATUS_TEMPORARYA files status can be one of two values: temporary or permanent. The status for each file Drupal manages is stored in the {files} tables. If the status is temporary Drupal's file garbage collection will delete the file and remove it from the…

File

includes/file.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * API for handling file uploads and server file management.
  5. */
  6. /**
  7. * @defgroup file File interface
  8. * @{
  9. * Common file handling functions.
  10. */
  11. define('FILE_DOWNLOADS_PUBLIC', 1);
  12. define('FILE_DOWNLOADS_PRIVATE', 2);
  13. define('FILE_CREATE_DIRECTORY', 1);
  14. define('FILE_MODIFY_PERMISSIONS', 2);
  15. define('FILE_EXISTS_RENAME', 0);
  16. define('FILE_EXISTS_REPLACE', 1);
  17. define('FILE_EXISTS_ERROR', 2);
  18. /**
  19. * A files status can be one of two values: temporary or permanent. The status
  20. * for each file Drupal manages is stored in the {files} tables. If the status
  21. * is temporary Drupal's file garbage collection will delete the file and
  22. * remove it from the files table after a set period of time.
  23. *
  24. * If you wish to add custom statuses for use by contrib modules please expand as
  25. * binary flags and consider the first 8 bits reserved. (0,1,2,4,8,16,32,64,128)
  26. */
  27. define('FILE_STATUS_TEMPORARY', 0);
  28. define('FILE_STATUS_PERMANENT', 1);
  29. /**
  30. * Create the download path to a file.
  31. *
  32. * @param $path A string containing the path of the file to generate URL for.
  33. * @return A string containing a URL that can be used to download the file.
  34. */
  35. function file_create_url($path) {
  36. // Strip file_directory_path from $path. We only include relative paths in urls.
  37. if (strpos($path, file_directory_path() .'/') === 0) {
  38. $path = trim(substr($path, strlen(file_directory_path())), '\\/');
  39. }
  40. switch (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC)) {
  41. case FILE_DOWNLOADS_PUBLIC:
  42. return $GLOBALS['base_url'] .'/'. file_directory_path() .'/'. str_replace('\\', '/', $path);
  43. case FILE_DOWNLOADS_PRIVATE:
  44. return url('system/files/'. $path, array('absolute' => TRUE));
  45. }
  46. }
  47. /**
  48. * Make sure the destination is a complete path and resides in the file system
  49. * directory, if it is not prepend the file system directory.
  50. *
  51. * @param $dest A string containing the path to verify. If this value is
  52. * omitted, Drupal's 'files' directory will be used.
  53. * @return A string containing the path to file, with file system directory
  54. * appended if necessary, or FALSE if the path is invalid (i.e. outside the
  55. * configured 'files' or temp directories).
  56. */
  57. function file_create_path($dest = 0) {
  58. $file_path = file_directory_path();
  59. if (!$dest) {
  60. return $file_path;
  61. }
  62. // file_check_location() checks whether the destination is inside the Drupal files directory.
  63. if (file_check_location($dest, $file_path)) {
  64. return $dest;
  65. }
  66. // check if the destination is instead inside the Drupal temporary files directory.
  67. else if (file_check_location($dest, file_directory_temp())) {
  68. return $dest;
  69. }
  70. // Not found, try again with prefixed directory path.
  71. else if (file_check_location($file_path .'/'. $dest, $file_path)) {
  72. return $file_path .'/'. $dest;
  73. }
  74. // File not found.
  75. return FALSE;
  76. }
  77. /**
  78. * Checks whether a directory exists and is writable.
  79. *
  80. * Furthermore, the directory can optionally be created if it does not exist,
  81. * and/or be set to writable if it is currently not. Directories need to have
  82. * execute permission to be considered a directory by FTP servers.
  83. *
  84. * @param $directory
  85. * A string representing the directory path.
  86. * @param $mode
  87. * An optional bitmask containing the actions, if any, to be carried out on
  88. * the directory. Any combination of the actions FILE_CREATE_DIRECTORY and
  89. * FILE_MODIFY_PERMISSIONS is allowed.
  90. * @param $form_item
  91. * An optional string containing the name of a form item that any errors
  92. * will be attached to. Useful when the function validates a directory path
  93. * entered as a form value. An error will consequently prevent form submit
  94. * handlers from running, and instead display the form along with the
  95. * error messages.
  96. *
  97. * @return
  98. * FALSE if the directory does not exist or is not writable, even after
  99. * any optional actions have been carried out. Otherwise, TRUE is returned.
  100. */
  101. function file_check_directory(&$directory, $mode = 0, $form_item = NULL) {
  102. $directory = rtrim($directory, '/\\');
  103. // Check if directory exists.
  104. if (!is_dir($directory)) {
  105. if (($mode & FILE_CREATE_DIRECTORY) && @mkdir($directory)) {
  106. drupal_set_message(t('The directory %directory has been created.', array('%directory' => $directory)));
  107. @chmod($directory, 0775); // Necessary for non-webserver users.
  108. }
  109. else {
  110. if ($form_item) {
  111. form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => $directory)));
  112. }
  113. return FALSE;
  114. }
  115. }
  116. // Check to see if the directory is writable.
  117. if (!is_writable($directory)) {
  118. if (($mode & FILE_MODIFY_PERMISSIONS) && @chmod($directory, 0775)) {
  119. drupal_set_message(t('The permissions of directory %directory have been changed to make it writable.', array('%directory' => $directory)));
  120. }
  121. else {
  122. form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => $directory)));
  123. watchdog('file system', 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => $directory), WATCHDOG_ERROR);
  124. return FALSE;
  125. }
  126. }
  127. if ((file_directory_path() == $directory || file_directory_temp() == $directory) && !is_file("$directory/.htaccess")) {
  128. $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
  129. if (($fp = fopen("$directory/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
  130. fclose($fp);
  131. chmod($directory .'/.htaccess', 0664);
  132. }
  133. else {
  134. $variables = array('%directory' => $directory, '!htaccess' => '<br />'. nl2br(check_plain($htaccess_lines)));
  135. form_set_error($form_item, t("Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines: <code>!htaccess</code>", $variables));
  136. 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);
  137. }
  138. }
  139. return TRUE;
  140. }
  141. /**
  142. * Checks path to see if it is a directory, or a dir/file.
  143. *
  144. * @param $path A string containing a file path. This will be set to the
  145. * directory's path.
  146. * @return If the directory is not in a Drupal writable directory, FALSE is
  147. * returned. Otherwise, the base name of the path is returned.
  148. */
  149. function file_check_path(&$path) {
  150. // Check if path is a directory.
  151. if (file_check_directory($path)) {
  152. return '';
  153. }
  154. // Check if path is a possible dir/file.
  155. $filename = basename($path);
  156. $path = dirname($path);
  157. if (file_check_directory($path)) {
  158. return $filename;
  159. }
  160. return FALSE;
  161. }
  162. /**
  163. * Check if a file is really located inside $directory. Should be used to make
  164. * sure a file specified is really located within the directory to prevent
  165. * exploits.
  166. *
  167. * @code
  168. * // Returns FALSE:
  169. * file_check_location('/www/example.com/files/../../../etc/passwd', '/www/example.com/files');
  170. * @endcode
  171. *
  172. * @param $source A string set to the file to check.
  173. * @param $directory A string where the file should be located.
  174. * @return 0 for invalid path or the real path of the source.
  175. */
  176. function file_check_location($source, $directory = '') {
  177. $check = realpath($source);
  178. if ($check) {
  179. $source = $check;
  180. }
  181. else {
  182. // This file does not yet exist
  183. $source = realpath(dirname($source)) .'/'. basename($source);
  184. }
  185. $directory = realpath($directory);
  186. if ($directory && strpos($source, $directory) !== 0) {
  187. return 0;
  188. }
  189. return $source;
  190. }
  191. /**
  192. * Copies a file to a new location.
  193. *
  194. * This is a powerful function that in many ways performs like an advanced
  195. * version of copy().
  196. * - Checks if $source and $dest are valid and readable/writable.
  197. * - Performs a file copy if $source is not equal to $dest.
  198. * - If file already exists in $dest either the call will error out, replace the
  199. * file or rename the file based on the $replace parameter.
  200. *
  201. * @param $source
  202. * Either a string specifying the file location of the original file or an
  203. * object containing a 'filepath' property. This parameter is passed by
  204. * reference and will contain the resulting destination filename in case of
  205. * success.
  206. * @param $dest
  207. * A string containing the directory $source should be copied to. If this
  208. * value is omitted, Drupal's 'files' directory will be used.
  209. * @param $replace
  210. * Replace behavior when the destination file already exists.
  211. * - FILE_EXISTS_REPLACE: Replace the existing file.
  212. * - FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is
  213. * unique.
  214. * - FILE_EXISTS_ERROR: Do nothing and return FALSE.
  215. * @return
  216. * TRUE for success, FALSE for failure.
  217. */
  218. function file_copy(&$source, $dest = 0, $replace = FILE_EXISTS_RENAME) {
  219. $dest = file_create_path($dest);
  220. $directory = $dest;
  221. $basename = file_check_path($directory);
  222. // Make sure we at least have a valid directory.
  223. if ($basename === FALSE) {
  224. $source = is_object($source) ? $source->filepath : $source;
  225. drupal_set_message(t('The selected file %file could not be uploaded, because the destination %directory is not properly configured.', array('%file' => $source, '%directory' => $dest)), 'error');
  226. watchdog('file system', 'The selected file %file could not be uploaded, because the destination %directory could not be found, or because its permissions do not allow the file to be written.', array('%file' => $source, '%directory' => $dest), WATCHDOG_ERROR);
  227. return 0;
  228. }
  229. // Process a file upload object.
  230. if (is_object($source)) {
  231. $file = $source;
  232. $source = $file->filepath;
  233. if (!$basename) {
  234. $basename = $file->filename;
  235. }
  236. }
  237. $source = realpath($source);
  238. if (!file_exists($source)) {
  239. drupal_set_message(t('The selected file %file could not be copied, because no file by that name exists. Please check that you supplied the correct filename.', array('%file' => $source)), 'error');
  240. return 0;
  241. }
  242. // If the destination file is not specified then use the filename of the source file.
  243. $basename = $basename ? $basename : basename($source);
  244. $dest = $directory .'/'. $basename;
  245. // Make sure source and destination filenames are not the same, makes no sense
  246. // to copy it if they are. In fact copying the file will most likely result in
  247. // a 0 byte file. Which is bad. Real bad.
  248. if ($source != realpath($dest)) {
  249. if (!$dest = file_destination($dest, $replace)) {
  250. drupal_set_message(t('The selected file %file could not be copied, because a file by that name already exists in the destination.', array('%file' => $source)), 'error');
  251. return FALSE;
  252. }
  253. if (!@copy($source, $dest)) {
  254. drupal_set_message(t('The selected file %file could not be copied.', array('%file' => $source)), 'error');
  255. return 0;
  256. }
  257. // Give everyone read access so that FTP'd users or
  258. // non-webserver users can see/read these files,
  259. // and give group write permissions so group members
  260. // can alter files uploaded by the webserver.
  261. @chmod($dest, 0664);
  262. }
  263. if (isset($file) && is_object($file)) {
  264. $file->filename = $basename;
  265. $file->filepath = $dest;
  266. $source = $file;
  267. }
  268. else {
  269. $source = $dest;
  270. }
  271. return 1; // Everything went ok.
  272. }
  273. /**
  274. * Determines the destination path for a file depending on how replacement of
  275. * existing files should be handled.
  276. *
  277. * @param $destination A string specifying the desired path.
  278. * @param $replace Replace behavior when the destination file already exists.
  279. * - FILE_EXISTS_REPLACE - Replace the existing file
  280. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
  281. * unique
  282. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  283. * @return The destination file path or FALSE if the file already exists and
  284. * FILE_EXISTS_ERROR was specified.
  285. */
  286. function file_destination($destination, $replace) {
  287. if (file_exists($destination)) {
  288. switch ($replace) {
  289. case FILE_EXISTS_RENAME:
  290. $basename = basename($destination);
  291. $directory = dirname($destination);
  292. $destination = file_create_filename($basename, $directory);
  293. break;
  294. case FILE_EXISTS_ERROR:
  295. drupal_set_message(t('The selected file %file could not be copied, because a file by that name already exists in the destination.', array('%file' => $destination)), 'error');
  296. return FALSE;
  297. }
  298. }
  299. return $destination;
  300. }
  301. /**
  302. * Moves a file to a new location.
  303. *
  304. * - Checks if $source and $dest are valid and readable/writable.
  305. * - Performs a file move if $source is not equal to $dest.
  306. * - If file already exists in $dest either the call will error out, replace the
  307. * file or rename the file based on the $replace parameter.
  308. *
  309. * @param $source
  310. * Either a string specifying the file location of the original file or an
  311. * object containing a 'filepath' property. This parameter is passed by
  312. * reference and will contain the resulting destination filename in case of
  313. * success.
  314. * @param $dest
  315. * A string containing the directory $source should be copied to. If this
  316. * value is omitted, Drupal's 'files' directory will be used.
  317. * @param $replace
  318. * Replace behavior when the destination file already exists.
  319. * - FILE_EXISTS_REPLACE: Replace the existing file.
  320. * - FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is
  321. * unique.
  322. * - FILE_EXISTS_ERROR: Do nothing and return FALSE.
  323. * @return
  324. * TRUE for success, FALSE for failure.
  325. */
  326. function file_move(&$source, $dest = 0, $replace = FILE_EXISTS_RENAME) {
  327. $path_original = is_object($source) ? $source->filepath : $source;
  328. if (file_copy($source, $dest, $replace)) {
  329. $path_current = is_object($source) ? $source->filepath : $source;
  330. if ($path_original == $path_current || file_delete($path_original)) {
  331. return 1;
  332. }
  333. drupal_set_message(t('The removal of the original file %file has failed.', array('%file' => $path_original)), 'error');
  334. }
  335. return 0;
  336. }
  337. /**
  338. * Modify a filename as needed for security purposes.
  339. *
  340. * Munging a file name prevents unknown file extensions from masking exploit
  341. * files. When web servers such as Apache decide how to process a URL request,
  342. * they use the file extension. If the extension is not recognized, Apache
  343. * skips that extension and uses the previous file extension. For example, if
  344. * the file being requested is exploit.php.pps, and Apache does not recognize
  345. * the '.pps' extension, it treats the file as PHP and executes it. To make
  346. * this file name safe for Apache and prevent it from executing as PHP, the
  347. * .php extension is "munged" into .php_, making the safe file name
  348. * exploit.php_.pps.
  349. *
  350. * Specifically, this function adds an underscore to all extensions that are
  351. * between 2 and 5 characters in length, internal to the file name, and not
  352. * included in $extensions.
  353. *
  354. * Function behavior is also controlled by the Drupal variable
  355. * 'allow_insecure_uploads'. If 'allow_insecure_uploads' evaluates to TRUE, no
  356. * alterations will be made, if it evaluates to FALSE, the filename is 'munged'.
  357. *
  358. * @param $filename
  359. * File name to modify.
  360. * @param $extensions
  361. * A space-separated list of extensions that should not be altered.
  362. * @param $alerts
  363. * If TRUE, drupal_set_message() will be called to display a message if the
  364. * file name was changed.
  365. *
  366. * @return
  367. * The potentially modified $filename.
  368. */
  369. function file_munge_filename($filename, $extensions, $alerts = TRUE) {
  370. $original = $filename;
  371. // Allow potentially insecure uploads for very savvy users and admin
  372. if (!variable_get('allow_insecure_uploads', 0)) {
  373. $whitelist = array_unique(explode(' ', trim($extensions)));
  374. // Split the filename up by periods. The first part becomes the basename
  375. // the last part the final extension.
  376. $filename_parts = explode('.', $filename);
  377. $new_filename = array_shift($filename_parts); // Remove file basename.
  378. $final_extension = array_pop($filename_parts); // Remove final extension.
  379. // Loop through the middle parts of the name and add an underscore to the
  380. // end of each section that could be a file extension but isn't in the list
  381. // of allowed extensions.
  382. foreach ($filename_parts as $filename_part) {
  383. $new_filename .= '.'. $filename_part;
  384. if (!in_array($filename_part, $whitelist) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $filename_part)) {
  385. $new_filename .= '_';
  386. }
  387. }
  388. $filename = $new_filename .'.'. $final_extension;
  389. if ($alerts && $original != $filename) {
  390. drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $filename)));
  391. }
  392. }
  393. return $filename;
  394. }
  395. /**
  396. * Undo the effect of upload_munge_filename().
  397. *
  398. * @param $filename string filename
  399. * @return string
  400. */
  401. function file_unmunge_filename($filename) {
  402. return str_replace('_.', '.', $filename);
  403. }
  404. /**
  405. * Create a full file path from a directory and filename. If a file with the
  406. * specified name already exists, an alternative will be used.
  407. *
  408. * @param $basename string filename
  409. * @param $directory string directory
  410. * @return
  411. */
  412. function file_create_filename($basename, $directory) {
  413. $dest = $directory .'/'. $basename;
  414. if (file_exists($dest)) {
  415. // Destination file already exists, generate an alternative.
  416. if ($pos = strrpos($basename, '.')) {
  417. $name = substr($basename, 0, $pos);
  418. $ext = substr($basename, $pos);
  419. }
  420. else {
  421. $name = $basename;
  422. $ext = '';
  423. }
  424. $counter = 0;
  425. do {
  426. $dest = $directory .'/'. $name .'_'. $counter++ . $ext;
  427. } while (file_exists($dest));
  428. }
  429. return $dest;
  430. }
  431. /**
  432. * Delete a file.
  433. *
  434. * @param $path A string containing a file path.
  435. * @return TRUE for success, FALSE for failure.
  436. */
  437. function file_delete($path) {
  438. if (is_file($path)) {
  439. return unlink($path);
  440. }
  441. }
  442. /**
  443. * Determine total disk space used by a single user or the whole filesystem.
  444. *
  445. * @param $uid
  446. * An optional user id. A NULL value returns the total space used
  447. * by all files.
  448. */
  449. function file_space_used($uid = NULL) {
  450. if (isset($uid)) {
  451. return (int) db_result(db_query('SELECT SUM(filesize) FROM {files} WHERE uid = %d', $uid));
  452. }
  453. return (int) db_result(db_query('SELECT SUM(filesize) FROM {files}'));
  454. }
  455. /**
  456. * Saves a file upload to a new location.
  457. *
  458. * The source file is validated as a proper upload and handled as such.
  459. * The file will be added to the files table as a temporary file. Temporary
  460. * files are periodically cleaned. To make the file permanent file call
  461. * file_set_status() to change its status.
  462. *
  463. * @param $source
  464. * A string specifying the name of the upload field to save.
  465. * @param $validators
  466. * (optional) An associative array of callback functions used to validate the
  467. * file. The keys are function names and the values arrays of callback
  468. * parameters which will be passed in after the file object. The
  469. * functions should return an array of error messages; an empty array
  470. * indicates that the file passed validation. The functions will be called in
  471. * the order specified.
  472. * @param $dest
  473. * A string containing the directory $source should be copied to. If this is
  474. * not provided or is not writable, the temporary directory will be used.
  475. * @param $replace
  476. * Replace behavior when the destination file already exists:
  477. * - FILE_EXISTS_REPLACE: Replace the existing file.
  478. * - FILE_EXISTS_RENAME: Append _{incrementing number} until the filename
  479. * is unique.
  480. * - FILE_EXISTS_ERROR: Do nothing and return FALSE.
  481. *
  482. * @return
  483. * An object containing the file information, or 0 in the event of an error.
  484. */
  485. function file_save_upload($source, $validators = array(), $dest = FALSE, $replace = FILE_EXISTS_RENAME) {
  486. global $user;
  487. static $upload_cache;
  488. // Add in our check of the the file name length.
  489. $validators['file_validate_name_length'] = array();
  490. // Return cached objects without processing since the file will have
  491. // already been processed and the paths in _FILES will be invalid.
  492. if (isset($upload_cache[$source])) {
  493. return $upload_cache[$source];
  494. }
  495. // If a file was uploaded, process it.
  496. if (isset($_FILES['files']) && $_FILES['files']['name'][$source] && is_uploaded_file($_FILES['files']['tmp_name'][$source])) {
  497. // Check for file upload errors and return FALSE if a
  498. // lower level system error occurred.
  499. switch ($_FILES['files']['error'][$source]) {
  500. // @see http://php.net/manual/en/features.file-upload.errors.php
  501. case UPLOAD_ERR_OK:
  502. break;
  503. case UPLOAD_ERR_INI_SIZE:
  504. case UPLOAD_ERR_FORM_SIZE:
  505. drupal_set_message(t('The file %file could not be saved, because it exceeds %maxsize, the maximum allowed size for uploads.', array('%file' => $source, '%maxsize' => format_size(file_upload_max_size()))), 'error');
  506. return 0;
  507. case UPLOAD_ERR_PARTIAL:
  508. case UPLOAD_ERR_NO_FILE:
  509. drupal_set_message(t('The file %file could not be saved, because the upload did not complete.', array('%file' => $source)), 'error');
  510. return 0;
  511. // Unknown error
  512. default:
  513. drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', array('%file' => $source)), 'error');
  514. return 0;
  515. }
  516. // Build the list of non-munged extensions.
  517. // @todo: this should not be here. we need to figure out the right place.
  518. $extensions = '';
  519. foreach ($user->roles as $rid => $name) {
  520. $extensions .= ' '. variable_get("upload_extensions_$rid",
  521. variable_get('upload_extensions_default', 'jpg jpeg gif png txt html doc xls pdf ppt pps odt ods odp'));
  522. }
  523. // Begin building file object.
  524. $file = new stdClass();
  525. $file->filename = file_munge_filename(trim(basename($_FILES['files']['name'][$source]), '.'), $extensions);
  526. $file->filepath = $_FILES['files']['tmp_name'][$source];
  527. $file->filemime = file_get_mimetype($file->filename);
  528. // If the destination is not provided, or is not writable, then use the
  529. // temporary directory.
  530. if (empty($dest) || file_check_path($dest) === FALSE) {
  531. $dest = file_directory_temp();
  532. }
  533. $file->source = $source;
  534. $file->destination = file_destination(file_create_path($dest .'/'. $file->filename), $replace);
  535. $file->filesize = $_FILES['files']['size'][$source];
  536. // Call the validation functions.
  537. $errors = array();
  538. foreach ($validators as $function => $args) {
  539. array_unshift($args, $file);
  540. // Make sure $file is passed around by reference.
  541. $args[0] = &$file;
  542. $errors = array_merge($errors, call_user_func_array($function, $args));
  543. }
  544. // Rename potentially executable files, to help prevent exploits.
  545. if (preg_match('/\.(php|pl|py|cgi|asp|js)$/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
  546. $file->filemime = 'text/plain';
  547. $file->filepath .= '.txt';
  548. $file->filename .= '.txt';
  549. // As the file may be named example.php.txt, we need to munge again to
  550. // convert to example.php_.txt, then create the correct destination.
  551. $file->filename = file_munge_filename($file->filename, $extensions);
  552. $file->destination = file_destination(file_create_path($dest .'/'. $file->filename), $replace);
  553. }
  554. // Check for validation errors.
  555. if (!empty($errors)) {
  556. $message = t('The selected file %name could not be uploaded.', array('%name' => $file->filename));
  557. if (count($errors) > 1) {
  558. $message .= '<ul><li>'. implode('</li><li>', $errors) .'</li></ul>';
  559. }
  560. else {
  561. $message .= ' '. array_pop($errors);
  562. }
  563. form_set_error($source, $message);
  564. return 0;
  565. }
  566. // Move uploaded files from PHP's upload_tmp_dir to Drupal's temporary directory.
  567. // This overcomes open_basedir restrictions for future file operations.
  568. $file->filepath = $file->destination;
  569. if (!move_uploaded_file($_FILES['files']['tmp_name'][$source], $file->filepath)) {
  570. form_set_error($source, t('File upload error. Could not move uploaded file.'));
  571. watchdog('file', 'Upload error. Could not move uploaded file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->filepath));
  572. return 0;
  573. }
  574. // If we made it this far it's safe to record this file in the database.
  575. $file->uid = $user->uid;
  576. $file->status = FILE_STATUS_TEMPORARY;
  577. $file->timestamp = time();
  578. drupal_write_record('files', $file);
  579. // Add file to the cache.
  580. $upload_cache[$source] = $file;
  581. return $file;
  582. }
  583. return 0;
  584. }
  585. /**
  586. * Check for files with names longer than we can store in the database.
  587. *
  588. * @param $file
  589. * A Drupal file object.
  590. * @return
  591. * An array. If the file name is too long, it will contain an error message.
  592. */
  593. function file_validate_name_length($file) {
  594. $errors = array();
  595. if (strlen($file->filename) > 255) {
  596. $errors[] = t('Its name exceeds the 255 characters limit. Please rename the file and try again.');
  597. }
  598. return $errors;
  599. }
  600. /**
  601. * Check that the filename ends with an allowed extension. This check is not
  602. * enforced for the user #1.
  603. *
  604. * @param $file
  605. * A Drupal file object.
  606. * @param $extensions
  607. * A string with a space separated list of allowed file extensions, not
  608. * including the period. For example, 'bmp jpg gif png'.
  609. *
  610. * @return
  611. * An array. If the file extension is not allowed, it will contain an error
  612. * message.
  613. */
  614. function file_validate_extensions($file, $extensions) {
  615. global $user;
  616. $errors = array();
  617. // Bypass validation for uid = 1.
  618. if ($user->uid != 1) {
  619. $regex = '/\.('. @ereg_replace(' +', '|', preg_quote($extensions)) .')$/i';
  620. if (!preg_match($regex, $file->filename)) {
  621. $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions));
  622. }
  623. }
  624. return $errors;
  625. }
  626. /**
  627. * Check that the file's size is below certain limits. This check is not
  628. * enforced for the user #1.
  629. *
  630. * @param $file
  631. * A Drupal file object.
  632. * @param $file_limit
  633. * An integer specifying the maximum file size in bytes. Zero indicates that
  634. * no limit should be enforced.
  635. * @param $user_limit
  636. * An integer specifying the maximum number of bytes the user is allowed. Zero
  637. * indicates that no limit should be enforced.
  638. * @return
  639. * An array. If the file size exceeds limits, it will contain an error message.
  640. */
  641. function file_validate_size($file, $file_limit = 0, $user_limit = 0) {
  642. global $user;
  643. $errors = array();
  644. // Bypass validation for uid = 1.
  645. if ($user->uid != 1) {
  646. if ($file_limit && $file->filesize > $file_limit) {
  647. $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($file_limit)));
  648. }
  649. // Save a query by only calling file_space_used() when a limit is provided.
  650. if ($user_limit && (file_space_used($user->uid) + $file->filesize) > $user_limit) {
  651. $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)));
  652. }
  653. }
  654. return $errors;
  655. }
  656. /**
  657. * Check that the file is recognized by image_get_info() as an image.
  658. *
  659. * @param $file
  660. * A Drupal file object.
  661. * @return
  662. * An array. If the file is not an image, it will contain an error message.
  663. */
  664. function file_validate_is_image(&$file) {
  665. $errors = array();
  666. $info = image_get_info($file->filepath);
  667. if (!$info || empty($info['extension'])) {
  668. $errors[] = t('Only JPEG, PNG and GIF images are allowed.');
  669. }
  670. return $errors;
  671. }
  672. /**
  673. * If the file is an image verify that its dimensions are within the specified
  674. * maximum and minimum dimensions. Non-image files will be ignored.
  675. *
  676. * @param $file
  677. * A Drupal file object. This function may resize the file affecting its size.
  678. * @param $maximum_dimensions
  679. * An optional string in the form WIDTHxHEIGHT e.g. '640x480' or '85x85'. If
  680. * an image toolkit is installed the image will be resized down to these
  681. * dimensions. A value of 0 indicates no restriction on size, so resizing
  682. * will be attempted.
  683. * @param $minimum_dimensions
  684. * An optional string in the form WIDTHxHEIGHT. This will check that the image
  685. * meets a minimum size. A value of 0 indicates no restriction.
  686. * @return
  687. * An array. If the file is an image and did not meet the requirements, it
  688. * will contain an error message.
  689. */
  690. function file_validate_image_resolution(&$file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
  691. $errors = array();
  692. // Check first that the file is an image.
  693. if ($info = image_get_info($file->filepath)) {
  694. if ($maximum_dimensions) {
  695. // Check that it is smaller than the given dimensions.
  696. list($width, $height) = explode('x', $maximum_dimensions);
  697. if ($info['width'] > $width || $info['height'] > $height) {
  698. // Try to resize the image to fit the dimensions.
  699. if (image_get_toolkit() && image_scale($file->filepath, $file->filepath, $width, $height)) {
  700. drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));
  701. // Clear the cached filesize and refresh the image information.
  702. clearstatcache();
  703. $info = image_get_info($file->filepath);
  704. $file->filesize = $info['file_size'];
  705. }
  706. else {
  707. $errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions));
  708. }
  709. }
  710. }
  711. if ($minimum_dimensions) {
  712. // Check that it is larger than the given dimensions.
  713. list($width, $height) = explode('x', $minimum_dimensions);
  714. if ($info['width'] < $width || $info['height'] < $height) {
  715. $errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', array('%dimensions' => $minimum_dimensions));
  716. }
  717. }
  718. }
  719. return $errors;
  720. }
  721. /**
  722. * Save a string to the specified destination.
  723. *
  724. * @param $data A string containing the contents of the file.
  725. * @param $dest A string containing the destination location.
  726. * @param $replace Replace behavior when the destination file already exists.
  727. * - FILE_EXISTS_REPLACE - Replace the existing file
  728. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is unique
  729. * - FILE_EXISTS_ERROR - Do nothing and return FALSE.
  730. *
  731. * @return A string containing the resulting filename or 0 on error
  732. */
  733. function file_save_data($data, $dest, $replace = FILE_EXISTS_RENAME) {
  734. $temp = file_directory_temp();
  735. // On Windows, tempnam() requires an absolute path, so we use realpath().
  736. $file = tempnam(realpath($temp), 'file');
  737. if (!$fp = fopen($file, 'wb')) {
  738. drupal_set_message(t('The file could not be created.'), 'error');
  739. return 0;
  740. }
  741. fwrite($fp, $data);
  742. fclose($fp);
  743. if (!file_move($file, $dest, $replace)) {
  744. return 0;
  745. }
  746. return $file;
  747. }
  748. /**
  749. * Set the status of a file.
  750. *
  751. * @param $file
  752. * A Drupal file object.
  753. * @param $status
  754. * A status value to set the file to. One of:
  755. * - FILE_STATUS_PERMANENT
  756. * - FILE_STATUS_TEMPORARY
  757. *
  758. * @return FALSE on failure, TRUE on success and $file->status will contain the
  759. * status.
  760. */
  761. function file_set_status(&$file, $status) {
  762. if (db_query('UPDATE {files} SET status = %d WHERE fid = %d', $status, $file->fid)) {
  763. $file->status = $status;
  764. return TRUE;
  765. }
  766. return FALSE;
  767. }
  768. /**
  769. * Transfer file using http to client. Pipes a file through Drupal to the
  770. * client.
  771. *
  772. * @param $source File to transfer.
  773. * @param $headers An array of http headers to send along with file.
  774. */
  775. function file_transfer($source, $headers) {
  776. if (ob_get_level()) {
  777. ob_end_clean();
  778. }
  779. // IE cannot download private files because it cannot store files downloaded
  780. // over https in the browser cache. The problem can be solved by sending
  781. // custom headers to IE. See http://support.microsoft.com/kb/323308/en-us
  782. if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) {
  783. drupal_set_header('Cache-Control: private');
  784. drupal_set_header('Pragma: private');
  785. }
  786. foreach ($headers as $header) {
  787. // To prevent HTTP header injection, we delete new lines that are
  788. // not followed by a space or a tab.
  789. // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
  790. $header = preg_replace('/\r?\n(?!\t| )/', '', $header);
  791. drupal_set_header($header);
  792. }
  793. $source = file_create_path($source);
  794. // Transfer file in 1024 byte chunks to save memory usage.
  795. if ($fd = fopen($source, 'rb')) {
  796. while (!feof($fd)) {
  797. print fread($fd, 1024);
  798. }
  799. fclose($fd);
  800. }
  801. else {
  802. drupal_not_found();
  803. }
  804. exit();
  805. }
  806. /**
  807. * Call modules that implement hook_file_download() to find out if a file is
  808. * accessible and what headers it should be transferred with. If a module
  809. * returns -1 drupal_access_denied() will be returned. If one or more modules
  810. * returned headers the download will start with the returned headers. If no
  811. * modules respond drupal_not_found() will be returned.
  812. */
  813. function file_download() {
  814. // Merge remainder of arguments from GET['q'], into relative file path.
  815. $args = func_get_args();
  816. $filepath = implode('/', $args);
  817. // Maintain compatibility with old ?file=paths saved in node bodies.
  818. if (isset($_GET['file'])) {
  819. $filepath = $_GET['file'];
  820. }
  821. if (file_exists(file_create_path($filepath))) {
  822. $headers = module_invoke_all('file_download', $filepath);
  823. if (in_array(-1, $headers)) {
  824. return drupal_access_denied();
  825. }
  826. if (count($headers)) {
  827. file_transfer($filepath, $headers);
  828. }
  829. }
  830. return drupal_not_found();
  831. }
  832. /**
  833. * Finds all files that match a given mask in a given directory.
  834. *
  835. * Directories and files beginning with a period are excluded; this
  836. * prevents hidden files and directories (such as SVN working directories)
  837. * from being scanned.
  838. *
  839. * @param $dir
  840. * The base directory for the scan, without trailing slash.
  841. * @param $mask
  842. * The regular expression of the files to find.
  843. * @param $nomask
  844. * An array of files/directories to ignore.
  845. * @param $callback
  846. * The callback function to call for each match.
  847. * @param $recurse
  848. * When TRUE, the directory scan will recurse the entire tree
  849. * starting at the provided directory.
  850. * @param $key
  851. * The key to be used for the returned associative array of files. Possible
  852. * values are "filename", for the path starting with $dir; "basename", for
  853. * the basename of the file; and "name" for the name of the file without the
  854. * extension.
  855. * @param $min_depth
  856. * Minimum depth of directories to return files from.
  857. * @param $depth
  858. * Current depth of recursion. This parameter is only used internally and
  859. * should not be passed in.
  860. *
  861. * @return
  862. * An associative array (keyed on the provided key) of objects with
  863. * "filename", "basename", and "name" members corresponding to the
  864. * matching files.
  865. */
  866. function file_scan_directory($dir, $mask, $nomask = array('.', '..', 'CVS'), $callback = 0, $recurse = TRUE, $key = 'filename', $min_depth = 0, $depth = 0) {
  867. $key = (in_array($key, array('filename', 'basename', 'name')) ? $key : 'filename');
  868. $files = array();
  869. if (is_dir($dir) && $handle = opendir($dir)) {
  870. while (FALSE !== ($file = readdir($handle))) {
  871. if (!in_array($file, $nomask) && $file[0] != '.') {
  872. if (is_dir("$dir/$file") && $recurse) {
  873. // Give priority to files in this folder by merging them in after any subdirectory files.
  874. $files = array_merge(file_scan_directory("$dir/$file", $mask, $nomask, $callback, $recurse, $key, $min_depth, $depth + 1), $files);
  875. }
  876. elseif ($depth >= $min_depth && @ereg($mask, $file)) {
  877. // Always use this match over anything already set in $files with the same $$key.
  878. $filename = "$dir/$file";
  879. $basename = basename($file);
  880. $name = substr($basename, 0, strrpos($basename, '.'));
  881. $files[$$key] = new stdClass();
  882. $files[$$key]->filename = $filename;
  883. $files[$$key]->basename = $basename;
  884. $files[$$key]->name = $name;
  885. if ($callback) {
  886. $callback($filename);
  887. }
  888. }
  889. }
  890. }
  891. closedir($handle);
  892. }
  893. return $files;
  894. }
  895. /**
  896. * Determine the default temporary directory.
  897. *
  898. * @return A string containing a temp directory.
  899. */
  900. function file_directory_temp() {
  901. $temporary_directory = variable_get('file_directory_temp', NULL);
  902. if (is_null($temporary_directory)) {
  903. $directories = array();
  904. // Has PHP been set with an upload_tmp_dir?
  905. if (ini_get('upload_tmp_dir')) {
  906. $directories[] = ini_get('upload_tmp_dir');
  907. }
  908. // Operating system specific dirs.
  909. if (substr(PHP_OS, 0, 3) == 'WIN') {
  910. $directories[] = 'c:\\windows\\temp';
  911. $directories[] = 'c:\\winnt\\temp';
  912. $path_delimiter = '\\';
  913. }
  914. else {
  915. $directories[] = '/tmp';
  916. $path_delimiter = '/';
  917. }
  918. foreach ($directories as $directory) {
  919. if (!$temporary_directory && is_dir($directory)) {
  920. $temporary_directory = $directory;
  921. }
  922. }
  923. // if a directory has been found, use it, otherwise default to 'files/tmp' or 'files\\tmp';
  924. $temporary_directory = $temporary_directory ? $temporary_directory : file_directory_path() . $path_delimiter .'tmp';
  925. variable_set('file_directory_temp', $temporary_directory);
  926. }
  927. return $temporary_directory;
  928. }
  929. /**
  930. * Determine the default 'files' directory.
  931. *
  932. * @return A string containing the path to Drupal's 'files' directory.
  933. */
  934. function file_directory_path() {
  935. return variable_get('file_directory_path', conf_path() .'/files');
  936. }
  937. /**
  938. * Determine the maximum file upload size by querying the PHP settings.
  939. *
  940. * @return
  941. * A file size limit in bytes based on the PHP upload_max_filesize and post_max_size
  942. */
  943. function file_upload_max_size() {
  944. static $max_size = -1;
  945. if ($max_size < 0) {
  946. $upload_max = parse_size(ini_get('upload_max_filesize'));
  947. $post_max = parse_size(ini_get('post_max_size'));
  948. $max_size = ($upload_max < $post_max) ? $upload_max : $post_max;
  949. }
  950. return $max_size;
  951. }
  952. /**
  953. * Determine an Internet Media Type, or MIME type from a filename.
  954. *
  955. * @param $filename
  956. * Name of the file, including extension.
  957. * @param $mapping
  958. * An optional array of extension to media type mappings in the form
  959. * 'extension1|extension2|...' => 'type'.
  960. *
  961. * @return
  962. * The internet media type registered for the extension or application/octet-stream for unknown extensions.
  963. */
  964. function file_get_mimetype($filename, $mapping = NULL) {
  965. if (!is_array($mapping)) {
  966. $mapping = variable_get('mime_extension_mapping', array(
  967. 'ez' => 'application/andrew-inset',
  968. 'atom' => 'application/atom',
  969. 'atomcat' => 'application/atomcat+xml',
  970. 'atomsrv' => 'application/atomserv+xml',
  971. 'cap|pcap' => 'application/cap',
  972. 'cu' => 'application/cu-seeme',
  973. 'tsp' => 'application/dsptype',
  974. 'spl' => 'application/x-futuresplash',
  975. 'hta' => 'application/hta',
  976. 'jar' => 'application/java-archive',
  977. 'ser' => 'application/java-serialized-object',
  978. 'class' => 'application/java-vm',
  979. 'hqx' => 'application/mac-binhex40',
  980. 'cpt' => 'image/x-corelphotopaint',
  981. 'nb' => 'application/mathematica',
  982. 'mdb' => 'application/msaccess',
  983. 'doc|dot' => 'application/msword',
  984. 'bin' => 'application/octet-stream',
  985. 'oda' => 'application/oda',
  986. 'ogg|ogx' => 'application/ogg',
  987. 'pdf' => 'application/pdf',
  988. 'key' => 'application/pgp-keys',
  989. 'pgp' => 'application/pgp-signature',
  990. 'prf' => 'application/pics-rules',
  991. 'ps|ai|eps' => 'application/postscript',
  992. 'rar' => 'application/rar',
  993. 'rdf' => 'application/rdf+xml',
  994. 'rss' => 'application/rss+xml',
  995. 'rtf' => 'application/rtf',
  996. 'smi|smil' => 'application/smil',
  997. 'wpd' => 'application/wordperfect',
  998. 'wp5' => 'application/wordperfect5.1',
  999. 'xhtml|xht' => 'application/xhtml+xml',
  1000. 'xml|xsl' => 'application/xml',
  1001. 'zip' => 'application/zip',
  1002. 'cdy' => 'application/vnd.cinderella',
  1003. 'kml' => 'application/vnd.google-earth.kml+xml',
  1004. 'kmz' => 'application/vnd.google-earth.kmz',
  1005. 'xul' => 'application/vnd.mozilla.xul+xml',
  1006. 'xls|xlb|xlt' => 'application/vnd.ms-excel',
  1007. 'cat' => 'application/vnd.ms-pki.seccat',
  1008. 'stl' => 'application/vnd.ms-pki.stl',
  1009. 'ppt|pps' => 'application/vnd.ms-powerpoint',
  1010. 'odc' => 'application/vnd.oasis.opendocument.chart',
  1011. 'odb' => 'application/vnd.oasis.opendocument.database',
  1012. 'odf' => 'application/vnd.oasis.opendocument.formula',
  1013. 'odg' => 'application/vnd.oasis.opendocument.graphics',
  1014. 'otg' => 'application/vnd.oasis.opendocument.graphics-template',
  1015. 'odi' => 'application/vnd.oasis.opendocument.image',
  1016. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  1017. 'otp' => 'application/vnd.oasis.opendocument.presentation-template',
  1018. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  1019. 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
  1020. 'odt' => 'application/vnd.oasis.opendocument.text',
  1021. 'odm' => 'application/vnd.oasis.opendocument.text-master',
  1022. 'ott' => 'application/vnd.oasis.opendocument.text-template',
  1023. 'oth' => 'application/vnd.oasis.opendocument.text-web',
  1024. 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
  1025. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  1026. 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
  1027. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  1028. 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
  1029. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  1030. 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
  1031. 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
  1032. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  1033. 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
  1034. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  1035. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  1036. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  1037. 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
  1038. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  1039. 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
  1040. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  1041. 'cod' => 'application/vnd.rim.cod',
  1042. 'mmf' => 'application/vnd.smaf',
  1043. 'sdc' => 'application/vnd.stardivision.calc',
  1044. 'sds' => 'application/vnd.stardivision.chart',
  1045. 'sda' => 'application/vnd.stardivision.draw',
  1046. 'sdd' => 'application/vnd.stardivision.impress',
  1047. 'sdf' => 'application/vnd.stardivision.math',
  1048. 'sdw' => 'application/vnd.stardivision.writer',
  1049. 'sgl' => 'application/vnd.stardivision.writer-global',
  1050. 'sxc' => 'application/vnd.sun.xml.calc',
  1051. 'stc' => 'application/vnd.sun.xml.calc.template',
  1052. 'sxd' => 'application/vnd.sun.xml.draw',
  1053. 'std' => 'application/vnd.sun.xml.draw.template',
  1054. 'sxi' => 'application/vnd.sun.xml.impress',
  1055. 'sti' => 'application/vnd.sun.xml.impress.template',
  1056. 'sxm' => 'application/vnd.sun.xml.math',
  1057. 'sxw' => 'application/vnd.sun.xml.writer',
  1058. 'sxg' => 'application/vnd.sun.xml.writer.global',
  1059. 'stw' => 'application/vnd.sun.xml.writer.template',
  1060. 'sis' => 'application/vnd.symbian.install',
  1061. 'vsd' => 'application/vnd.visio',
  1062. 'wbxml' => 'application/vnd.wap.wbxml',
  1063. 'wmlc' => 'application/vnd.wap.wmlc',
  1064. 'wmlsc' => 'application/vnd.wap.wmlscriptc',
  1065. 'wk' => 'application/x-123',
  1066. '7z' => 'application/x-7z-compressed',
  1067. 'abw' => 'application/x-abiword',
  1068. 'dmg' => 'application/x-apple-diskimage',
  1069. 'bcpio' => 'application/x-bcpio',
  1070. 'torrent' => 'application/x-bittorrent',
  1071. 'cab' => 'application/x-cab',
  1072. 'cbr' => 'application/x-cbr',
  1073. 'cbz' => 'application/x-cbz',
  1074. 'cdf' => 'application/x-cdf',
  1075. 'vcd' => 'application/x-cdlink',
  1076. 'pgn' => 'application/x-chess-pgn',
  1077. 'cpio' => 'application/x-cpio',
  1078. 'csh' => 'text/x-csh',
  1079. 'deb|udeb' => 'application/x-debian-package',
  1080. 'dcr|dir|dxr' => 'application/x-director',
  1081. 'dms' => 'application/x-dms',
  1082. 'wad' => 'application/x-doom',
  1083. 'dvi' => 'application/x-dvi',
  1084. 'rhtml' => 'application/x-httpd-eruby',
  1085. 'flac' => 'application/x-flac',
  1086. 'pfa|pfb|gsf|pcf|pcf.Z' => 'application/x-font',
  1087. 'mm' => 'application/x-freemind',
  1088. 'gnumeric' => 'application/x-gnumeric',
  1089. 'sgf' => 'application/x-go-sgf',
  1090. 'gcf' => 'application/x-graphing-calculator',
  1091. 'gtar|tgz|taz' => 'application/x-gtar',
  1092. 'hdf' => 'application/x-hdf',
  1093. 'phtml|pht|php' => 'application/x-httpd-php',
  1094. 'phps' => 'application/x-httpd-php-source',
  1095. 'php3' => 'application/x-httpd-php3',
  1096. 'php3p' => 'application/x-httpd-php3-preprocessed',
  1097. 'php4' => 'application/x-httpd-php4',
  1098. 'ica' => 'application/x-ica',
  1099. 'ins|isp' => 'application/x-internet-signup',
  1100. 'iii' => 'application/x-iphone',
  1101. 'iso' => 'application/x-iso9660-image',
  1102. 'jnlp' => 'application/x-java-jnlp-file',
  1103. 'js' => 'application/x-javascript',
  1104. 'jmz' => 'application/x-jmol',
  1105. 'chrt' => 'application/x-kchart',
  1106. 'kil' => 'application/x-killustrator',
  1107. 'skp|skd|skt|skm' => 'application/x-koan',
  1108. 'kpr|kpt' => 'application/x-kpresenter',
  1109. 'ksp' => 'application/x-kspread',
  1110. 'kwd|kwt' => 'application/x-kword',
  1111. 'latex' => 'application/x-latex',
  1112. 'lha' => 'application/x-lha',
  1113. 'lyx' => 'application/x-lyx',
  1114. 'lzh' => 'application/x-lzh',
  1115. 'lzx' => 'application/x-lzx',
  1116. 'frm|maker|frame|fm|fb|book|fbdoc' => 'application/x-maker',
  1117. 'mif' => 'application/x-mif',
  1118. 'wmd' => 'application/x-ms-wmd',
  1119. 'wmz' => 'application/x-ms-wmz',
  1120. 'com|exe|bat|dll' => 'application/x-msdos-program',
  1121. 'msi' => 'application/x-msi',
  1122. 'nc' => 'application/x-netcdf',
  1123. 'pac' => 'application/x-ns-proxy-autoconfig',
  1124. 'nwc' => 'application/x-nwc',
  1125. 'o' => 'application/x-object',
  1126. 'oza' => 'application/x-oz-application',
  1127. 'p7r' => 'application/x-pkcs7-certreqresp',
  1128. 'crl' => 'application/x-pkcs7-crl',
  1129. 'pyc|pyo' => 'application/x-python-code',
  1130. 'qtl' => 'application/x-quicktimeplayer',
  1131. 'rpm' => 'application/x-redhat-package-manager',
  1132. 'sh' => 'text/x-sh',
  1133. 'shar' => 'application/x-shar',
  1134. 'swf|swfl' => 'application/x-shockwave-flash',
  1135. 'sit|sitx' => 'application/x-stuffit',
  1136. 'sv4cpio' => 'application/x-sv4cpio',
  1137. 'sv4crc' => 'application/x-sv4crc',
  1138. 'tar' => 'application/x-tar',
  1139. 'tcl' => 'application/x-tcl',
  1140. 'gf' => 'application/x-tex-gf',
  1141. 'pk' => 'application/x-tex-pk',
  1142. 'texinfo|texi' => 'application/x-texinfo',
  1143. '~|%|bak|old|sik' => 'application/x-trash',
  1144. 't|tr|roff' => 'application/x-troff',
  1145. 'man' => 'application/x-troff-man',
  1146. 'me' => 'application/x-troff-me',
  1147. 'ms' => 'application/x-troff-ms',
  1148. 'ustar' => 'application/x-ustar',
  1149. 'src' => 'application/x-wais-source',
  1150. 'wz' => 'application/x-wingz',
  1151. 'crt' => 'application/x-x509-ca-cert',
  1152. 'xcf' => 'application/x-xcf',
  1153. 'fig' => 'application/x-xfig',
  1154. 'xpi' => 'application/x-xpinstall',
  1155. 'au|snd' => 'audio/basic',
  1156. 'mid|midi|kar' => 'audio/midi',
  1157. 'mpga|mpega|mp2|mp3|m4a' => 'audio/mpeg',
  1158. 'f4a|f4b' => 'audio/mp4',
  1159. 'm3u' => 'audio/x-mpegurl',
  1160. 'oga|spx' => 'audio/ogg',
  1161. 'sid' => 'audio/prs.sid',
  1162. 'aif|aiff|aifc' => 'audio/x-aiff',
  1163. 'gsm' => 'audio/x-gsm',
  1164. 'wma' => 'audio/x-ms-wma',
  1165. 'wax' => 'audio/x-ms-wax',
  1166. 'ra|rm|ram' => 'audio/x-pn-realaudio',
  1167. 'ra' => 'audio/x-realaudio',
  1168. 'pls' => 'audio/x-scpls',
  1169. 'sd2' => 'audio/x-sd2',
  1170. 'wav' => 'audio/x-wav',
  1171. 'alc' => 'chemical/x-alchemy',
  1172. 'cac|cache' => 'chemical/x-cache',
  1173. 'csf' => 'chemical/x-cache-csf',
  1174. 'cbin|cascii|ctab' => 'chemical/x-cactvs-binary',
  1175. 'cdx' => 'chemical/x-cdx',
  1176. 'cer' => 'chemical/x-cerius',
  1177. 'c3d' => 'chemical/x-chem3d',
  1178. 'chm' => 'chemical/x-chemdraw',
  1179. 'cif' => 'chemical/x-cif',
  1180. 'cmdf' => 'chemical/x-cmdf',
  1181. 'cml' => 'chemical/x-cml',
  1182. 'cpa' => 'chemical/x-compass',
  1183. 'bsd' => 'chemical/x-crossfire',
  1184. 'csml|csm' => 'chemical/x-csml',
  1185. 'ctx' => 'chemical/x-ctx',
  1186. 'cxf|cef' => 'chemical/x-cxf',
  1187. 'emb|embl' => 'chemical/x-embl-dl-nucleotide',
  1188. 'spc' => 'chemical/x-galactic-spc',
  1189. 'inp|gam|gamin' => 'chemical/x-gamess-input',
  1190. 'fch|fchk' => 'chemical/x-gaussian-checkpoint',
  1191. 'cub' => 'chemical/x-gaussian-cube',
  1192. 'gau|gjc|gjf' => 'chemical/x-gaussian-input',
  1193. 'gal' => 'chemical/x-gaussian-log',
  1194. 'gcg' => 'chemical/x-gcg8-sequence',
  1195. 'gen' => 'chemical/x-genbank',
  1196. 'hin' => 'chemical/x-hin',
  1197. 'istr|ist' => 'chemical/x-isostar',
  1198. 'jdx|dx' => 'chemical/x-jcamp-dx',
  1199. 'kin' => 'chemical/x-kinemage',
  1200. 'mcm' => 'chemical/x-macmolecule',
  1201. 'mmd|mmod' => 'chemical/x-macromodel-input',
  1202. 'mol' => 'chemical/x-mdl-molfile',
  1203. 'rd' => 'chemical/x-mdl-rdfile',
  1204. 'rxn' => 'chemical/x-mdl-rxnfile',
  1205. 'sd|sdf' => 'chemical/x-mdl-sdfile',
  1206. 'tgf' => 'chemical/x-mdl-tgf',
  1207. 'mcif' => 'chemical/x-mmcif',
  1208. 'mol2' => 'chemical/x-mol2',
  1209. 'b' => 'chemical/x-molconn-Z',
  1210. 'gpt' => 'chemical/x-mopac-graph',
  1211. 'mop|mopcrt|mpc|dat|zmt' => 'chemical/x-mopac-input',
  1212. 'moo' => 'chemical/x-mopac-out',
  1213. 'mvb' => 'chemical/x-mopac-vib',
  1214. 'asn' => 'chemical/x-ncbi-asn1-spec',
  1215. 'prt|ent' => 'chemical/x-ncbi-asn1-ascii',
  1216. 'val|aso' => 'chemical/x-ncbi-asn1-binary',
  1217. 'pdb|ent' => 'chemical/x-pdb',
  1218. 'ros' => 'chemical/x-rosdal',
  1219. 'sw' => 'chemical/x-swissprot',
  1220. 'vms' => 'chemical/x-vamas-iso14976',
  1221. 'vmd' => 'chemical/x-vmd',
  1222. 'xtel' => 'chemical/x-xtel',
  1223. 'xyz' => 'chemical/x-xyz',
  1224. 'gif' => 'image/gif',
  1225. 'ief' => 'image/ief',
  1226. 'jpeg|jpg|jpe' => 'image/jpeg',
  1227. 'pcx' => 'image/pcx',
  1228. 'png' => 'image/png',
  1229. 'svg|svgz' => 'image/svg+xml',
  1230. 'tiff|tif' => 'image/tiff',
  1231. 'djvu|djv' => 'image/vnd.djvu',
  1232. 'wbmp' => 'image/vnd.wap.wbmp',
  1233. 'ras' => 'image/x-cmu-raster',
  1234. 'cdr' => 'image/x-coreldraw',
  1235. 'pat' => 'image/x-coreldrawpattern',
  1236. 'cdt' => 'image/x-coreldrawtemplate',
  1237. 'ico' => 'image/x-icon',
  1238. 'art' => 'image/x-jg',
  1239. 'jng' => 'image/x-jng',
  1240. 'bmp' => 'image/x-ms-bmp',
  1241. 'psd' => 'image/x-photoshop',
  1242. 'pnm' => 'image/x-portable-anymap',
  1243. 'pbm' => 'image/x-portable-bitmap',
  1244. 'pgm' => 'image/x-portable-graymap',
  1245. 'ppm' => 'image/x-portable-pixmap',
  1246. 'rgb' => 'image/x-rgb',
  1247. 'xbm' => 'image/x-xbitmap',
  1248. 'xpm' => 'image/x-xpixmap',
  1249. 'xwd' => 'image/x-xwindowdump',
  1250. 'eml' => 'message/rfc822',
  1251. 'igs|iges' => 'model/iges',
  1252. 'msh|mesh|silo' => 'model/mesh',
  1253. 'wrl|vrml' => 'model/vrml',
  1254. 'ics|icz' => 'text/calendar',
  1255. 'css' => 'text/css',
  1256. 'csv' => 'text/csv',
  1257. '323' => 'text/h323',
  1258. 'html|htm|shtml' => 'text/html',
  1259. 'uls' => 'text/iuls',
  1260. 'mml' => 'text/mathml',
  1261. 'asc|txt|text|pot' => 'text/plain',
  1262. 'rtx' => 'text/richtext',
  1263. 'sct|wsc' => 'text/scriptlet',
  1264. 'tm|ts' => 'text/texmacs',
  1265. 'tsv' => 'text/tab-separated-values',
  1266. 'jad' => 'text/vnd.sun.j2me.app-descriptor',
  1267. 'wml' => 'text/vnd.wap.wml',
  1268. 'wmls' => 'text/vnd.wap.wmlscript',
  1269. 'bib' => 'text/x-bibtex',
  1270. 'boo' => 'text/x-boo',
  1271. 'h++|hpp|hxx|hh' => 'text/x-c++hdr',
  1272. 'c++|cpp|cxx|cc' => 'text/x-c++src',
  1273. 'h' => 'text/x-chdr',
  1274. 'htc' => 'text/x-component',
  1275. 'c' => 'text/x-csrc',
  1276. 'd' => 'text/x-dsrc',
  1277. 'diff|patch' => 'text/x-diff',
  1278. 'hs' => 'text/x-haskell',
  1279. 'java' => 'text/x-java',
  1280. 'lhs' => 'text/x-literate-haskell',
  1281. 'moc' => 'text/x-moc',
  1282. 'p|pas' => 'text/x-pascal',
  1283. 'gcd' => 'text/x-pcs-gcd',
  1284. 'pl|pm' => 'text/x-perl',
  1285. 'py' => 'text/x-python',
  1286. 'etx' => 'text/x-setext',
  1287. 'tcl|tk' => 'text/x-tcl',
  1288. 'tex|ltx|sty|cls' => 'text/x-tex',
  1289. 'vcs' => 'text/x-vcalendar',
  1290. 'vcf' => 'text/x-vcard',
  1291. '3gp' => 'video/3gpp',
  1292. 'dl' => 'video/dl',
  1293. 'dif|dv' => 'video/dv',
  1294. 'fli' => 'video/fli',
  1295. 'gl' => 'video/gl',
  1296. 'mpeg|mpg|mpe' => 'video/mpeg',
  1297. 'mp4|f4v|f4p' => 'video/mp4',
  1298. 'flv' => 'video/x-flv',
  1299. 'ogv' => 'video/ogg',
  1300. 'qt|mov' => 'video/quicktime',
  1301. 'mxu' => 'video/vnd.mpegurl',
  1302. 'lsf|lsx' => 'video/x-la-asf',
  1303. 'mng' => 'video/x-mng',
  1304. 'asf|asx' => 'video/x-ms-asf',
  1305. 'wm' => 'video/x-ms-wm',
  1306. 'wmv' => 'video/x-ms-wmv',
  1307. 'wmx' => 'video/x-ms-wmx',
  1308. 'wvx' => 'video/x-ms-wvx',
  1309. 'avi' => 'video/x-msvideo',
  1310. 'movie' => 'video/x-sgi-movie',
  1311. 'ice' => 'x-conference/x-cooltalk',
  1312. 'sisx' => 'x-epoc/x-sisx-app',
  1313. 'vrm|vrml|wrl' => 'x-world/x-vrml',
  1314. 'xps' => 'application/vnd.ms-xpsdocument',
  1315. ));
  1316. }
  1317. foreach ($mapping as $ext_preg => $mime_match) {
  1318. if (preg_match('!\.('. $ext_preg .')$!i', $filename)) {
  1319. return $mime_match;
  1320. }
  1321. }
  1322. return 'application/octet-stream';
  1323. }
  1324. /**
  1325. * @} End of "defgroup file".
  1326. */

Comments

What is the point from passing by reference ??

Many functions in this file uses pass by reference for (from my point of view) no particular reasons, the question is why?

- to save the caller a few lines of code ??, not a pro. style.
- to ease the development ??, it does not.

see the file_copy(&$source); function, apparently, the passed source object (or string) &$source is blown up completely in that function, you prepare a $file object, pass it to file_copy() and you will never see it again, unless you have previously saved it.

Professionally, there is no point from passing by reference here, I know all objects are passed by ref by default, but here (in file_copy(&$source);), destructing the passed object is intended for no particular reason.

- it does not save memory.
- nor it makes the code smarter.

Also, file.inc, does not define or create any hooks for files operations (maybe there is just one), the most hook_lack functionality in Drupal.

Function names also are not descriptive, you see names like:

file_check_path(); // its name is not even related to its task.
file_check_directory(); // the same, it also modify, create, chmod, and set form & status messages!,, looks like the awaiting function all developers dreamed of.

Writing a new functions instead of those in file.inc however never help, since I need to modify all contributed modules code to adapt.

You've missed the point.

Variables are passed by reference because they are modified by the called function, and that modification needs to be passed back to the caller.

For example, $dir = "hello/"; file_check_directory($dir); echo $dir; will result in "sites/default/hello".

I don't disagree that some of the API is a little convoluted, the function naming especially, but you seem to have a fundamental misunderstanding of why references are used in this API.

The object is not

The object is not "destructed" as I see it. Where are you finding that the function is unsetting the object that it is passed?

It's very useful that I can assign a new file upload to $file, and then do stuff like "file_set_status(&$file)" and have my $file object automatically have the status updated.

BTW objects are only passed as references by default in PHP5, in PHP4 you must use the ampersand thusly: my_function(&$my_var)

Login or register to post comments