Index: modules/upload/upload.admin.inc =================================================================== RCS file: /cvs/drupal/drupal/modules/upload/upload.admin.inc,v retrieving revision 1.10 diff -u -r1.10 upload.admin.inc --- modules/upload/upload.admin.inc 16 Jul 2008 21:59:28 -0000 1.10 +++ modules/upload/upload.admin.inc 26 Jul 2008 22:32:33 -0000 @@ -74,11 +74,10 @@ '#field_suffix' => '' . t('WIDTHxHEIGHT') . '' ); $form['settings_general']['upload_list_default'] = array( - '#type' => 'select', + '#type' => 'checkbox', '#title' => t('List files by default'), '#default_value' => variable_get('upload_list_default', 1), - '#options' => array(0 => t('No'), 1 => t('Yes')), - '#description' => t('Display attached files when viewing a post.'), + '#description' => t('Determines whether attached files are shown to users by default.'), ); $form['settings_general']['upload_extensions_default'] = array( Index: modules/upload/upload.module =================================================================== RCS file: /cvs/drupal/drupal/modules/upload/upload.module,v retrieving revision 1.205 diff -u -r1.205 upload.module --- modules/upload/upload.module 24 Jul 2008 16:25:19 -0000 1.205 +++ modules/upload/upload.module 26 Jul 2008 22:32:33 -0000 @@ -263,6 +263,38 @@ } /** + * Implementation of hook_file_load(). + */ +function upload_file_load(&$file, $source = NULL) { + // Add the upload specific data into the file object. + $values = db_fetch_array(db_query('SELECT * FROM {upload} u WHERE u.fid = %d', $file->fid)); + foreach ((array)$values as $key => $value) { + $file->{$key} = $value; + } +} + +/** + * Implementation of hook_file_references(). + */ +function upload_file_references(&$file, $source = NULL) { + // If upload.module is still using a file, do not let other modules delete it. + $count = db_result(db_query('SELECT count(*) FROM {upload} WHERE fid = %d', $file->fid)); + if ($count) { + // return the name of the module and how many references it has to the file. + return array('upload' => $count); + } +} + +/** + * Implementation of hook_file_delete(). + */ +function upload_file_delete(&$file, $source = NULL) { + // Delete all information associated with the file. + db_query('DELETE FROM {upload} WHERE fid = %d', $file->fid); +} + + +/** * Implementation of hook_nodeapi(). */ function upload_nodeapi(&$node, $op, $teaser) { @@ -406,13 +438,15 @@ // If the file isn't used by any other revisions delete it. $count = db_result(db_query('SELECT COUNT(fid) FROM {upload} WHERE fid = %d', $fid)); if ($count < 1) { - file_delete($file->filepath); + file_delete($file); db_query('DELETE FROM {files} WHERE fid = %d', $fid); } // Remove it from the session in the case of new uploads, // that you want to disassociate before node submission. unset($_SESSION['upload_files'][$fid]); + // Try to clean up a file that is no longer in use. + file_delete($file); // Move on, so the removed file won't be added to new revisions. continue; } @@ -420,13 +454,12 @@ // Create a new revision, or associate a new file needed. if (!empty($node->old_vid) || isset($_SESSION['upload_files'][$fid])) { db_query("INSERT INTO {upload} (fid, nid, vid, list, description, weight) VALUES (%d, %d, %d, %d, '%s', %d)", $file->fid, $node->nid, $node->vid, $file->list, $file->description, $file->weight); - file_set_status($file, FILE_STATUS_PERMANENT); } // Update existing revision. else { db_query("UPDATE {upload} SET list = %d, description = '%s', weight = %d WHERE fid = %d AND vid = %d", $file->list, $file->description, $file->weight, $file->fid, $node->vid); - file_set_status($file, FILE_STATUS_PERMANENT); } + file_set_status($file, FILE_STATUS_PERMANENT); } // Empty the session storage after save. We use this variable to track files // that haven't been related to the node yet. @@ -434,38 +467,23 @@ } function upload_delete($node) { - $files = array(); - $result = db_query('SELECT DISTINCT f.* FROM {upload} u INNER JOIN {files} f ON u.fid = f.fid WHERE u.nid = %d', $node->nid); - while ($file = db_fetch_object($result)) { - $files[$file->fid] = $file; + db_query('DELETE FROM {upload} WHERE nid = %d', $node->nid); + if (!is_array($node->files)) { + return; } - - foreach ($files as $fid => $file) { - // Delete all files associated with the node - db_query('DELETE FROM {files} WHERE fid = %d', $fid); - file_delete($file->filepath); + foreach($node->files as $file) { + file_delete($file); } - - // Delete all file revision information associated with the node - db_query('DELETE FROM {upload} WHERE nid = %d', $node->nid); } function upload_delete_revision($node) { - if (is_array($node->files)) { - foreach ($node->files as $file) { - // Check if the file will be used after this revision is deleted - $count = db_result(db_query('SELECT COUNT(fid) FROM {upload} WHERE fid = %d', $file->fid)); - - // if the file won't be used, delete it - if ($count < 2) { - db_query('DELETE FROM {files} WHERE fid = %d', $file->fid); - file_delete($file->filepath); - } - } - } - - // delete the revision db_query('DELETE FROM {upload} WHERE vid = %d', $node->vid); + if (!is_array($node->files)) { + return; + } + foreach ($node->files as $file) { + file_delete($file); + } } function _upload_form($node) { @@ -479,11 +497,11 @@ if (!empty($node->files) && is_array($node->files)) { $form['files']['#theme'] = 'upload_form_current'; $form['files']['#tree'] = TRUE; - foreach ($node->files as $key => $file) { + foreach ($node->files as $file) { $file = (object)$file; - $description = file_create_url($file->filepath); - $description = "" . check_plain($description) . ""; - $form['files'][$key]['description'] = array('#type' => 'textfield', '#default_value' => !empty($file->description) ? $file->description : $file->filename, '#maxlength' => 256, '#description' => $description ); + $key = $file->fid; + + $form['files'][$key]['description'] = array('#type' => 'textfield', '#default_value' => !empty($file->description) ? $file->description : $file->filename, '#maxlength' => 256, '#description' => '' . file_create_url($file->filepath) . ''); $form['files'][$key]['size'] = array('#markup' => format_size($file->filesize)); $form['files'][$key]['remove'] = array('#type' => 'checkbox', '#default_value' => !empty($file->remove)); $form['files'][$key]['list'] = array('#type' => 'checkbox', '#default_value' => $file->list); @@ -498,12 +516,26 @@ if (user_access('upload files')) { $limits = _upload_file_limits($user); + + $limit_description = t('The maximum size of file uploads is %filesize. ', array('%filesize' => format_size($limits['file_size']))); + if (!empty($limits['resolution'])) { + if (image_get_toolkit()) { + $limit_description .= t('Images larger than %resolution will be resized. ', array('%resolution' => $limits['resolution'])); + } + else { + $limit_description .= t('Images may not be larger than %resolution. ', array('%resolution' => $limits['resolution'])); + } + } + if ($user->uid != 1) { + $limit_description .= t('Only files with the following extensions may be uploaded: %extensions. ', array('%extensions' => $limits['extensions'])); + } + $form['new']['#weight'] = 10; $form['new']['upload'] = array( '#type' => 'file', '#title' => t('Attach new file'), '#size' => 40, - '#description' => ($limits['resolution'] ? t('Images are larger than %resolution will be resized. ', array('%resolution' => $limits['resolution'])) : '') . t('The maximum upload size is %filesize. Only files with the following extensions may be uploaded: %extensions. ', array('%extensions' => $limits['extensions'], '%filesize' => format_size($limits['file_size']))), + '#description' => $limit_description, ); $form['new']['attach'] = array( '#type' => 'submit', @@ -565,9 +597,9 @@ $files = array(); if ($node->vid) { - $result = db_query('SELECT * FROM {files} f INNER JOIN {upload} r ON f.fid = r.fid WHERE r.vid = %d ORDER BY r.weight, f.fid', $node->vid); + $result = db_query('SELECT u.fid FROM {upload} u WHERE u.vid = %d ORDER BY u.fid', $node->vid); while ($file = db_fetch_object($result)) { - $files[$file->fid] = $file; + $files[$file->fid] = file_load($file->fid); } } Index: modules/blogapi/blogapi.module =================================================================== RCS file: /cvs/drupal/drupal/modules/blogapi/blogapi.module,v retrieving revision 1.120 diff -u -r1.120 blogapi.module --- modules/blogapi/blogapi.module 23 Jul 2008 07:42:08 -0000 1.120 +++ modules/blogapi/blogapi.module 26 Jul 2008 22:32:29 -0000 @@ -379,12 +379,12 @@ return blogapi_error(t('No file sent.')); } - if (!$file = file_save_data($data, $name)) { + if (!$filepath = file_save_data_plain($data, $name)) { return blogapi_error(t('Error storing file.')); } // Return the successful result. - return array('url' => file_create_url($file), 'struct'); + return array('url' => file_create_url($filepath), 'struct'); } /** * Blogging API callback. Returns a list of the taxonomy terms that can be Index: modules/user/user.module =================================================================== RCS file: /cvs/drupal/drupal/modules/user/user.module,v retrieving revision 1.912 diff -u -r1.912 user.module --- modules/user/user.module 16 Jul 2008 21:59:29 -0000 1.912 +++ modules/user/user.module 26 Jul 2008 22:32:36 -0000 @@ -406,8 +406,8 @@ ); if ($file = file_save_upload('picture_upload', $validators)) { // Remove the old picture. - if (isset($form_state['values']['_account']->picture) && file_exists($form_state['values']['_account']->picture)) { - file_delete($form_state['values']['_account']->picture); + if (isset($form_state['values']['_account']->picture)) { + file_delete_plain($form_state['values']['_account']->picture); } // The image was saved using file_save_upload() and was added to the @@ -415,8 +415,8 @@ // collector delete the original upload. $info = image_get_info($file->filepath); $destination = variable_get('user_picture_path', 'pictures') . '/picture-' . $form['#uid'] . '.' . $info['extension']; - if (file_copy($file, $destination, FILE_EXISTS_REPLACE)) { - $form_state['values']['picture'] = $file->filepath; + if (file_copy_plain($file->filepath, $destination, FILE_EXISTS_REPLACE)) { + $form_state['values']['picture'] = $destination; } else { form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures')))); @@ -839,7 +839,7 @@ $variables['picture'] = ''; if (variable_get('user_pictures', 0)) { $account = $variables['account']; - if (!empty($account->picture) && file_exists($account->picture)) { + if (!empty($account->picture) && file_exists(file_create_path($account->picture))) { $picture = file_create_url($account->picture); } else if (variable_get('user_picture_default', '')) { @@ -1532,8 +1532,8 @@ $user = user_load(array('uid' => $uid)); // Delete picture if requested, and if no replacement picture was given. if (!empty($edit['picture_delete'])) { - if ($user->picture && file_exists($user->picture)) { - file_delete($user->picture); + if ($user->picture) { + file_delete_plain($user->picture); } $edit['picture'] = ''; } Index: modules/system/system.admin.inc =================================================================== RCS file: /cvs/drupal/drupal/modules/system/system.admin.inc,v retrieving revision 1.82 diff -u -r1.82 system.admin.inc --- modules/system/system.admin.inc 23 Jul 2008 07:37:06 -0000 1.82 +++ modules/system/system.admin.inc 26 Jul 2008 22:32:33 -0000 @@ -338,9 +338,9 @@ // The image was saved using file_save_upload() and was added to the // files table as a temporary file. We'll make a copy and let the garbage // collector delete the original upload. - if (file_copy($file, $filename, FILE_EXISTS_REPLACE)) { + if ($filepath = file_copy_plain($file->filepath, $filename, FILE_EXISTS_REPLACE)) { $_POST['default_logo'] = 0; - $_POST['logo_path'] = $file->filepath; + $_POST['logo_path'] = $filepath; $_POST['toggle_logo'] = 1; } } @@ -353,9 +353,9 @@ // The image was saved using file_save_upload() and was added to the // files table as a temporary file. We'll make a copy and let the garbage // collector delete the original upload. - if (file_copy($file, $filename)) { + if ($filepath = file_copy_plain($file->filepath, $filename, FILE_EXISTS_REPLACE)) { $_POST['default_favicon'] = 0; - $_POST['favicon_path'] = $file->filepath; + $_POST['favicon_path'] = $filepath; $_POST['toggle_favicon'] = 1; } } Index: modules/system/system.module =================================================================== RCS file: /cvs/drupal/drupal/modules/system/system.module,v retrieving revision 1.611 diff -u -r1.611 system.module --- modules/system/system.module 23 Jul 2008 07:37:06 -0000 1.611 +++ modules/system/system.module 26 Jul 2008 22:32:33 -0000 @@ -1401,12 +1401,14 @@ if (file_exists($file->filepath)) { // If files that exist cannot be deleted, continue so the database remains // consistent. - if (!file_delete($file->filepath)) { - watchdog('file system', 'Could not delete temporary file "%path" during garbage collection', array('%path' => $file->filepath), 'error'); + if (!file_delete($file)) { + watchdog('file system', t('Could not delete temporary file "%path" during garbage collection', array('%path' => $file->filepath)), 'error'); continue; } } - db_query('DELETE FROM {files} WHERE fid = %d', $file->fid); + else { + db_query('DELETE FROM {files} WHERE fid = %d', $file->fid); + } } } Index: includes/file.inc =================================================================== RCS file: /cvs/drupal/drupal/includes/file.inc,v retrieving revision 1.127 diff -u -r1.127 file.inc --- includes/file.inc 5 Jul 2008 18:34:29 -0000 1.127 +++ includes/file.inc 26 Jul 2008 22:32:29 -0000 @@ -29,17 +29,18 @@ define('FILE_DOWNLOADS_PRIVATE', 2); /** - * Flag used by file_create_directory() -- create directory if not present. + * Flag used by file_check_directory() -- create directory if not present. */ define('FILE_CREATE_DIRECTORY', 1); /** - * Flag used by file_create_directory() -- file permissions may be changed. + * Flag used by file_check_directory() -- file permissions may be changed. */ define('FILE_MODIFY_PERMISSIONS', 2); /** - * Flag for dealing with existing files: Append number until filename is unique. + * Flag for dealing with existing files: Append number until filename is + * unique. */ define('FILE_EXISTS_RENAME', 0); @@ -77,7 +78,8 @@ * @return A string containing a URL that can be used to download the file. */ function file_create_url($path) { - // Strip file_directory_path from $path. We only include relative paths in urls. + // Strip file_directory_path from $path. We only include relative paths in + // URLs. if (strpos($path, file_directory_path() . '/') === 0) { $path = trim(substr($path, strlen(file_directory_path())), '\\/'); } @@ -93,28 +95,30 @@ * 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 + * @param $destination 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) { +function file_create_path($destination = 0) { $file_path = file_directory_path(); - if (!$dest) { + if (!$destination) { 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; + // file_check_location() checks whether the destination is inside the Drupal + // files directory. + if (file_check_location($destination, $file_path)) { + return $destination; + } + // Check if the destination is instead inside the Drupal temporary files + // directory. + else if (file_check_location($destination, file_directory_temp())) { + return $destination; } // Not found, try again with prefixed directory path. - else if (file_check_location($file_path . '/' . $dest, $file_path)) { - return $file_path . '/' . $dest; + else if (file_check_location($file_path . '/' . $destination, $file_path)) { + return $file_path . '/' . $destination; } // File not found. return FALSE; @@ -152,9 +156,13 @@ // Check to see if the directory is writable. if (!is_writable($directory)) { - if (($mode & FILE_MODIFY_PERMISSIONS) && !@chmod($directory, 0775)) { - 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); + // If not able to modify permissions, or if able to, but chmod + // fails, return false. + if (!$mode || (($mode & FILE_MODIFY_PERMISSIONS) && !@chmod($directory, 0775))) { + if ($form_item) { + 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; } } @@ -202,7 +210,8 @@ /** * 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. + * exploits. Note that the file or path being checked does not actually need + * to exist yet. * * @code * // Returns FALSE: @@ -211,7 +220,8 @@ * * @param $source A string set to the file to check. * @param $directory A string where the file should be located. - * @return FALSE for invalid path or the real path of the source. + * @return FALSE if the path does not exist in the directory; + * otherwise, the real path of the source. */ function file_check_location($source, $directory = '') { $check = realpath($source); @@ -219,7 +229,7 @@ $source = $check; } else { - // This file does not yet exist + // This file does not yet exist. $source = realpath(dirname($source)) . '/' . basename($source); } $directory = realpath($directory); @@ -230,67 +240,107 @@ } /** - * Copies a file to a new location. This is a powerful function that in many ways + * Copy a file to a new location and adds a file record to the database. + * + * This function should be used when manipulating files that have records + * stored in the database. 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 + * - Checks if $source and $destination are valid and readable/writable. + * - Performs a file copy if $source is not equal to $destination. + * - If file already exists in $destination either the call will error out, + * replace the file or rename the file based on the $replace parameter. + * - Adds the new file to the files database. If the source file is a + * temporary file, the resulting file will also be a temporary file. + * @see file_save_upload about temporary files. + * + * @param $source + * A file object. + * @param $destination + * 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. + * @return + * File object if the copy is successful, or FALSE in the event of an error. + * + * @see file_copy_plain() */ -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 FALSE; - } - - // Process a file upload object. - if (is_object($source)) { - $file = $source; - $source = $file->filepath; - if (!$basename) { - $basename = $file->filename; +function file_copy($source, $destination = 0, $replace = FILE_EXISTS_RENAME) { + if ($result = file_copy_plain($source->filepath, $destination, $replace)) { + $file = clone $source; + $file->fid = NULL; + $file->filename = basename($result); + $file->filepath = $result; + if ($file = file_save($file)) { + module_invoke_all('file_copy', $file, $source); + return $file; } } + return FALSE; +} +/** + * Copy a file to a new location without saving a record in the database. + * + * This is a powerful function that in many ways performs like an advanced + * version of copy(). + * - Checks if $source and $destination are valid and readable/writable. + * - Performs a file copy if $source is not equal to $destination. + * - If file already exists in $destination 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. + * @param $destination + * 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 + * The path to the new file, or FALSE in the event of an error. + * + * @see file_copy() + */ +function file_copy_plain($source, $destination = 0, $replace = FILE_EXISTS_RENAME) { $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 FALSE; } - // If the destination file is not specified then use the filename of the source file. + $destination = file_create_path($destination); + $directory = $destination; + $basename = file_check_path($directory); + + // Make sure we at least have a valid directory. + if ($basename === FALSE) { + drupal_set_message(t('The selected file %file could not be copied, because the destination %directory is not properly configured.', array('%file' => $source, '%directory' => $destination)), 'error'); + return FALSE; + } + + // If the destination file is not specified then use the filename of the + // source file. $basename = $basename ? $basename : basename($source); - $dest = $directory . '/' . $basename; + $destination = $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)) { + // 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($destination)) { + if (!$destination = 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' => $source)), 'error'); return FALSE; } - if (!@copy($source, $dest)) { + if (!@copy($source, $destination)) { drupal_set_message(t('The selected file %file could not be copied.', array('%file' => $source)), 'error'); return FALSE; } @@ -299,19 +349,10 @@ // 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; + @chmod($destination, 0664); } - return TRUE; // Everything went ok. + return $destination; } /** @@ -320,9 +361,9 @@ * * @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_REPLACE - Replace the existing file. * - FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is - * unique + * 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. @@ -330,6 +371,10 @@ function file_destination($destination, $replace) { if (file_exists($destination)) { switch ($replace) { + case FILE_EXISTS_REPLACE: + // Do nothing here, we want to overwrite the existing file. + break; + case FILE_EXISTS_RENAME: $basename = basename($destination); $directory = dirname($destination); @@ -345,38 +390,71 @@ } /** - * 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 + * Move a file to a new location and update the file's database entry. + * + * Moving a file is performed by copying the file to the new location and then + * deleting the original. + * - Checks if $source and $destination are valid and readable/writable. + * - Performs a file move if $source is not equal to $destination. + * - If file already exists in $destination either the call will error out, + * replace the file or rename the file based on the $replace parameter. + * - Adds the new file to the files database. + * + * @param $source + * A file object. + * @param $destination + * 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. + * @return + * Resulting file object for success, or FALSE in the event of an error. */ -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 TRUE; +function file_move($source, $destination = 0, $replace = FILE_EXISTS_RENAME) { + if ($result = file_move_plain($source->filepath, $destination, $replace)) { + $file = clone $source; + $file->filename = basename($result); + $file->filepath = $result; + if ($file = file_save($file)) { + module_invoke_all('file_move', $file, $source); + return $file; } - drupal_set_message(t('The removal of the original file %file has failed.', array('%file' => $path_original)), 'error'); + drupal_set_message(t('The removal of the original file %file has failed.', array('%file' => $source->filepath)), 'error'); } return FALSE; } /** + * Move a file to a new location. + * + * @param $source + * A string specifying the file location of the original file. + * @param $destination + * 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 + * The filepath of the moved file, or FALSE in the event of an error. + */ +function file_move_plain($source, $destination = 0, $replace = FILE_EXISTS_RENAME) { + if ($result = file_copy_plain($source, $destination, $replace)) { + if (!file_delete_plain($source)) { + $result = FALSE; + } + } + return $result; +} + +/** * Munge the filename as needed for security purposes. For instance the file * name "exploit.php.pps" would become "exploit.php_.pps". * @@ -438,9 +516,9 @@ * @return */ function file_create_filename($basename, $directory) { - $dest = $directory . '/' . $basename; + $destination = $directory . '/' . $basename; - if (file_exists($dest)) { + if (file_exists($destination)) { // Destination file already exists, generate an alternative. if ($pos = strrpos($basename, '.')) { $name = substr($basename, 0, $pos); @@ -452,45 +530,102 @@ $counter = 0; do { - $dest = $directory . '/' . $name . '_' . $counter++ . $ext; - } while (file_exists($dest)); + $destination = $directory . '/' . $name . '_' . $counter++ . $ext; + } while (file_exists($destination)); } - return $dest; + return $destination; +} + +/** + * Delete a file and its database record. + * + * @param $path + * A file object. + * @param $force + * Boolean indicating that the file should be deleted even if + * hook_file_references() reports that the file is in use. + * @return mixed + * TRUE for success, Array for reference count block, or FALSE in the event + * of an error. + * + * @see hook_file_references() + */ +function file_delete($file, $force = FALSE) { + // If any module returns a value from the reference hook, the + // file will not be deleted from Drupal, but file_delete will + // return a populated array that tests as TRUE. + if (!$force && ($references = module_invoke_all('file_references', $file))) { + return $references; + } + + // Let other modules clean up on delete. + module_invoke_all('file_delete', $file); + + // Make sure the file is deleted before removing its row from the + // database, so UIs can still find the file in the database. + if (file_delete_plain($file->filepath)) { + db_query('DELETE FROM {files} WHERE fid = %d', $file->fid); + return TRUE; + } + return FALSE; } /** * Delete a file. * - * @param $path A string containing a file path. - * @return TRUE for success, FALSE for failure. + * This function should be used when the file to be deleted does not have an + * entry recorded in the files table. + * + * @param $path + * A string containing a file path. + * @return + * TRUE for success or path does not exist, or FALSE in the event of an + * error. */ -function file_delete($path) { +function file_delete_plain($path) { if (is_file($path)) { return unlink($path); } + if (is_dir($path)) { + watchdog('file', t('%path is a directory and cannot be removed with file_delete_plain.', array('%path' => $path)), WATCHDOG_ERROR); + return FALSE; + } + // Return TRUE for non-existant file, but log that nothing was actually + // deleted, as the intended result of file_delete_plain is in fact the + // current state. + if (!file_exists($path)) { + watchdog('file', t('The file %path was not deleted, because it does not exist.', array('%path' => $path)), WATCHDOG_NOTICE); + return TRUE; + } + return FALSE; } /** * Determine total disk space used by a single user or the whole filesystem. * * @param $uid - * An optional user id. A NULL value returns the total space used - * by all files. + * Optional. A user id, specifying NULL returns the total space used by all + * non-temporary files. + * @param $status + * Optional. File Status to return. Combine with a bitwise OR(|) to return + * multiple statuses. The default status is FILE_STATUS_PERMANENT. + * @return + * An integer containing the number of bytes used. */ -function file_space_used($uid = NULL) { +function file_space_used($uid = NULL, $status = FILE_STATUS_PERMANENT) { if (isset($uid)) { - return (int) db_result(db_query('SELECT SUM(filesize) FROM {files} WHERE uid = %d', $uid)); + return (int)db_result(db_query('SELECT SUM(filesize) FROM {files} WHERE uid = %d AND status & %d', $uid, $status)); } - return (int) db_result(db_query('SELECT SUM(filesize) FROM {files}')); + return (int)db_result(db_query('SELECT SUM(filesize) FROM {files} WHERE status & %d', $status)); } /** * 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 + * 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 its status. * * @param $source @@ -502,7 +637,7 @@ * 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 $dest + * @param $destination * A string containing the directory $source should be copied to. If this is * not provided or is not writable, the temporary directory will be used. * @param $replace @@ -510,25 +645,27 @@ * 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 FALSE in the event of an error. + * An object containing the file information, or FALSE in the event of an + * error. */ -function file_save_upload($source, $validators = array(), $dest = FALSE, $replace = FILE_EXISTS_RENAME) { +function file_save_upload($source, $validators = array(), $destination = 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]; } + // Add in our check of the the file name length. + $validators['file_validate_name_length'] = array(); + + // 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. + // 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: @@ -560,9 +697,12 @@ // Begin building file object. $file = new stdClass(); + $file->uid = $user->uid; + $file->status = FILE_STATUS_TEMPORARY; $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]; + $file->filesize = $_FILES['files']['size'][$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')) { @@ -573,26 +713,28 @@ // If the destination is not provided, or is not writable, then use the // temporary directory. - if (empty($dest) || file_check_path($dest) === FALSE) { - $dest = file_directory_temp(); + if (empty($destination) || file_check_path($destination) === FALSE) { + $destination = file_directory_temp(); } $file->source = $source; - $file->destination = file_destination(file_create_path($dest . '/' . $file->filename), $replace); - $file->filesize = $_FILES['files']['size'][$source]; + $file->destination = file_destination(file_create_path($destination . '/' . $file->filename), $replace); - // Call the validation functions. + // Call the validation functions specified by this function's caller. $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. + // Let other modules perform validation on the new file. + $errors = array_merge($errors, module_invoke_all('file_validate', $file)); + + // Check for errors. if (!empty($errors)) { $message = t('The selected file %name could not be uploaded.', array('%name' => $file->filename)); if (count($errors) > 1) { - $message .= '