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_directoryCheck that the directory exists and is writable. Directories need to have execute permissions to be considered a directory by FTP servers, etc.
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_check_upload
file_copyCopies a file to a new location. This is a powerful function that in many ways performs like an advanced version of copy().
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_directory_pathDetermine the default 'files' directory.
file_directory_tempDetermine the default temporary directory.
file_download
file_moveMoves a file to a new location.
file_save_dataSave a string to the specified destination.
file_save_uploadSaves a file upload to a new location. The source file is validated as a proper upload and handled as such.
file_scan_directoryFinds all files that match a given mask in a given directory. Directories and files beginning with a period are excluded.
file_transferTransfer file using http to client. Pipes a file through Drupal to the client.
file_upload_max_sizeDetermine the maximum file upload size by querying the PHP settings.
_file_convert_to_mbHelper function for file_upload_max_size().

Constants

NameDescription
FILE_CREATE_DIRECTORY
FILE_DOWNLOADS_PRIVATE
FILE_DOWNLOADS_PUBLIC
FILE_EXISTS_ERROR
FILE_EXISTS_RENAME
FILE_EXISTS_REPLACE
FILE_MODIFY_PERMISSIONS

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. * Create the download path to a file.
  20. *
  21. * @param $path A string containing the path of the file to generate URL for.
  22. * @return A string containing a URL that can be used to download the file.
  23. */
  24. function file_create_url($path) {
  25. // Strip file_directory_path from $path. We only include relative paths in urls.
  26. if (strpos($path, file_directory_path() . '/') === 0) {
  27. $path = trim(substr($path, strlen(file_directory_path())), '\\/');
  28. }
  29. switch (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC)) {
  30. case FILE_DOWNLOADS_PUBLIC:
  31. return $GLOBALS['base_url'] .'/'. file_directory_path() .'/'. str_replace('\\', '/', $path);
  32. case FILE_DOWNLOADS_PRIVATE:
  33. return url('system/files/'. $path, NULL, NULL, TRUE);
  34. }
  35. }
  36. /**
  37. * Make sure the destination is a complete path and resides in the file system
  38. * directory, if it is not prepend the file system directory.
  39. *
  40. * @param $dest A string containing the path to verify. If this value is
  41. * omitted, Drupal's 'files' directory will be used.
  42. * @return A string containing the path to file, with file system directory
  43. * appended if necessary, or FALSE if the path is invalid (i.e. outside the
  44. * configured 'files' or temp directories).
  45. */
  46. function file_create_path($dest = 0) {
  47. $file_path = file_directory_path();
  48. if (!$dest) {
  49. return $file_path;
  50. }
  51. // file_check_location() checks whether the destination is inside the Drupal files directory.
  52. if (file_check_location($dest, $file_path)) {
  53. return $dest;
  54. }
  55. // check if the destination is instead inside the Drupal temporary files directory.
  56. else if (file_check_location($dest, file_directory_temp())) {
  57. return $dest;
  58. }
  59. // Not found, try again with prefixed directory path.
  60. else if (file_check_location($file_path . '/' . $dest, $file_path)) {
  61. return $file_path . '/' . $dest;
  62. }
  63. // File not found.
  64. return FALSE;
  65. }
  66. /**
  67. * Check that the directory exists and is writable. Directories need to
  68. * have execute permissions to be considered a directory by FTP servers, etc.
  69. *
  70. * @param $directory A string containing the name of a directory path.
  71. * @param $mode A Boolean value to indicate if the directory should be created
  72. * if it does not exist or made writable if it is read-only.
  73. * @param $form_item An optional string containing the name of a form item that
  74. * any errors will be attached to. This is useful for settings forms that
  75. * require the user to specify a writable directory. If it can't be made to
  76. * work, a form error will be set preventing them from saving the settings.
  77. * @return False when directory not found, or true when directory exists.
  78. */
  79. function file_check_directory(&$directory, $mode = 0, $form_item = NULL) {
  80. $directory = rtrim($directory, '/\\');
  81. // Check if directory exists.
  82. if (!is_dir($directory)) {
  83. if (($mode & FILE_CREATE_DIRECTORY) && @mkdir($directory)) {
  84. drupal_set_message(t('The directory %directory has been created.', array('%directory' => theme('placeholder', $directory))));
  85. @chmod($directory, 0775); // Necessary for non-webserver users.
  86. }
  87. else {
  88. if ($form_item) {
  89. form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => theme('placeholder', $directory))));
  90. }
  91. return false;
  92. }
  93. }
  94. // Check to see if the directory is writable.
  95. if (!is_writable($directory)) {
  96. if (($mode & FILE_MODIFY_PERMISSIONS) && @chmod($directory, 0775)) {
  97. drupal_set_message(t('The permissions of directory %directory have been changed to make it writable.', array('%directory' => theme('placeholder', $directory))));
  98. }
  99. else {
  100. form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => theme('placeholder', $directory))));
  101. watchdog('file system', t('The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => theme('placeholder', $directory))), WATCHDOG_ERROR);
  102. return false;
  103. }
  104. }
  105. if ((file_directory_path() == $directory || file_directory_temp() == $directory) && !is_file("$directory/.htaccess")) {
  106. $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
  107. if (($fp = fopen("$directory/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
  108. fclose($fp);
  109. chmod($directory .'/.htaccess', 0664);
  110. }
  111. else {
  112. $message = 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>", array('%directory' => theme('placeholder', $directory), '%htaccess' => '<br />'. str_replace("\n", '<br />', check_plain($htaccess_lines))));
  113. form_set_error($form_item, $message);
  114. watchdog('security', $message, WATCHDOG_ERROR);
  115. }
  116. }
  117. return true;
  118. }
  119. /**
  120. * Checks path to see if it is a directory, or a dir/file.
  121. *
  122. * @param $path A string containing a file path. This will be set to the
  123. * directory's path.
  124. * @return If the directory is not in a Drupal writable directory, FALSE is
  125. * returned. Otherwise, the base name of the path is returned.
  126. */
  127. function file_check_path(&$path) {
  128. // Check if path is a directory.
  129. if (file_check_directory($path)) {
  130. return '';
  131. }
  132. // Check if path is a possible dir/file.
  133. $filename = basename($path);
  134. $path = dirname($path);
  135. if (file_check_directory($path)) {
  136. return $filename;
  137. }
  138. return false;
  139. }
  140. /**
  141. * Check if $source is a valid file upload. If so, move the file to Drupal's tmp dir
  142. * and return it as an object.
  143. *
  144. * The use of SESSION['file_uploads'] should probably be externalized to upload.module
  145. *
  146. * @todo Rename file_check_upload to file_prepare upload.
  147. * @todo Refactor or merge file_save_upload.
  148. * @todo Extenalize SESSION['file_uploads'] to modules.
  149. *
  150. * @param $source An upload source (the name of the upload form item), or a file
  151. * @return false for an invalid file or upload. A file object for valid uploads/files.
  152. *
  153. */
  154. function file_check_upload($source = 'upload') {
  155. // Cache for uploaded files. Since the data in _FILES is modified
  156. // by this function, we cache the result.
  157. static $upload_cache;
  158. // Test source to see if it is an object.
  159. if (is_object($source)) {
  160. // Validate the file path if an object was passed in instead of
  161. // an upload key.
  162. if (is_file($source->filepath)) {
  163. return $source;
  164. }
  165. else {
  166. return false;
  167. }
  168. }
  169. // Return cached objects without processing since the file will have
  170. // already been processed and the paths in _FILES will be invalid.
  171. if (isset($upload_cache[$source])) {
  172. return $upload_cache[$source];
  173. }
  174. // If a file was uploaded, process it.
  175. if ($_FILES["edit"]["name"][$source] && is_uploaded_file($_FILES["edit"]["tmp_name"][$source])) {
  176. // Check for file upload errors and return false if a
  177. // lower level system error occurred.
  178. switch ($_FILES["edit"]["error"][$source]) {
  179. // @see http://php.net/manual/en/features.file-upload.errors.php
  180. case UPLOAD_ERR_OK:
  181. break;
  182. case UPLOAD_ERR_INI_SIZE:
  183. case UPLOAD_ERR_FORM_SIZE:
  184. drupal_set_message(t('The file %file could not be saved, because it exceeds the maximum allowed size for uploads.', array('%file' => theme('placeholder', $source))), 'error');
  185. return 0;
  186. case UPLOAD_ERR_PARTIAL:
  187. case UPLOAD_ERR_NO_FILE:
  188. drupal_set_message(t('The file %file could not be saved, because the upload did not complete.', array('%file' => theme('placeholder', $source))), 'error');
  189. return 0;
  190. // Unknown error
  191. default:
  192. drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', array('%file' => theme('placeholder', $source))),'error');
  193. return 0;
  194. }
  195. // Begin building file object.
  196. $file = new StdClass();
  197. $file->filename = trim(basename($_FILES["edit"]["name"][$source]), '.');
  198. // Create temporary name/path for newly uploaded files.
  199. $file->filepath = tempnam(file_directory_temp(), 'tmp_');
  200. $file->filemime = $_FILES["edit"]["type"][$source];
  201. // Rename potentially executable files, to help prevent exploits.
  202. if (((substr($file->filemime, 0, 5) == 'text/' || strpos($file->filemime, 'javascript')) && (substr($file->filename, -4) != '.txt')) || preg_match('/\.(php|pl|py|cgi|asp)$/i', $file->filename)) {
  203. $file->filemime = 'text/plain';
  204. $file->filepath .= '.txt';
  205. $file->filename .= '.txt';
  206. }
  207. // Move uploaded files from php's upload_tmp_dir to Drupal's file temp.
  208. // This overcomes open_basedir restrictions for future file operations.
  209. if (!move_uploaded_file($_FILES["edit"]["tmp_name"][$source], $file->filepath)) {
  210. drupal_set_message(t('File upload error. Could not move uploaded file.'));
  211. watchdog('file', t('Upload Error. Could not move uploaded file(%file) to destination(%destination).', array('%file' => theme('placeholder', $_FILES["edit"]["tmp_name"][$source]), '%destination' => theme('placeholder', $file->filepath))));
  212. return false;
  213. }
  214. $file->filesize = $_FILES["edit"]["size"][$source];
  215. $file->source = $source;
  216. // Add processed file to the cache.
  217. $upload_cache[$source] = $file;
  218. return $file;
  219. }
  220. else {
  221. // In case of previews return previous file object.
  222. if (file_exists($_SESSION['file_uploads'][$source]->filepath)) {
  223. return $_SESSION['file_uploads'][$source];
  224. }
  225. }
  226. // If nothing was done, return false.
  227. return false;
  228. }
  229. /**
  230. * Check if a file is really located inside $directory. Should be used to make
  231. * sure a file specified is really located within the directory to prevent
  232. * exploits.
  233. *
  234. * @code
  235. * // Returns false:
  236. * file_check_location('/www/example.com/files/../../../etc/passwd', '/www/example.com/files');
  237. * @endcode
  238. *
  239. * @param $source A string set to the file to check.
  240. * @param $directory A string where the file should be located.
  241. * @return 0 for invalid path or the real path of the source.
  242. */
  243. function file_check_location($source, $directory = '') {
  244. $check = realpath($source);
  245. if ($check) {
  246. $source = $check;
  247. }
  248. else {
  249. // This file does not yet exist
  250. $source = realpath(dirname($source)) .'/'. basename($source);
  251. }
  252. $directory = realpath($directory);
  253. if ($directory && strpos($source, $directory) !== 0) {
  254. return 0;
  255. }
  256. return $source;
  257. }
  258. /**
  259. * Copies a file to a new location. This is a powerful function that in many ways
  260. * performs like an advanced version of copy().
  261. * - Checks if $source and $dest are valid and readable/writable.
  262. * - Performs a file copy if $source is not equal to $dest.
  263. * - If file already exists in $dest either the call will error out, replace the
  264. * file or rename the file based on the $replace parameter.
  265. *
  266. * @param $source A string specifying the file location of the original file.
  267. * This parameter will contain the resulting destination filename in case of
  268. * success.
  269. * @param $dest A string containing the directory $source should be copied to.
  270. * If this value is omitted, Drupal's 'files' directory will be used.
  271. * @param $replace Replace behavior when the destination file already exists.
  272. * - FILE_EXISTS_REPLACE - Replace the existing file
  273. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is unique
  274. * - FILE_EXISTS_ERROR - Do nothing and return false.
  275. * @return True for success, false for failure.
  276. */
  277. function file_copy(&$source, $dest = 0, $replace = FILE_EXISTS_RENAME) {
  278. $dest = file_create_path($dest);
  279. $directory = $dest;
  280. $basename = file_check_path($directory);
  281. // Make sure we at least have a valid directory.
  282. if ($basename === false) {
  283. $source = is_object($source) ? $source->filepath : $source;
  284. drupal_set_message(t('The selected file %file could not be uploaded, because the destination %directory is not properly configured.', array('%file' => theme('placeholder', $source), '%directory' => theme('placeholder', $dest))), 'error');
  285. watchdog('file system', t('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' => theme('placeholder', $source), '%directory' => theme('placeholder', $dest))), WATCHDOG_ERROR);
  286. return 0;
  287. }
  288. // Process a file upload object.
  289. if (is_object($source)) {
  290. $file = $source;
  291. $source = $file->filepath;
  292. if (!$basename) {
  293. $basename = $file->filename;
  294. }
  295. }
  296. $source = realpath($source);
  297. if (!file_exists($source)) {
  298. 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' => theme('placeholder', $source))), 'error');
  299. return 0;
  300. }
  301. // If the destination file is not specified then use the filename of the source file.
  302. $basename = $basename ? $basename : basename($source);
  303. $dest = $directory .'/'. $basename;
  304. // Make sure source and destination filenames are not the same, makes no sense
  305. // to copy it if they are. In fact copying the file will most likely result in
  306. // a 0 byte file. Which is bad. Real bad.
  307. if ($source != realpath($dest)) {
  308. if (file_exists($dest)) {
  309. switch ($replace) {
  310. case FILE_EXISTS_RENAME:
  311. // Destination file already exists and we can't replace is so we try and
  312. // and find a new filename.
  313. if ($pos = strrpos($basename, '.')) {
  314. $name = substr($basename, 0, $pos);
  315. $ext = substr($basename, $pos);
  316. }
  317. else {
  318. $name = $basename;
  319. }
  320. $counter = 0;
  321. do {
  322. $dest = $directory .'/'. $name .'_'. $counter++ . $ext;
  323. } while (file_exists($dest));
  324. break;
  325. case FILE_EXISTS_ERROR:
  326. 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' => theme('placeholder', $source))), 'error');
  327. return 0;
  328. }
  329. }
  330. if (!@copy($source, $dest)) {
  331. drupal_set_message(t('The selected file %file could not be copied.', array('%file' => theme('placeholder', $source))), 'error');
  332. return 0;
  333. }
  334. // Give everyone read access so that FTP'd users or
  335. // non-webserver users can see/read these files.
  336. @chmod($dest, 0664);
  337. }
  338. if (is_object($file)) {
  339. $file->filename = $basename;
  340. $file->filepath = $dest;
  341. $source = $file;
  342. }
  343. else {
  344. $source = $dest;
  345. }
  346. return 1; // Everything went ok.
  347. }
  348. /**
  349. * Moves a file to a new location.
  350. * - Checks if $source and $dest are valid and readable/writable.
  351. * - Performs a file move if $source is not equal to $dest.
  352. * - If file already exists in $dest either the call will error out, replace the
  353. * file or rename the file based on the $replace parameter.
  354. *
  355. * @param $source A string specifying the file location of the original file.
  356. * This parameter will contain the resulting destination filename in case of
  357. * success.
  358. * @param $dest A string containing the directory $source should be copied to.
  359. * If this value is omitted, Drupal's 'files' directory will be used.
  360. * @param $replace Replace behavior when the destination file already exists.
  361. * - FILE_EXISTS_REPLACE - Replace the existing file
  362. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is unique
  363. * - FILE_EXISTS_ERROR - Do nothing and return false.
  364. * @return True for success, false for failure.
  365. */
  366. function file_move(&$source, $dest = 0, $replace = FILE_EXISTS_RENAME) {
  367. $path_original = is_object($source) ? $source->filepath : $source;
  368. if (file_copy($source, $dest, $replace)) {
  369. $path_current = is_object($source) ? $source->filepath : $source;
  370. if ($path_original == $path_current || file_delete($path_original)) {
  371. return 1;
  372. }
  373. drupal_set_message(t('The removal of the original file %file has failed.', array('%file' => theme('placeholder', $path_original))), 'error');
  374. }
  375. return 0;
  376. }
  377. /**
  378. * Create a full file path from a directory and filename. If a file with the
  379. * specified name already exists, an alternative will be used.
  380. *
  381. * @param $basename string filename
  382. * @param $directory string directory
  383. * @return
  384. */
  385. function file_create_filename($basename, $directory) {
  386. $dest = $directory .'/'. $basename;
  387. if (file_exists($dest)) {
  388. // Destination file already exists, generate an alternative.
  389. if ($pos = strrpos($basename, '.')) {
  390. $name = substr($basename, 0, $pos);
  391. $ext = substr($basename, $pos);
  392. }
  393. else {
  394. $name = $basename;
  395. }
  396. $counter = 0;
  397. do {
  398. $dest = $directory .'/'. $name .'_'. $counter++ . $ext;
  399. } while (file_exists($dest));
  400. }
  401. return $dest;
  402. }
  403. /**
  404. * Delete a file.
  405. *
  406. * @param $path A string containing a file path.
  407. * @return True for success, false for failure.
  408. */
  409. function file_delete($path) {
  410. if (is_file($path)) {
  411. return unlink($path);
  412. }
  413. }
  414. /**
  415. * Saves a file upload to a new location. The source file is validated as a
  416. * proper upload and handled as such.
  417. *
  418. * @param $source A string specifying the name of the upload field to save.
  419. * This parameter will contain the resulting destination filename in case of
  420. * success.
  421. * @param $dest A string containing the directory $source should be copied to,
  422. * will use the temporary directory in case no other value is set.
  423. * @param $replace A boolean, set to true if the destination should be replaced
  424. * when in use, but when false append a _X to the filename.
  425. * @return An object containing file info or 0 in case of error.
  426. */
  427. function file_save_upload($source, $dest = false, $replace = FILE_EXISTS_RENAME) {
  428. // Make sure $source exists && is valid.
  429. if ($file = file_check_upload($source)) {
  430. // This should be refactored, file_check_upload has already
  431. // moved the file to the temporary folder.
  432. if (!$dest) {
  433. $dest = file_directory_temp();
  434. $temporary = 1;
  435. if (is_file($file->filepath)) {
  436. // If this file was uploaded by this user before replace the temporary copy.
  437. $replace = FILE_EXISTS_REPLACE;
  438. }
  439. }
  440. unset($_SESSION['file_uploads'][is_object($source) ? $source->source : $source]);
  441. if (file_move($file, $dest, $replace)) {
  442. if ($temporary) {
  443. $_SESSION['file_uploads'][is_object($source) ? $source->source : $source] = $file;
  444. }
  445. return $file;
  446. }
  447. return 0;
  448. }
  449. return 0;
  450. }
  451. /**
  452. * Save a string to the specified destination.
  453. *
  454. * @param $data A string containing the contents of the file.
  455. * @param $dest A string containing the destination location.
  456. * @param $replace Replace behavior when the destination file already exists.
  457. * - FILE_EXISTS_REPLACE - Replace the existing file
  458. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is unique
  459. * - FILE_EXISTS_ERROR - Do nothing and return false.
  460. *
  461. * @return A string containing the resulting filename or 0 on error
  462. */
  463. function file_save_data($data, $dest, $replace = FILE_EXISTS_RENAME) {
  464. $temp = file_directory_temp();
  465. $file = tempnam($temp, 'file');
  466. if (!$fp = fopen($file, 'wb')) {
  467. drupal_set_message(t('The file could not be created.'), 'error');
  468. return 0;
  469. }
  470. fwrite($fp, $data);
  471. fclose($fp);
  472. if (!file_move($file, $dest, $replace)) {
  473. return 0;
  474. }
  475. return $file;
  476. }
  477. /**
  478. * Transfer file using http to client. Pipes a file through Drupal to the
  479. * client.
  480. *
  481. * @param $source File to transfer.
  482. * @param $headers An array of http headers to send along with file.
  483. */
  484. function file_transfer($source, $headers) {
  485. ob_end_clean();
  486. foreach ($headers as $header) {
  487. // To prevent HTTP header injection, we delete new lines that are
  488. // not followed by a space or a tab.
  489. // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
  490. $header = preg_replace('/\r?\n(?!\t| )/', '', $header);
  491. header($header);
  492. }
  493. $source = file_create_path($source);
  494. // Transfer file in 1024 byte chunks to save memory usage.
  495. if ($fd = fopen($source, 'rb')) {
  496. while (!feof($fd)) {
  497. print fread($fd, 1024);
  498. }
  499. fclose($fd);
  500. }
  501. else {
  502. drupal_not_found();
  503. }
  504. exit();
  505. }
  506. /**
  507. * Call modules that implement hook_file_download() to find out if a file is
  508. * accessible and what headers it should be transferred with. If a module
  509. * returns -1 drupal_access_denied() will be returned. If one or more modules
  510. * returned headers the download will start with the returned headers. If no
  511. * modules respond drupal_not_found() will be returned.
  512. */
  513. function file_download() {
  514. // Merge remainder of arguments from GET['q'], into relative file path.
  515. $args = func_get_args();
  516. $filepath = implode('/', $args);
  517. // Maintain compatibility with old ?file=paths saved in node bodies.
  518. if (isset($_GET['file'])) {
  519. $filepath = $_GET['file'];
  520. }
  521. if (file_exists(file_create_path($filepath))) {
  522. $headers = module_invoke_all('file_download', $filepath);
  523. if (in_array(-1, $headers)) {
  524. return drupal_access_denied();
  525. }
  526. if (count($headers)) {
  527. file_transfer($filepath, $headers);
  528. }
  529. }
  530. return drupal_not_found();
  531. }
  532. /**
  533. * Finds all files that match a given mask in a given
  534. * directory. Directories and files beginning with a period are excluded.
  535. *
  536. * @param $dir
  537. * The base directory for the scan.
  538. * @param $mask
  539. * The regular expression of the files to find.
  540. * @param $nomask
  541. * An array of files/directories to ignore.
  542. * @param $callback
  543. * The callback function to call for each match.
  544. * @param $recurse
  545. * When TRUE, the directory scan will recurse the entire tree
  546. * starting at the provided directory.
  547. * @param $key
  548. * The key to be used for the returned array of files. Possible
  549. * values are "filename", for the path starting with $dir,
  550. * "basename", for the basename of the file, and "name" for the name
  551. * of the file without an extension.
  552. * @param $min_depth
  553. * Minimum depth of directories to return files from.
  554. * @param $depth
  555. * Current depth of recursion. This parameter is only used internally and should not be passed.
  556. *
  557. * @return
  558. * An associative array (keyed on the provided key) of objects with
  559. * "path", "basename", and "name" members corresponding to the
  560. * matching files.
  561. */
  562. function file_scan_directory($dir, $mask, $nomask = array('.', '..', 'CVS'), $callback = 0, $recurse = TRUE, $key = 'filename', $min_depth = 0, $depth = 0) {
  563. $key = (in_array($key, array('filename', 'basename', 'name')) ? $key : 'filename');
  564. $files = array();
  565. if (is_dir($dir) && $handle = opendir($dir)) {
  566. while ($file = readdir($handle)) {
  567. if (!in_array($file, $nomask) && $file[0] != '.') {
  568. if (is_dir("$dir/$file") && $recurse) {
  569. $files = array_merge($files, file_scan_directory("$dir/$file", $mask, $nomask, $callback, $recurse, $key, $min_depth, $depth + 1));
  570. }
  571. elseif ($depth >= $min_depth && ereg($mask, $file)) {
  572. $filename = "$dir/$file";
  573. $basename = basename($file);
  574. $name = substr($basename, 0, strrpos($basename, '.'));
  575. $files[$$key] = new stdClass();
  576. $files[$$key]->filename = $filename;
  577. $files[$$key]->basename = $basename;
  578. $files[$$key]->name = $name;
  579. if ($callback) {
  580. $callback($filename);
  581. }
  582. }
  583. }
  584. }
  585. closedir($handle);
  586. }
  587. return $files;
  588. }
  589. /**
  590. * Determine the default temporary directory.
  591. *
  592. * @return A string containing a temp directory.
  593. */
  594. function file_directory_temp() {
  595. $temporary_directory = variable_get('file_directory_temp', NULL);
  596. if (is_null($temporary_directory)) {
  597. $directories = array();
  598. // Has PHP been set with an upload_tmp_dir?
  599. if (ini_get('upload_tmp_dir')) {
  600. $directories[] = ini_get('upload_tmp_dir');
  601. }
  602. // Operating system specific dirs.
  603. if (substr(PHP_OS, 0, 3) == 'WIN') {
  604. $directories[] = 'c:\\windows\\temp';
  605. $directories[] = 'c:\\winnt\\temp';
  606. $path_delimiter = '\\';
  607. }
  608. else {
  609. $directories[] = '/tmp';
  610. $path_delimiter = '/';
  611. }
  612. foreach ($directories as $directory) {
  613. if (!$temporary_directory && is_dir($directory)) {
  614. $temporary_directory = $directory;
  615. }
  616. }
  617. // if a directory has been found, use it, otherwise default to 'files/tmp' or 'files\\tmp';
  618. $temporary_directory = $temporary_directory ? $temporary_directory : file_directory_path() . $path_delimiter . 'tmp';
  619. variable_set('file_directory_temp', $temporary_directory);
  620. }
  621. return $temporary_directory;
  622. }
  623. /**
  624. * Determine the default 'files' directory.
  625. *
  626. * @return A string containing the path to Drupal's 'files' directory.
  627. */
  628. function file_directory_path() {
  629. return variable_get('file_directory_path', 'files');
  630. }
  631. /**
  632. * Helper function for file_upload_max_size().
  633. */
  634. function _file_convert_to_mb($val){
  635. $val = trim($val);
  636. $last = strtolower($val[strlen($val) - 1]);
  637. switch($last) {
  638. // The 'G' modifier is available since PHP 5.1.0
  639. case 'g':
  640. $size = $val * 1024;
  641. break;
  642. case 'k':
  643. $size = $val / 1024;
  644. break;
  645. default:
  646. $size = (int) $val;
  647. }
  648. return $size;
  649. }
  650. /**
  651. * Determine the maximum file upload size by querying the PHP settings.
  652. *
  653. * @return
  654. * A file size limit in MB based on the PHP upload_max_filesize and post_max_size
  655. */
  656. function file_upload_max_size() {
  657. static $max_size = -1;
  658. if ($max_size < 0) {
  659. $upload_max = _file_convert_to_mb(ini_get('upload_max_filesize'));
  660. // sanity check- a single upload should not be more than 50% the size limit of the total post
  661. $post_max = _file_convert_to_mb(ini_get('post_max_size')) / 2;
  662. $max_size = ($upload_max < $post_max) ? $upload_max : $post_max;
  663. }
  664. return $max_size;
  665. }
Login or register to post comments