* Make sure the destination is a complete path and resides in the file system
* directory, if it is not prepend the file system directory.
*
* @param $dest A string containing the path to verify. If this value is
* omitted, Drupal's 'files' directory will be used.
* @return A string containing the path to file, with file system directory
* appended if necessary, or FALSE if the path is invalid (i.e. outside the
* configured 'files' or temp directories).
*/
function file_create_path($dest = 0) {
$file_path = file_directory_path();
if (!$dest) {
return $file_path;
}
// file_check_location() checks whether the destination is inside the Drupal files directory.
if (file_check_location($dest, $file_path)) {
return $dest;
}
// check if the destination is instead inside the Drupal temporary files directory.
else if (file_check_location($dest, file_directory_temp())) {
return $dest;
}
// Not found, try again with prefixed directory path.
else if (file_check_location($file_path .'/'. $dest, $file_path)) {
return $file_path .'/'. $dest;
}
// File not found.
return FALSE;
}
/**
* Check that the directory exists and is writable. Directories need to
* have execute permissions to be considered a directory by FTP servers, etc.
*
* @param $directory A string containing the name of a directory path.
* @param $mode A Boolean value to indicate if the directory should be created
* if it does not exist or made writable if it is read-only.
* @param $form_item An optional string containing the name of a form item that
* any errors will be attached to. This is useful for settings forms that
* require the user to specify a writable directory. If it can't be made to
* work, a form error will be set preventing them from saving the settings.
* @return FALSE when directory not found, or TRUE when directory exists.
*/
function file_check_directory(&$directory, $mode = 0, $form_item = NULL) {
$directory = rtrim($directory, '/\\');
// Check if directory exists.
if (!is_dir($directory)) {
if (($mode & FILE_CREATE_DIRECTORY) && @mkdir($directory)) {
drupal_set_message(t('The directory %directory has been created.', array('%directory' => $directory)));
@chmod($directory, 0775); // Necessary for non-webserver users.
}
else {
if ($form_item) {
form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => $directory)));
}
return FALSE;
}
}
// Check to see if the directory is writable.
if (!is_writable($directory)) {
if (($mode & FILE_MODIFY_PERMISSIONS) && @chmod($directory, 0775)) {
drupal_set_message(t('The permissions of directory %directory have been changed to make it writable.', array('%directory' => $directory)));
}
else {
form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => $directory)));
watchdog('file system', 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => $directory), WATCHDOG_ERROR);
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));
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);
}
}
return TRUE;
}
/**
* Checks path to see if it is a directory, or a dir/file.
*
* @param $path A string containing a file path. This will be set to the
* directory's path.
* @return If the directory is not in a Drupal writable directory, FALSE is
* returned. Otherwise, the base name of the path is returned.
*/
function file_check_path(&$path) {
// Check if path is a directory.
if (file_check_directory($path)) {
return '';
}
// Check if path is a possible dir/file.
$filename = basename($path);
$path = dirname($path);
if (file_check_directory($path)) {
return $filename;
}
return FALSE;
}
/**
* 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
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');
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);
return 0;
}
// Process a file upload object.
if (is_object($source)) {
$file = $source;
$source = $file->filepath;
if (!$basename) {
$basename = $file->filename;
}
}
$source = realpath($source);
if (!file_exists($source)) {
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');
return 0;
}
// If the destination file is not specified then use the filename of the source file.
// Make sure source and destination filenames are not the same, makes no sense
// to copy it if they are. In fact copying the file will most likely result in
// a 0 byte file. Which is bad. Real bad.
if ($source != realpath($dest)) {
if (!$dest = file_destination($dest, $replace)) {
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');
return FALSE;
}
if (!@copy($source, $dest)) {
drupal_set_message(t('The selected file %file could not be copied.', array('%file' => $source)), 'error');
return 0;
}
// Give everyone read access so that FTP'd users or
// non-webserver users can see/read these files,
// and give group write permissions so group members
// can alter files uploaded by the webserver.
@chmod($dest, 0664);
}
if (isset($file) && is_object($file)) {
$file->filename = $basename;
$file->filepath = $dest;
$source = $file;
}
else {
$source = $dest;
}
return 1; // Everything went ok.
}
/**
* Determines the destination path for a file depending on how replacement of
* existing files should be handled.
*
* @param $destination A string specifying the desired path.
* @param $replace Replace behavior when the destination file already exists.
* - FILE_EXISTS_REPLACE - Replace the existing file
* - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is
* unique
* - FILE_EXISTS_ERROR - Do nothing and return FALSE.
* @return The destination file path or FALSE if the file already exists and
* FILE_EXISTS_ERROR was specified.
*/
function file_destination($destination, $replace) {
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');
return FALSE;
}
}
return $destination;
}
/**
* Moves a file to a new location.
* - Checks if $source and $dest are valid and readable/writable.
* - Performs a file move if $source is not equal to $dest.
* - If file already exists in $dest either the call will error out, replace the
* file or rename the file based on the $replace parameter.
*
* @param $source A string specifying the file location of the original file.
* This parameter will contain the resulting destination filename in case of
* success.
* @param $dest A string containing the directory $source should be copied to.
* If this value is omitted, Drupal's 'files' directory will be used.
* @param $replace Replace behavior when the destination file already exists.
* - FILE_EXISTS_REPLACE - Replace the existing file
* - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is unique
* - FILE_EXISTS_ERROR - Do nothing and return FALSE.
* @return True for success, FALSE for failure.
*/
function file_move(&$source, $dest = 0, $replace = FILE_EXISTS_RENAME) {
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');
return 0;
case UPLOAD_ERR_PARTIAL:
case UPLOAD_ERR_NO_FILE:
drupal_set_message(t('The file %file could not be saved, because the upload did not complete.', array('%file' => $source)), 'error');
return 0;
// Unknown error
default:
drupal_set_message(t('The file %file could not be saved. An unknown error has occurred.', array('%file' => $source)), 'error');
return 0;
}
// Build the list of non-munged extensions.
// @todo: this should not be here. we need to figure out the right place.
$errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions));
}
}
return $errors;
}
/**
* Check that the file's size is below certain limits. This check is not
* enforced for the user #1.
*
* @param $file
* A Drupal file object.
* @param $file_limit
* An integer specifying the maximum file size in bytes. Zero indicates that
* no limit should be enforced.
* @param $$user_limit
* An integer specifying the maximum number of bytes the user is allowed. Zero
* indicates that no limit should be enforced.
* @return
* An array. If the file size exceeds limits, it will contain an error message.
*/
function file_validate_size($file, $file_limit = 0, $user_limit = 0) {
global $user;
$errors = array();
// Bypass validation for uid = 1.
if ($user->uid != 1) {
if ($file_limit && $file->filesize > $file_limit) {
$errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', array('%filesize' => format_size($file->filesize), '%maxsize' => format_size($file_limit)));
$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)));
}
}
return $errors;
}
/**
* Check that the file is recognized by image_get_info() as an image.
*
* @param $file
* A Drupal file object.
* @return
* An array. If the file is not an image, it will contain an error message.
*/
function file_validate_is_image(&$file) {
$errors = array();
$info = image_get_info($file->filepath);
if (!$info || empty($info['extension'])) {
$errors[] = t('Only JPEG, PNG and GIF images are allowed.');
}
return $errors;
}
/**
* If the file is an image verify that its dimensions are within the specified
* maximum and minimum dimensions. Non-image files will be ignored.
*
* @param $file
* A Drupal file object. This function may resize the file affecting its size.
* @param $maximum_dimensions
* An optional string in the form WIDTHxHEIGHT e.g. '640x480' or '85x85'. If
* an image toolkit is installed the image will be resized down to these
* dimensions. A value of 0 indicates no restriction on size, so resizing
* will be attempted.
* @param $minimum_dimensions
* An optional string in the form WIDTHxHEIGHT. This will check that the image
* meets a minimum size. A value of 0 indicates no restriction.
* @return
* An array. If the file is an image and did not meet the requirements, it
* will contain an error message.
*/
function file_validate_image_resolution(&$file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
$errors = array();
// Check first that the file is an image.
if ($info = image_get_info($file->filepath)) {
if ($maximum_dimensions) {
// Check that it is smaller than the given dimensions.
if ($info['width'] > $width || $info['height'] > $height) {
// Try to resize the image to fit the dimensions.
if (image_get_toolkit() && image_scale($file->filepath, $file->filepath, $width, $height)) {
drupal_set_message(t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', array('%dimensions' => $maximum_dimensions)));
// Clear the cached filesize and refresh the image information.
clearstatcache();
$info = image_get_info($file->filepath);
$file->filesize = $info['file_size'];
}
else {
$errors[] = t('The image is too large; the maximum dimensions are %dimensions pixels.', array('%dimensions' => $maximum_dimensions));
}
}
}
if ($minimum_dimensions) {
// Check that it is larger than the given dimensions.