Newer
Older
/**
* Implementation of hook_help().
*/
Dries Buytaert
committed
case 'admin/help#upload':
$output = '<p>'. t('The upload module allows users to upload files to the site. The ability to upload files to a site is important for members of a community who want to share work. It is also useful to administrators who want to keep uploaded files connected to a node or page.') .'</p>';
$output .= '<p>'. t('Users with the upload files permission can upload attachments. You can choose which post types can take attachments on the content types settings page. Each user role can be customized for the file size of uploads, and the dimension of image files.') .'</p>';
$output .= t('<p>You can</p>
<ul>
<li>administer user permissions at <a href="%admin-access">administer >> access control</a>.</li>
<li>administer content at <a href="%admin-content-types">administer >> settings >> content types</a>.</li>
<li>administer upload at <a href="%admin-upload">administer >> settings >> upload</a>.</li>
Dries Buytaert
committed
</ul>
', array('%admin-access' => url('admin/access'), '%admin-content-types' => url('admin/settings/content-types'), '%admin-upload' => url('admin/settings/upload')));
Dries Buytaert
committed
$output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%upload">Upload page</a>.', array('%upload' => 'http://drupal.org/handbook/modules/upload/')) .'</p>';
Dries Buytaert
committed
return $output;
Dries Buytaert
committed
return t('Allows users to upload and attach files to content.');
Dries Buytaert
committed
case 'admin/settings/upload':
Gerhard Killesreiter
committed
return t('<p>Users with the <a href="%permissions">upload files permission</a> can upload attachments. Users with the <a href="%permissions">view uploaded files permission</a> can view uploaded attachments. You can choose which post types can take attachments on the <a href="%types">content types settings</a> page.</p>', array('%permissions' => url('admin/access'), '%types' => url('admin/settings/content-types')));
/**
* Implementation of hook_perm().
*/
Steven Wittens
committed
return array('upload files', 'view uploaded files');
/**
* Implementation of hook_link().
*/
function upload_link($type, $node = 0, $main = 0) {
$links = array();
// Display a link with the number of attachments
if ($main && $type == 'node' && isset($node->files) && user_access('view uploaded files')) {
$num_files = 0;
foreach ($node->files as $file) {
if ($file->list) {
$num_files++;
}
}
if ($num_files) {
$links[] = l(format_plural($num_files, '1 attachment', '%count attachments'), "node/$node->nid", array('title' => t('Read full article to view attachments.')), NULL, 'attachments');
}
}
return $links;
}
/**
* Implementation of hook_menu().
*/
function upload_menu($may_cache) {
$items = array();
if ($may_cache) {
$items[] = array(
'path' => 'upload/js',
'callback' => 'upload_js',
'access' => user_access('upload files'),
'type' => MENU_CALLBACK
);
Dries Buytaert
committed
}
else {
if (isset($_SESSION['file_previews'])) {
foreach ($_SESSION['file_previews'] as $fid => $file) {
Gerhard Killesreiter
committed
if (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PRIVATE) {
// strip file_directory_path() from filename. @see file_create_url
if (strpos($filename, file_directory_path()) !== false) {
$filename = trim(substr($filename, strlen(file_directory_path())), '\\/');
}
$filename = 'system/files/' . $filename;
Gerhard Killesreiter
committed
}
$items[] = array(
'path' => $filename, 'title' => t('file download'),
'callback' => 'upload_download',
Steven Wittens
committed
'access' => user_access('view uploaded files'),
Dries Buytaert
committed
'type' => MENU_CALLBACK
$_SESSION['file_previews'][$fid]->_filename = $filename;
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/**
* Form API callback to validate the upload settings form.
*/
function upload_settings_form_validate($form_id, $form_values) {
if (($form_values['upload_max_resolution'] != '0')) {
if (!preg_match('/^[0-9]+x[0-9]+$/', $form_values['upload_max_resolution'])) {
form_set_error('upload_max_resolution', t('The maximum allowed image size expressed as WIDTHxHEIGHT (e.g. 640x480). Set to 0 for no restriction.'));
}
}
$exceed_max_msg = t('Your PHP settings limit the maximum file size per upload to %size MB.', array('%size' => file_upload_max_size())).'<br/>';
$more_info = t("Depending on your sever environment, these settings may be changed in the system-wide php.ini file, a php.ini file in your Drupal root directory, in your Drupal site's settings.php file, or in the .htaccess file in your Drupal root directory.");
foreach ($form_values['roles'] as $rid => $role) {
$uploadsize = $form_values['upload_uploadsize_'. $rid];
$usersize = $form_values['upload_usersize_'. $rid];
if (!is_numeric($uploadsize) || ($uploadsize <= 0)) {
form_set_error('upload_uploadsize_'. $rid, t('The %role file size limit must be a number and greater than zero.', array('%role' => theme('placeholder', $role))));
}
if (!is_numeric($usersize) || ($usersize <= 0)) {
form_set_error('upload_usersize_'. $rid, t('The %role file size limit must be a number and greater than zero.', array('%role' => theme('placeholder', $role))));
}
if ($uploadsize > file_upload_max_size()) {
form_set_error('upload_uploadsize_'. $rid, $exceed_max_msg . $more_info);
$more_info = '';
}
if ($uploadsize > $usersize) {
form_set_error('upload_uploadsize_'. $rid, t('The %role maximum file size per upload is greater than the total file size allowed per user', array('%role' => theme('placeholder', $role))));
}
}
}
function upload_settings() {
Dries Buytaert
committed
$form['settings_general'] = array('#type' => 'fieldset', '#title' => t('General settings'));
$form['settings_general']['upload_max_resolution'] = array(
Dries Buytaert
committed
'#type' => 'textfield', '#title' => t('Maximum resolution for uploaded images'), '#default_value' => variable_get('upload_max_resolution', 0),
'#size' => 15, '#maxlength' => 10, '#description' => t('The maximum allowed image size expressed as WIDTHxHEIGHT (e.g. 640x480). Set to 0 for no restriction.')
$form['settings_general']['upload_list_default'] = array('#type' => 'select', '#title' => t('List files by default'),
Gerhard Killesreiter
committed
'#default_value' => variable_get('upload_list_default',1),
'#options' => array( 0 => t('No'), 1 => t('Yes') ),
'#description' => t('Set whether files attached to nodes are listed or not in the node view by default.'),
);
$form['upload_max_size'] = array('#value' => '<p>'. t('Your PHP settings limit the maximum file size per upload to %size MB.', array('%size' => file_upload_max_size())).'</p>');
$roles = user_roles(0, 'upload files');
$form['roles'] = array('#type' => 'value', '#value' => $roles);
Dries Buytaert
committed
$form["settings_role_$rid"] = array('#type' => 'fieldset', '#title' => t('Settings for %role', array('%role' => theme('placeholder', $role))), '#collapsible' => TRUE, '#collapsed' => TRUE);
$form["settings_role_$rid"]["upload_extensions_$rid"] = array(
'#type' => 'textfield', '#title' => t('Permitted file extensions'), '#default_value' => variable_get("upload_extensions_$rid", 'jpg jpeg gif png txt doc xls xls pdf ppt pps odt ods odp'),
'#maxlength' => 255, '#description' => t('Extensions that users in this role can upload. Separate extensions with a space and do not include the leading dot.')
);
$form["settings_role_$rid"]["upload_uploadsize_$rid"] = array(
Dries Buytaert
committed
'#type' => 'textfield', '#title' => t('Maximum file size per upload'), '#default_value' => variable_get("upload_uploadsize_$rid", 1),
'#size' => 5, '#maxlength' => 5, '#description' => t('The maximum size of a file a user can upload (in megabytes).')
);
$form["settings_role_$rid"]["upload_usersize_$rid"] = array(
Dries Buytaert
committed
'#type' => 'textfield', '#title' => t('Total file size per user'), '#default_value' => variable_get("upload_usersize_$rid", 10),
'#size' => 5, '#maxlength' => 5, '#description' => t('The maximum size of all files a user can have on the site (in megabytes).')
// Note: form_id constructed in system_site_settings() is 'upload_settings_form'
foreach ($_SESSION['file_previews'] as $file) {
file_transfer($file->filepath, array('Content-Type: '. mime_header_encode($file->filemime), 'Content-Length: '. $file->filesize));
Gerhard Killesreiter
committed
$file = file_create_path($file);
$result = db_query("SELECT f.* FROM {files} f WHERE filepath = '%s'", $file);
if ($file = db_fetch_object($result)) {
if (user_access('view uploaded files')) {
$node = node_load($file->nid);
if (node_access('view', $node)) {
$name = mime_header_encode($file->filename);
$type = mime_header_encode($file->filemime);
return array(
'Content-Type: '. $type .'; name='. $name,
'Content-Length: '. $file->filesize,
Gerhard Killesreiter
committed
'Expires: 0', 'Pragma: cache', 'Cache-Control: private'
Dries Buytaert
committed
else {
return -1;
}
Steven Wittens
committed
}
Gerhard Killesreiter
committed
else {
return -1;
}
Dries Buytaert
committed
}
Gerhard Killesreiter
committed
/**
* Save new uploads and attach them to the node object.
* append file_previews to the node object as well.
*/
function _upload_prepare(&$node) {
// Clean up old file previews if a post didn't get the user to this page.
// i.e. the user left the edit page, because they didn't want to upload anything.
if(count($_POST) == 0) {
if (is_array($_SESSION['file_previews']) && count($_SESSION['file_previews'])) {
foreach($_SESSION['file_previews'] as $fid => $file) {
}
unset($_SESSION['file_previews']);
}
}
Gerhard Killesreiter
committed
// $_SESSION['file_current_upload'] tracks the fid of the file submitted this page request.
// form_builder sets the value of file->list to 0 for checkboxes added to a form after
// it has been submitted. Since unchecked checkboxes have no return value and do not
// get a key in _POST form_builder has no way of knowing the difference between a check
// box that wasn't present on the last form build, and a checkbox that is unchecked.
Gerhard Killesreiter
committed
unset($_SESSION['file_current_upload']);
// Save new file uploads to tmp dir.
if (($file = file_check_upload()) && user_access('upload files')) {
// Scale image uploads.
$file = _upload_image($file);
$key = 'upload_'. count($_SESSION['file_previews']);
$file->fid = $key;
$file->source = $key;
$file->list = variable_get('upload_list_default',1);
$_SESSION['file_previews'][$key] = $file;
// Store the uploaded fid for this page request in case of submit without
// preview or attach. See earlier notes.
Gerhard Killesreiter
committed
$_SESSION['file_current_upload'] = $key;
}
// Attach file previews to node object.
if (is_array($_SESSION['file_previews']) && count($_SESSION['file_previews'])) {
foreach($_SESSION['file_previews'] as $fid => $file) {
if ($user->uid != 1) {
// Here something.php.pps becomes something.php_.pps
$file->filename = upload_munge_filename($file->filename, NULL, 0);
$file->description = $file->filename;
}
$node->files[$fid] = $file;
}
}
}
Dries Buytaert
committed
function upload_form_alter($form_id, &$form) {
Dries Buytaert
committed
if (isset($form['type'])) {
if ($form['type']['#value'] .'_node_settings' == $form_id) {
$form['workflow']['upload_'. $form['type']['#value']] = array(
'#type' => 'radios', '#title' => t('Attachments'), '#default_value' => variable_get('upload_'. $form['type']['#value'], 1),
'#options' => array(t('Disabled'), t('Enabled')),
);
}
Dries Buytaert
committed
Dries Buytaert
committed
$node = $form['#node'];
if ($form['type']['#value'] .'_node_form' == $form_id && variable_get("upload_$node->type", TRUE) && user_access('upload files')) {
Dries Buytaert
committed
drupal_add_js('misc/progress.js');
drupal_add_js('misc/upload.js');
// Attachments fieldset
Dries Buytaert
committed
$form['attachments'] = array(
'#type' => 'fieldset',
'#title' => t('File attachments'),
'#collapsible' => TRUE,
'#collapsed' => empty($node->files),
'#description' => t('Changes made to the attachments are not permanent until you save this post. The first "listed" file will be included in RSS feeds.'),
'#prefix' => '<div class="attachments">',
'#suffix' => '</div>',
'#weight' => 30,
Dries Buytaert
committed
);
// Wrapper for fieldset contents (used by upload JS).
$form['attachments']['wrapper'] = array(
'#prefix' => '<div id="attach-wrapper">',
'#suffix' => '</div>',
);
$form['attachments']['wrapper'] += _upload_form($node);
$form['#attributes']['enctype'] = 'multipart/form-data';
Dries Buytaert
committed
}
Dries Buytaert
committed
}
}
function _upload_validate(&$node) {
// Accumulator for disk space quotas.
$filesize = 0;
// Check if node->files exists, and if it contains something.
Gerhard Killesreiter
committed
if (is_array($node->files)) {
// Update existing files with form data.
foreach($node->files as $fid => $file) {
// Convert file to object for compatibility
$file = (object)$file;
Dries Buytaert
committed
// Validate new uploads.
if (strpos($fid, 'upload') !== false && !$file->remove) {
// Bypass validation for uid = 1.
// Update filesize accumulator.
$filesize += $file->filesize;
// Validate file against all users roles.
// Only denies an upload when all roles prevent it.
Dries Buytaert
committed
$total_usersize = upload_space_used($user->uid) + $filesize;
Gerhard Killesreiter
committed
$error = array();
$extensions = variable_get("upload_extensions_$rid", 'jpg jpeg gif png txt doc xls xls pdf ppt pps odt ods odp');
$uploadsize = variable_get("upload_uploadsize_$rid", 1) * 1024 * 1024;
Gerhard Killesreiter
committed
$usersize = variable_get("upload_usersize_$rid", 10) * 1024 * 1024;
$regex = '/\.('. ereg_replace(' +', '|', preg_quote($extensions)) .')$/i';
if (!preg_match($regex, $file->filename)) {
$error['extension']++;
}
Dries Buytaert
committed
if ($uploadsize && $file->filesize > $uploadsize) {
Dries Buytaert
committed
if ($usersize && $total_usersize + $file->filesize > $usersize) {
Gerhard Killesreiter
committed
$user_roles = count($user->roles);
$valid = TRUE;
if ($error['extension'] == $user_roles) {
form_set_error('upload', t('The selected file %name can not be attached to this post, because it is only possible to attach files with the following extensions: %files-allowed.', array('%name' => theme('placeholder', $file->filename), '%files-allowed' => theme('placeholder', $extensions))));
Gerhard Killesreiter
committed
$valid = FALSE;
Gerhard Killesreiter
committed
elseif ($error['uploadsize'] == $user_roles) {
form_set_error('upload', t('The selected file %name can not be attached to this post, because it exceeded the maximum filesize of %maxsize.', array('%name' => theme('placeholder', $file->filename), '%maxsize' => theme('placeholder', format_size($uploadsize)))));
Gerhard Killesreiter
committed
$valid = FALSE;
Gerhard Killesreiter
committed
elseif ($error['usersize'] == $user_roles) {
form_set_error('upload', t('The selected file %name can not be attached to this post, because the disk quota of %quota has been reached.', array('%name' => theme('placeholder', $file->filename), '%quota' => theme('placeholder', format_size($usersize)))));
Gerhard Killesreiter
committed
$valid = FALSE;
elseif (strlen($file->filename) > 255) {
form_set_error('upload', t('The selected file %name can not be attached to this post, because the filename is too long.', array('%name' => theme('placeholder', $file->filename))));
Gerhard Killesreiter
committed
if (!$valid) {
Gerhard Killesreiter
committed
unset($node->files[$fid], $_SESSION['file_previews'][$fid]);
file_delete($file->filepath);
}
}
}
}
/**
* Implementation of hook_nodeapi().
*/
Gerhard Killesreiter
committed
function upload_nodeapi(&$node, $op, $teaser) {
switch ($op) {
Dries Buytaert
committed
Steven Wittens
committed
if (variable_get("upload_$node->type", 1) == 1) {
return $output;
break;
case 'prepare':
_upload_prepare($node);
break;
case 'validate':
_upload_validate($node);
Dries Buytaert
committed
if (isset($node->files) && user_access('view uploaded files')) {
Gerhard Killesreiter
committed
// Manipulate so that inline references work in preview
if (!variable_get('clean_url', 0)) {
$previews = array();
foreach ($node->files as $file) {
if (strpos($file->fid, 'upload') !== false) {
Gerhard Killesreiter
committed
// URLs to files being previewed are actually Drupal paths. When Clean
// URLs are disabled, the two do not match. We perform an automatic
// replacement from temporary to permanent URLs. That way, the author
// can use the final URL in the body before having actually saved (to
// place inline images for example).
foreach ($previews as $file) {
$old = file_create_filename($file->filename, file_create_path());
$new = url($old);
$node->body = str_replace($old, $new, $node->body);
$node->teaser = str_replace($old, $new, $node->teaser);
}
}
Gerhard Killesreiter
committed
// Add the attachments list to node body
if (count($node->files) && !$teaser) {
$node->body .= theme('upload_attachments', $node->files);
Dries Buytaert
committed
if (user_access('upload files')) {
upload_save($node);
}
Dries Buytaert
committed
case 'delete revision':
upload_delete_revision($node);
break;
Gerhard Killesreiter
committed
return is_array($node->files) ? format_plural(count($node->files), '1 attachment', '%count attachments') : null;
Gerhard Killesreiter
committed
if (is_array($node->files)) {
$files = array();
foreach ($node->files as $file) {
if ($file->list) {
$files[] = $file;
}
}
if (count($files) > 0) {
// RSS only allows one enclosure per item
$file = array_shift($files);
return array(
array(
'key' => 'enclosure',
'attributes' => array(
'url' => file_create_url($file->filepath),
'length' => $file->filesize,
'type' => $file->filemime
)
)
);
return array();
Gerhard Killesreiter
committed
}
}
Gerhard Killesreiter
committed
/**
* Displays file attachments in table
*/
function theme_upload_attachments($files) {
$header = array(t('Attachment'), t('Size'));
$rows = array();
foreach ($files as $file) {
Gerhard Killesreiter
committed
$file = (object)$file;
if ($file->list && !$file->remove) {
// Generate valid URL for both existing attachments and preview of new attachments (these have 'upload' in fid)
$href = file_create_url((strpos($file->fid, 'upload') === FALSE ? $file->filepath : file_create_filename($file->filename, file_create_path())));
Gerhard Killesreiter
committed
$text = $file->description ? $file->description : $file->filename;
Gerhard Killesreiter
committed
$rows[] = array(l($text, $href), format_size($file->filesize));
}
}
if (count($rows)) {
return theme('table', $header, $rows, array('id' => 'attachments'));
Dries Buytaert
committed
/**
* Determine how much disk space is occupied by a user's uploaded files.
*
* @param $uid
* The integer user id of a user.
* @return
Dries Buytaert
committed
* The amount of disk space used by the user in bytes.
Dries Buytaert
committed
*/
function upload_space_used($uid) {
Dries Buytaert
committed
return db_result(db_query('SELECT SUM(filesize) FROM {files} f INNER JOIN {node} n ON f.nid = n.nid WHERE n.uid = %d', $uid));
Dries Buytaert
committed
}
Dries Buytaert
committed
/**
* Determine how much disk space is occupied by uploaded files.
*
* @return
Dries Buytaert
committed
* The amount of disk space used by uploaded files in bytes.
Dries Buytaert
committed
*/
function upload_total_space_used() {
Dries Buytaert
committed
return db_result(db_query('SELECT SUM(filesize) FROM {files}'));
/**
* Munge the filename as needed for security purposes.
*
* @param $filename
* The name of a file to modify.
* @param $extensions
* A space separated list of valid extensions. If this is blank, we'll use
* the admin-defined defaults for the user role from upload_extensions_$rid.
* @param $alerts
* Whether alerts (watchdog, drupal_set_message()) should be displayed.
* @return $filename
* The potentially modified $filename.
*/
function upload_munge_filename($filename, $extensions = NULL, $alerts = 1) {
global $user;
$original = $filename;
// Allow potentially insecure uploads for very savvy users and admin
if (!variable_get('allow_insecure_uploads', 0)) {
if (!isset($extensions)) {
$extensions = '';
foreach ($user->roles as $rid => $name) {
$extensions .= ' '. variable_get("upload_extensions_$rid", variable_get('upload_extensions_default', 'jpg jpeg gif png txt doc xls xls pdf ppt pps odt ods odp'));
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
}
}
$whitelist = array_unique(explode(' ', trim($extensions)));
$filename_parts = explode('.', $filename);
$new_filename = array_shift($filename_parts); // Remove file basename.
$final_extension = array_pop($filename_parts); // Remove final extension.
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) {
$message = t('Your filename has been renamed to conform to site policy.');
drupal_set_message($message);
}
return $filename;
}
/**
* Undo the effect of upload_munge_filename().
*/
function upload_unmunge_filename($filename) {
return str_replace('_.', '.', $filename);
}
Gerhard Killesreiter
committed
function upload_save(&$node) {
Gerhard Killesreiter
committed
if (!is_array($node->files)) {
return;
}
foreach ($node->files as $fid => $file) {
// Convert file to object for compatibility
$file = (object)$file;
// Remove file. Process removals first since no further processing
// will be required.
if ($file->remove) {
// Remove file previews...
if (strpos($file->fid, 'upload') !== false) {
Dries Buytaert
committed
// Remove managed files.
else {
db_query('DELETE FROM {file_revisions} WHERE fid = %d AND vid = %d', $fid, $node->vid);
Dries Buytaert
committed
// Only delete a file if it isn't used by any revision
$count = db_result(db_query('SELECT COUNT(fid) FROM {file_revisions} WHERE fid = %d', $fid));
Dries Buytaert
committed
if ($count < 1) {
db_query('DELETE FROM {files} WHERE fid = %d', $fid);
Dries Buytaert
committed
file_delete($file->filepath);
}
Dries Buytaert
committed
// New file upload
elseif (strpos($file->fid, 'upload') !== false) {
if ($file = file_save_upload($file, $file->filename)) {
$file->fid = db_next_id('{files}_fid');
db_query("INSERT INTO {files} (fid, nid, filename, filepath, filemime, filesize) VALUES (%d, %d, '%s', '%s', '%s', %d)", $file->fid, $node->nid, $file->filename, $file->filepath, $file->filemime, $file->filesize);
db_query("INSERT INTO {file_revisions} (fid, vid, list, description) VALUES (%d, %d, %d, '%s')", $file->fid, $node->vid, $file->list, $file->description);
Gerhard Killesreiter
committed
// tell other modules where the file was stored.
$node->files[$fid] = $file;
Dries Buytaert
committed
}
unset($_SESSION['file_previews'][$fid]);
}
// Create a new revision, as needed
elseif ($node->old_vid && is_numeric($fid)) {
db_query("INSERT INTO {file_revisions} (fid, vid, list, description) VALUES (%d, %d, %d, '%s')", $file->fid, $node->vid, $file->list, $file->description);
}
// Update existing revision
else {
db_query("UPDATE {file_revisions} SET list = %d, description = '%s' WHERE fid = %d AND vid = %d", $file->list, $file->description, $file->fid, $node->vid);
Dries Buytaert
committed
}
}
Dries Buytaert
committed
$files = array();
$result = db_query('SELECT * FROM {files} WHERE nid = %d', $node->nid);
while ($file = db_fetch_object($result)) {
$files[$file->fid] = $file;
}
foreach ($files as $fid => $file) {
// Delete all file revision information associated with the node
Dries Buytaert
committed
db_query('DELETE FROM {file_revisions} WHERE fid = %d', $fid);
Dries Buytaert
committed
// Delete all files associated with the node
Dries Buytaert
committed
db_query('DELETE FROM {files} WHERE nid = %d', $node->nid);
}
function upload_delete_revision($node) {
Gerhard Killesreiter
committed
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 {file_revisions} 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);
}
Dries Buytaert
committed
}
}
// delete the revision
db_query('DELETE FROM {file_revisions} WHERE vid = %d', $node->vid);
function _upload_form($node) {
Dries Buytaert
committed
$form['#theme'] = 'upload_form_new';
if (is_array($node->files) && count($node->files)) {
$form['files']['#theme'] = 'upload_form_current';
$form['files']['#tree'] = TRUE;
$description = file_create_url((strpos($file->fid, 'upload') === false ? $file->filepath : file_create_filename($file->filename, file_create_path())));
$description = "<small>". check_plain($description) ."</small>";
$form['files'][$key]['description'] = array('#type' => 'textfield', '#default_value' => (strlen($file->description)) ? $file->description : $file->filename, '#maxlength' => 256, '#description' => $description );
$form['files'][$key]['size'] = array('#type' => 'markup', '#value' => format_size($file->filesize));
$form['files'][$key]['remove'] = array('#type' => 'checkbox', '#default_value' => $file->remove);
$form['files'][$key]['list'] = array('#type' => 'checkbox', '#default_value' => $file->list);
Gerhard Killesreiter
committed
// if the file was uploaded this page request, set value. this fixes the problem
// formapi has recognizing new checkboxes. see comments in _upload_prepare.
if ($_SESSION['file_current_upload'] == $file->fid) {
$form['files'][$key]['list']['#value'] = variable_get('upload_list_default',1);
}
$form['files'][$key]['filename'] = array('#type' => 'value', '#value' => $file->filename);
$form['files'][$key]['filepath'] = array('#type' => 'value', '#value' => $file->filepath);
$form['files'][$key]['filemime'] = array('#type' => 'value', '#value' => $file->filemime);
$form['files'][$key]['filesize'] = array('#type' => 'value', '#value' => $file->filesize);
$form['files'][$key]['fid'] = array('#type' => 'value', '#value' => $file->fid);
Dries Buytaert
committed
if (user_access('upload files')) {
// This div is hidden when the user uploads through JS.
$form['new'] = array(
'#prefix' => '<div id="attach-hide">',
'#suffix' => '</div>',
);
Dries Buytaert
committed
$form['new']['upload'] = array('#type' => 'file', '#title' => t('Attach new file'), '#size' => 40);
$form['new']['attach'] = array('#type' => 'button', '#value' => t('Attach'), '#name'=> 'attach', '#attributes' => array('id' => 'attach'));
// The class triggers the js upload behaviour.
$form['attach'] = array('#type' => 'hidden', '#value' => url('upload/js', NULL, NULL, TRUE), '#attributes' => array('class' => 'upload'));
Dries Buytaert
committed
// Needed for JS
$form['current']['vid'] = array('#type' => 'hidden', '#value' => $node->vid);
/**
* Theme the attachments list.
*/
function theme_upload_form_current(&$form) {
$header = array(t('Delete'), t('List'), t('Description'), t('Size'));
foreach (element_children($form) as $key) {
$row[] = form_render($form[$key]['remove']);
$row[] = form_render($form[$key]['list']);
$row[] = form_render($form[$key]['description']);
$row[] = form_render($form[$key]['size']);
$rows[] = $row;
}
$output = theme('table', $header, $rows);
$output .= form_render($form);
return $output;
/**
* Theme the attachment form.
* Note: required to output prefix/suffix.
*/
function theme_upload_form_new($form) {
$output = form_render($form);
return $output;
}
$result = db_query('SELECT * FROM {files} f INNER JOIN {file_revisions} r ON f.fid = r.fid WHERE r.vid = %d ORDER BY f.fid', $node->vid);
while ($file = db_fetch_object($result)) {
$files[$file->fid] = $file;
}
}
return $files;
}
Dries Buytaert
committed
/**
* Check an upload, if it is an image, make sure it fits within the
* maximum dimensions allowed.
*/
function _upload_image($file) {
$info = image_get_info($file->filepath);
if ($info) {
list($width, $height) = explode('x', variable_get('upload_max_resolution', 0));
if ($width && $height) {
$result = image_scale($file->filepath, $file->filepath, $width, $height);
if ($result) {
$file->filesize = filesize($file->filepath);
drupal_set_message(t('The image was resized to fit within the maximum allowed resolution of %resolution pixels.', array('%resolution' => theme('placeholder', variable_get('upload_max_resolution', 0)))));
Dries Buytaert
committed
}
}
}
return $file;
}
/**
* Menu-callback for JavaScript-based uploads.
*/
function upload_js() {
// We only do the upload.module part of the node validation process.
$node = (object)$_POST['edit'];
// Load existing node files.
$node->files = upload_load($node);
// Handle new uploads, and merge tmp files into node-files.
_upload_prepare($node);
_upload_validate($node);
$form = _upload_form($node);
foreach (module_implements('form_alter') as $module) {
$function = $module .'_form_alter';
$function('upload_js', $form);
}
$form = form_builder('upload_js', $form);
$output = theme('status_messages') . form_render($form);
// We send the updated file attachments form.
print drupal_to_js(array('status' => TRUE, 'data' => $output));