file.inc

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

API for handling file uploads and server file management.

Functions

Namesort descending Description
file_check_directory Checks whether a directory exists and is writable.
file_check_location Check 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_path Checks path to see if it is a directory, or a dir/file.
file_copy Copies a file to a new location.
file_create_filename Create 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_htaccess Creates a .htaccess file in the given directory.
file_create_path Make 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_url Create the download path to a file.
file_delete Delete a file.
file_destination Determines the destination path for a file depending on how replacement of existing files should be handled.
file_directory_path Determine the default 'files' directory.
file_directory_temp Determine the default temporary directory.
file_download Call 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_download_access Checks that the current user has access to a particular file.
file_download_headers Retrieves headers for a private file download.
file_get_mimetype Determine an Internet Media Type, or MIME type from a filename.
file_htaccess_lines Returns the standard .htaccess lines that Drupal writes to file directories.
file_move Moves a file to a new location.
file_munge_filename Modify a filename as needed for security purposes.
file_save_data Save a string to the specified destination.
file_save_upload Saves a file upload to a new location.
file_scan_directory Finds all files that match a given mask in a given directory.
file_set_status Set the status of a file.
file_space_used Determine total disk space used by a single user or the whole filesystem.
file_transfer Transfer file using http to client. Pipes a file through Drupal to the client.
file_unmunge_filename Undo the effect of upload_munge_filename().
file_upload_max_size Determine the maximum file upload size by querying the PHP settings.
file_validate_extensions Check that the filename ends with an allowed extension. This check is not enforced for the user #1.
file_validate_image_resolution If 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_image Check that the file is recognized by image_get_info() as an image.
file_validate_name_length Check for files with names longer than we can store in the database.
file_validate_size Check that the file's size is below certain limits. This check is not enforced for the user #1.

Constants

Namesort descending Description
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_TEMPORARY A 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

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