TRUE));
}
}
/**
* 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);
return FALSE;
}
}
if ((file_directory_path() == $directory || file_directory_temp() == $directory) && !is_file("$directory/.htaccess")) {
$htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
if (($fp = fopen("$directory/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
fclose($fp);
chmod($directory .'/.htaccess', 0664);
}
else {
$variables = array('%directory' => $directory, '!htaccess' => '
'. nl2br(check_plain($htaccess_lines)));
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: !htaccess
", $variables));
watchdog('security', "Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines: !htaccess
", $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
* exploits.
*
* @code
* // Returns FALSE:
* file_check_location('/www/example.com/files/../../../etc/passwd', '/www/example.com/files');
* @endcode
*
* @param $source A string set to the file to check.
* @param $directory A string where the file should be located.
* @return 0 for invalid path or the real path of the source.
*/
function file_check_location($source, $directory = '') {
$check = realpath($source);
if ($check) {
$source = $check;
}
else {
// This file does not yet exist
$source = realpath(dirname($source)) .'/'. basename($source);
}
$directory = realpath($directory);
if ($directory && strpos($source, $directory) !== 0) {
return 0;
}
return $source;
}
/**
* Copies a file to a new location. This is a powerful function that in many ways
* performs like an advanced version of copy().
* - Checks if $source and $dest are valid and readable/writable.
* - Performs a file copy 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_copy(&$source, $dest = 0, $replace = FILE_EXISTS_RENAME) {
$dest = file_create_path($dest);
$directory = $dest;
$basename = file_check_path($directory);
// Make sure we at least have a valid directory.
if ($basename === FALSE) {
$source = is_object($source) ? $source->filepath : $source;
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.
$basename = $basename ? $basename : basename($source);
$dest = $directory .'/'. $basename;
// 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) {
if (file_exists($destination)) {
switch ($replace) {
case FILE_EXISTS_RENAME:
$basename = basename($destination);
$directory = dirname($destination);
$destination = file_create_filename($basename, $directory);
break;
case FILE_EXISTS_ERROR:
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) {
$path_original = is_object($source) ? $source->filepath : $source;
if (file_copy($source, $dest, $replace)) {
$path_current = is_object($source) ? $source->filepath : $source;
if ($path_original == $path_current || file_delete($path_original)) {
return 1;
}
drupal_set_message(t('The removal of the original file %file has failed.', array('%file' => $path_original)), 'error');
}
return 0;
}
/**
* Munge the filename as needed for security purposes. For instance the file
* name "exploit.php.pps" would become "exploit.php_.pps".
*
* @param $filename The name of a file to modify.
* @param $extensions A space separated list of extensions that should not
* be altered.
* @param $alerts Whether alerts (watchdog, drupal_set_message()) should be
* displayed.
* @return $filename The potentially modified $filename.
*/
function file_munge_filename($filename, $extensions, $alerts = TRUE) {
$original = $filename;
// Allow potentially insecure uploads for very savvy users and admin
if (!variable_get('allow_insecure_uploads', 0)) {
$whitelist = array_unique(explode(' ', trim($extensions)));
// Split the filename up by periods. The first part becomes the basename
// the last part the final extension.
$filename_parts = explode('.', $filename);
$new_filename = array_shift($filename_parts); // Remove file basename.
$final_extension = array_pop($filename_parts); // Remove final extension.
// Loop through the middle parts of the name and add an underscore to the
// end of each section that could be a file extension but isn't in the list
// of allowed extensions.
foreach ($filename_parts as $filename_part) {
$new_filename .= '.'. $filename_part;
if (!in_array($filename_part, $whitelist) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $filename_part)) {
$new_filename .= '_';
}
}
$filename = $new_filename .'.'. $final_extension;
if ($alerts && $original != $filename) {
drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $filename)));
}
}
return $filename;
}
/**
* Undo the effect of upload_munge_filename().
*
* @param $filename string filename
* @return string
*/
function file_unmunge_filename($filename) {
return str_replace('_.', '.', $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.
*
* @param $basename string filename
* @param $directory string directory
* @return
*/
function file_create_filename($basename, $directory) {
$dest = $directory .'/'. $basename;
if (file_exists($dest)) {
// Destination file already exists, generate an alternative.
if ($pos = strrpos($basename, '.')) {
$name = substr($basename, 0, $pos);
$ext = substr($basename, $pos);
}
else {
$name = $basename;
}
$counter = 0;
do {
$dest = $directory .'/'. $name .'_'. $counter++ . $ext;
} while (file_exists($dest));
}
return $dest;
}
/**
* Delete a file.
*
* @param $path A string containing a file path.
* @return TRUE for success, FALSE for failure.
*/
function file_delete($path) {
if (is_file($path)) {
return unlink($path);
}
}
/**
* Determine the total amount of disk space used by a single user's files, or
* the filesystem as a whole.
*
* @param $uid An optional, user id. A NULL value returns the total space used
* by all files.
*/
function file_space_used($uid = NULL) {
if (is_null($uid)) {
return db_result(db_query('SELECT SUM(filesize) FROM {files} WHERE uid = %d', $uid));
}
return db_result(db_query('SELECT SUM(filesize) FROM {files}'));
}
/**
* Saves a file upload to a new location. The source file is validated as a
* proper upload and handled as such.
*
* The file will be added to the files table as a temporary file. Temporary files
* are periodically cleaned. To make the file permanent file call
* file_set_status() to change it's status.
*
* @param $source
* A string specifying the name of the upload field to save.
* @param $dest
* A string containing the directory $source should be copied to. If this is
* not provided, the temporary directory will be used.
* @param $validators
* An optional, associative array of callback functions used to validate the
* file. The keys are function names and the values arrays of callback
* parameters which will be passed in after the user and file objects. The
* functions should return an array of error messages, an empty array
* indicates that the file passed validation. The functions will be called in
* the order specified.
* @param $replace
* A boolean indicating whether an existing file of the same name in the
* destination directory should overwritten. A false value will generate a
* new, unique filename in the destination directory.
* @return
* An object containing the file information, or 0 in the event of an error.
*/
function file_save_upload($source, $validators = array(), $dest = FALSE, $replace = FILE_EXISTS_RENAME) {
global $user;
static $upload_cache;
// Add in our check of the the file name length.
$validators['file_validate_name_length'] = array();
// Return cached objects without processing since the file will have
// already been processed and the paths in _FILES will be invalid.
if (isset($upload_cache[$source])) {
return $upload_cache[$source];
}
// If a file was uploaded, process it.
if (isset($_FILES['files']) && $_FILES['files']['name'][$source] && is_uploaded_file($_FILES['files']['tmp_name'][$source])) {
// Check for file upload errors and return FALSE if a
// lower level system error occurred.
switch ($_FILES['files']['error'][$source]) {
// @see http://php.net/manual/en/features.file-upload.errors.php
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
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.
$extensions = '';
foreach ($user->roles as $rid => $name) {
$extensions .= ' '. variable_get("upload_extensions_$rid",
variable_get('upload_extensions_default', 'jpg jpeg gif png txt html doc xls pdf ppt pps odt ods odp'));
}
// Begin building file object.
$file = new stdClass();
$file->filename = file_munge_filename(trim(basename($_FILES['files']['name'][$source]), '.'), $extensions);
$file->filepath = $_FILES['files']['tmp_name'][$source];
$file->filemime = $_FILES['files']['type'][$source];
// Rename potentially executable files, to help prevent exploits.
if (preg_match('/\.(php|pl|py|cgi|asp|js)$/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
$file->filemime = 'text/plain';
$file->filepath .= '.txt';
$file->filename .= '.txt';
}
// Create temporary name/path for newly uploaded files.
if (!$dest) {
$dest = file_destination(file_create_path($file->filename), FILE_EXISTS_RENAME);
}
$file->source = $source;
$file->destination = $dest;
$file->filesize = $_FILES['files']['size'][$source];
// Call the validation functions.
$errors = array();
foreach ($validators as $function => $args) {
array_unshift($args, $file);
$errors = array_merge($errors, call_user_func_array($function, $args));
}
// Check for validation errors.
if (!empty($errors)) {
$message = t('The selected file %name could not be uploaded. ', array('%name' => $file->filename));
if (count($errors) > 1) {
$message .= '