upload.module

  1. drupal
    1. 4.6 modules/upload.module
    2. 4.7 modules/upload.module
    3. 5 modules/upload/upload.module
    4. 6 modules/upload/upload.module

File-handling and attaching files to nodes.

Functions & methods

NameDescription
theme_upload_attachmentsDisplays file attachments in table
theme_upload_form_currentTheme the attachments list.
theme_upload_form_newTheme the attachment form. Note: required to output prefix/suffix.
upload_delete
upload_delete_revision
upload_download
upload_file_download
upload_form_alter
upload_helpImplementation of hook_help().
upload_jsMenu-callback for JavaScript-based uploads.
upload_linkImplementation of hook_link().
upload_load
upload_menuImplementation of hook_menu().
upload_munge_filenameMunge the filename as needed for security purposes.
upload_nodeapiImplementation of hook_nodeapi().
upload_permImplementation of hook_perm().
upload_save
upload_settings
upload_settings_form_validateForm API callback to validate the upload settings form.
upload_space_usedDetermine how much disk space is occupied by a user's uploaded files.
upload_total_space_usedDetermine how much disk space is occupied by uploaded files.
upload_unmunge_filenameUndo the effect of upload_munge_filename().
_upload_form
_upload_imageCheck an upload, if it is an image, make sure it fits within the maximum dimensions allowed.
_upload_prepareSave new uploads and attach them to the node object. append file_previews to the node object as well.
_upload_validate

File

modules/upload.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * File-handling and attaching files to nodes.
  5. *
  6. */
  7. /**
  8. * Implementation of hook_help().
  9. */
  10. function upload_help($section) {
  11. switch ($section) {
  12. case 'admin/help#upload':
  13. $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>';
  14. $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>';
  15. $output .= t('<p>You can</p>
  16. <ul>
  17. <li>administer user permissions at <a href="%admin-access">administer &gt;&gt; access control</a>.</li>
  18. <li>administer content at <a href="%admin-content-types">administer &gt;&gt; settings &gt;&gt; content types</a>.</li>
  19. <li>administer upload at <a href="%admin-upload">administer &gt;&gt; settings &gt;&gt; upload</a>.</li>
  20. </ul>
  21. ', array('%admin-access' => url('admin/access'), '%admin-content-types' => url('admin/settings/content-types'), '%admin-upload' => url('admin/settings/upload')));
  22. $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>';
  23. return $output;
  24. case 'admin/modules#description':
  25. return t('Allows users to upload and attach files to content.');
  26. case 'admin/settings/upload':
  27. 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')));
  28. }
  29. }
  30. /**
  31. * Implementation of hook_perm().
  32. */
  33. function upload_perm() {
  34. return array('upload files', 'view uploaded files');
  35. }
  36. /**
  37. * Implementation of hook_link().
  38. */
  39. function upload_link($type, $node = 0, $main = 0) {
  40. $links = array();
  41. // Display a link with the number of attachments
  42. if ($main && $type == 'node' && isset($node->files) && user_access('view uploaded files')) {
  43. $num_files = 0;
  44. foreach ($node->files as $file) {
  45. if ($file->list) {
  46. $num_files++;
  47. }
  48. }
  49. if ($num_files) {
  50. $links[] = l(format_plural($num_files, '1 attachment', '%count attachments'), "node/$node->nid", array('title' => t('Read full article to view attachments.')), NULL, 'attachments');
  51. }
  52. }
  53. return $links;
  54. }
  55. /**
  56. * Implementation of hook_menu().
  57. */
  58. function upload_menu($may_cache) {
  59. $items = array();
  60. if ($may_cache) {
  61. $items[] = array(
  62. 'path' => 'upload/js',
  63. 'callback' => 'upload_js',
  64. 'access' => user_access('upload files'),
  65. 'type' => MENU_CALLBACK
  66. );
  67. }
  68. else {
  69. // Add handlers for previewing new uploads.
  70. if (isset($_SESSION['file_previews'])) {
  71. foreach ($_SESSION['file_previews'] as $fid => $file) {
  72. $filename = file_create_filename($file->filename, file_create_path());
  73. if (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PRIVATE) {
  74. // strip file_directory_path() from filename. @see file_create_url
  75. if (strpos($filename, file_directory_path()) !== false) {
  76. $filename = trim(substr($filename, strlen(file_directory_path())), '\\/');
  77. }
  78. $filename = 'system/files/' . $filename;
  79. }
  80. $items[] = array(
  81. 'path' => $filename, 'title' => t('file download'),
  82. 'callback' => 'upload_download',
  83. 'access' => user_access('view uploaded files'),
  84. 'type' => MENU_CALLBACK
  85. );
  86. $_SESSION['file_previews'][$fid]->_filename = $filename;
  87. }
  88. }
  89. }
  90. return $items;
  91. }
  92. /**
  93. * Form API callback to validate the upload settings form.
  94. */
  95. function upload_settings_form_validate($form_id, $form_values) {
  96. if (($form_values['upload_max_resolution'] != '0')) {
  97. if (!preg_match('/^[0-9]+x[0-9]+$/', $form_values['upload_max_resolution'])) {
  98. form_set_error('upload_max_resolution', t('The maximum allowed image size expressed as WIDTHxHEIGHT (e.g. 640x480). Set to 0 for no restriction.'));
  99. }
  100. }
  101. $exceed_max_msg = t('Your PHP settings limit the maximum file size per upload to %size MB.', array('%size' => file_upload_max_size())).'<br/>';
  102. $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.");
  103. foreach ($form_values['roles'] as $rid => $role) {
  104. $uploadsize = $form_values['upload_uploadsize_'. $rid];
  105. $usersize = $form_values['upload_usersize_'. $rid];
  106. if (!is_numeric($uploadsize) || ($uploadsize <= 0)) {
  107. 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))));
  108. }
  109. if (!is_numeric($usersize) || ($usersize <= 0)) {
  110. 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))));
  111. }
  112. if ($uploadsize > file_upload_max_size()) {
  113. form_set_error('upload_uploadsize_'. $rid, $exceed_max_msg . $more_info);
  114. $more_info = '';
  115. }
  116. if ($uploadsize > $usersize) {
  117. 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))));
  118. }
  119. }
  120. }
  121. function upload_settings() {
  122. $form['settings_general'] = array('#type' => 'fieldset', '#title' => t('General settings'));
  123. $form['settings_general']['upload_max_resolution'] = array(
  124. '#type' => 'textfield', '#title' => t('Maximum resolution for uploaded images'), '#default_value' => variable_get('upload_max_resolution', 0),
  125. '#size' => 15, '#maxlength' => 10, '#description' => t('The maximum allowed image size expressed as WIDTHxHEIGHT (e.g. 640x480). Set to 0 for no restriction.')
  126. );
  127. $form['settings_general']['upload_list_default'] = array('#type' => 'select', '#title' => t('List files by default'),
  128. '#default_value' => variable_get('upload_list_default',1),
  129. '#options' => array( 0 => t('No'), 1 => t('Yes') ),
  130. '#description' => t('Set whether files attached to nodes are listed or not in the node view by default.'),
  131. );
  132. $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>');
  133. $roles = user_roles(0, 'upload files');
  134. $form['roles'] = array('#type' => 'value', '#value' => $roles);
  135. foreach ($roles as $rid => $role) {
  136. $form["settings_role_$rid"] = array('#type' => 'fieldset', '#title' => t('Settings for %role', array('%role' => theme('placeholder', $role))), '#collapsible' => TRUE, '#collapsed' => TRUE);
  137. $form["settings_role_$rid"]["upload_extensions_$rid"] = array(
  138. '#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'),
  139. '#maxlength' => 255, '#description' => t('Extensions that users in this role can upload. Separate extensions with a space and do not include the leading dot.')
  140. );
  141. $form["settings_role_$rid"]["upload_uploadsize_$rid"] = array(
  142. '#type' => 'textfield', '#title' => t('Maximum file size per upload'), '#default_value' => variable_get("upload_uploadsize_$rid", 1),
  143. '#size' => 5, '#maxlength' => 5, '#description' => t('The maximum size of a file a user can upload (in megabytes).')
  144. );
  145. $form["settings_role_$rid"]["upload_usersize_$rid"] = array(
  146. '#type' => 'textfield', '#title' => t('Total file size per user'), '#default_value' => variable_get("upload_usersize_$rid", 10),
  147. '#size' => 5, '#maxlength' => 5, '#description' => t('The maximum size of all files a user can have on the site (in megabytes).')
  148. );
  149. }
  150. // Note: form_id constructed in system_site_settings() is 'upload_settings_form'
  151. return $form;
  152. }
  153. function upload_download() {
  154. foreach ($_SESSION['file_previews'] as $file) {
  155. if ($file->_filename == $_GET['q']) {
  156. file_transfer($file->filepath, array('Content-Type: '. mime_header_encode($file->filemime), 'Content-Length: '. $file->filesize));
  157. }
  158. }
  159. }
  160. function upload_file_download($file) {
  161. $file = file_create_path($file);
  162. $result = db_query("SELECT f.* FROM {files} f WHERE filepath = '%s'", $file);
  163. if ($file = db_fetch_object($result)) {
  164. if (user_access('view uploaded files')) {
  165. $node = node_load($file->nid);
  166. if (node_access('view', $node)) {
  167. $name = mime_header_encode($file->filename);
  168. $type = mime_header_encode($file->filemime);
  169. return array(
  170. 'Content-Type: '. $type .'; name='. $name,
  171. 'Content-Length: '. $file->filesize,
  172. 'Expires: 0', 'Pragma: cache', 'Cache-Control: private'
  173. );
  174. }
  175. else {
  176. return -1;
  177. }
  178. }
  179. else {
  180. return -1;
  181. }
  182. }
  183. }
  184. /**
  185. * Save new uploads and attach them to the node object.
  186. * append file_previews to the node object as well.
  187. */
  188. function _upload_prepare(&$node) {
  189. // Clean up old file previews if a post didn't get the user to this page.
  190. // i.e. the user left the edit page, because they didn't want to upload anything.
  191. if(count($_POST) == 0) {
  192. if (is_array($_SESSION['file_previews']) && count($_SESSION['file_previews'])) {
  193. foreach($_SESSION['file_previews'] as $fid => $file) {
  194. file_delete($file->filepath);
  195. }
  196. unset($_SESSION['file_previews']);
  197. }
  198. }
  199. // $_SESSION['file_current_upload'] tracks the fid of the file submitted this page request.
  200. // form_builder sets the value of file->list to 0 for checkboxes added to a form after
  201. // it has been submitted. Since unchecked checkboxes have no return value and do not
  202. // get a key in _POST form_builder has no way of knowing the difference between a check
  203. // box that wasn't present on the last form build, and a checkbox that is unchecked.
  204. unset($_SESSION['file_current_upload']);
  205. global $user;
  206. // Save new file uploads to tmp dir.
  207. if (($file = file_check_upload()) && user_access('upload files')) {
  208. // Scale image uploads.
  209. $file = _upload_image($file);
  210. $key = 'upload_'. count($_SESSION['file_previews']);
  211. $file->fid = $key;
  212. $file->source = $key;
  213. $file->list = variable_get('upload_list_default',1);
  214. $_SESSION['file_previews'][$key] = $file;
  215. // Store the uploaded fid for this page request in case of submit without
  216. // preview or attach. See earlier notes.
  217. $_SESSION['file_current_upload'] = $key;
  218. }
  219. // Attach file previews to node object.
  220. if (is_array($_SESSION['file_previews']) && count($_SESSION['file_previews'])) {
  221. foreach($_SESSION['file_previews'] as $fid => $file) {
  222. if ($user->uid != 1) {
  223. // Here something.php.pps becomes something.php_.pps
  224. $file->filename = upload_munge_filename($file->filename, NULL, 0);
  225. $file->description = $file->filename;
  226. }
  227. $node->files[$fid] = $file;
  228. }
  229. }
  230. }
  231. function upload_form_alter($form_id, &$form) {
  232. if (isset($form['type'])) {
  233. if ($form['type']['#value'] .'_node_settings' == $form_id) {
  234. $form['workflow']['upload_'. $form['type']['#value']] = array(
  235. '#type' => 'radios', '#title' => t('Attachments'), '#default_value' => variable_get('upload_'. $form['type']['#value'], 1),
  236. '#options' => array(t('Disabled'), t('Enabled')),
  237. );
  238. }
  239. $node = $form['#node'];
  240. if ($form['type']['#value'] .'_node_form' == $form_id && variable_get("upload_$node->type", TRUE) && user_access('upload files')) {
  241. drupal_add_js('misc/progress.js');
  242. drupal_add_js('misc/upload.js');
  243. // Attachments fieldset
  244. $form['attachments'] = array(
  245. '#type' => 'fieldset',
  246. '#title' => t('File attachments'),
  247. '#collapsible' => TRUE,
  248. '#collapsed' => empty($node->files),
  249. '#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.'),
  250. '#prefix' => '<div class="attachments">',
  251. '#suffix' => '</div>',
  252. '#weight' => 30,
  253. );
  254. // Wrapper for fieldset contents (used by upload JS).
  255. $form['attachments']['wrapper'] = array(
  256. '#prefix' => '<div id="attach-wrapper">',
  257. '#suffix' => '</div>',
  258. );
  259. $form['attachments']['wrapper'] += _upload_form($node);
  260. $form['#attributes']['enctype'] = 'multipart/form-data';
  261. }
  262. }
  263. }
  264. function _upload_validate(&$node) {
  265. // Accumulator for disk space quotas.
  266. $filesize = 0;
  267. // Check if node->files exists, and if it contains something.
  268. if (is_array($node->files)) {
  269. // Update existing files with form data.
  270. foreach($node->files as $fid => $file) {
  271. // Convert file to object for compatibility
  272. $file = (object)$file;
  273. // Validate new uploads.
  274. if (strpos($fid, 'upload') !== false && !$file->remove) {
  275. global $user;
  276. // Bypass validation for uid = 1.
  277. if ($user->uid != 1) {
  278. // Update filesize accumulator.
  279. $filesize += $file->filesize;
  280. // Validate file against all users roles.
  281. // Only denies an upload when all roles prevent it.
  282. $total_usersize = upload_space_used($user->uid) + $filesize;
  283. $error = array();
  284. foreach ($user->roles as $rid => $name) {
  285. $extensions = variable_get("upload_extensions_$rid", 'jpg jpeg gif png txt doc xls xls pdf ppt pps odt ods odp');
  286. $uploadsize = variable_get("upload_uploadsize_$rid", 1) * 1024 * 1024;
  287. $usersize = variable_get("upload_usersize_$rid", 10) * 1024 * 1024;
  288. $regex = '/\.('. ereg_replace(' +', '|', preg_quote($extensions)) .')$/i';
  289. if (!preg_match($regex, $file->filename)) {
  290. $error['extension']++;
  291. }
  292. if ($uploadsize && $file->filesize > $uploadsize) {
  293. $error['uploadsize']++;
  294. }
  295. if ($usersize && $total_usersize + $file->filesize > $usersize) {
  296. $error['usersize']++;
  297. }
  298. }
  299. $user_roles = count($user->roles);
  300. $valid = TRUE;
  301. if ($error['extension'] == $user_roles) {
  302. 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))));
  303. $valid = FALSE;
  304. }
  305. elseif ($error['uploadsize'] == $user_roles) {
  306. 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)))));
  307. $valid = FALSE;
  308. }
  309. elseif ($error['usersize'] == $user_roles) {
  310. 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)))));
  311. $valid = FALSE;
  312. }
  313. elseif (strlen($file->filename) > 255) {
  314. 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))));
  315. $valid = FALSE;
  316. }
  317. if (!$valid) {
  318. unset($node->files[$fid], $_SESSION['file_previews'][$fid]);
  319. file_delete($file->filepath);
  320. }
  321. }
  322. }
  323. }
  324. }
  325. }
  326. /**
  327. * Implementation of hook_nodeapi().
  328. */
  329. function upload_nodeapi(&$node, $op, $teaser) {
  330. switch ($op) {
  331. case 'load':
  332. $output = '';
  333. if (variable_get("upload_$node->type", 1) == 1) {
  334. $output['files'] = upload_load($node);
  335. return $output;
  336. }
  337. break;
  338. case 'prepare':
  339. _upload_prepare($node);
  340. break;
  341. case 'validate':
  342. _upload_validate($node);
  343. break;
  344. case 'view':
  345. if (isset($node->files) && user_access('view uploaded files')) {
  346. // Manipulate so that inline references work in preview
  347. if (!variable_get('clean_url', 0)) {
  348. $previews = array();
  349. foreach ($node->files as $file) {
  350. if (strpos($file->fid, 'upload') !== false) {
  351. $previews[] = $file;
  352. }
  353. }
  354. // URLs to files being previewed are actually Drupal paths. When Clean
  355. // URLs are disabled, the two do not match. We perform an automatic
  356. // replacement from temporary to permanent URLs. That way, the author
  357. // can use the final URL in the body before having actually saved (to
  358. // place inline images for example).
  359. foreach ($previews as $file) {
  360. $old = file_create_filename($file->filename, file_create_path());
  361. $new = url($old);
  362. $node->body = str_replace($old, $new, $node->body);
  363. $node->teaser = str_replace($old, $new, $node->teaser);
  364. }
  365. }
  366. // Add the attachments list to node body
  367. if (count($node->files) && !$teaser) {
  368. $node->body .= theme('upload_attachments', $node->files);
  369. }
  370. }
  371. break;
  372. case 'insert':
  373. case 'update':
  374. if (user_access('upload files')) {
  375. upload_save($node);
  376. }
  377. break;
  378. case 'delete':
  379. upload_delete($node);
  380. break;
  381. case 'delete revision':
  382. upload_delete_revision($node);
  383. break;
  384. case 'search result':
  385. return is_array($node->files) ? format_plural(count($node->files), '1 attachment', '%count attachments') : null;
  386. case 'rss item':
  387. if (is_array($node->files)) {
  388. $files = array();
  389. foreach ($node->files as $file) {
  390. if ($file->list) {
  391. $files[] = $file;
  392. }
  393. }
  394. if (count($files) > 0) {
  395. // RSS only allows one enclosure per item
  396. $file = array_shift($files);
  397. return array(
  398. array(
  399. 'key' => 'enclosure',
  400. 'attributes' => array(
  401. 'url' => file_create_url($file->filepath),
  402. 'length' => $file->filesize,
  403. 'type' => $file->filemime
  404. )
  405. )
  406. );
  407. }
  408. }
  409. return array();
  410. }
  411. }
  412. /**
  413. * Displays file attachments in table
  414. */
  415. function theme_upload_attachments($files) {
  416. $header = array(t('Attachment'), t('Size'));
  417. $rows = array();
  418. foreach ($files as $file) {
  419. $file = (object)$file;
  420. if ($file->list && !$file->remove) {
  421. // Generate valid URL for both existing attachments and preview of new attachments (these have 'upload' in fid)
  422. $href = file_create_url((strpos($file->fid, 'upload') === FALSE ? $file->filepath : file_create_filename($file->filename, file_create_path())));
  423. $text = $file->description ? $file->description : $file->filename;
  424. $rows[] = array(l($text, $href), format_size($file->filesize));
  425. }
  426. }
  427. if (count($rows)) {
  428. return theme('table', $header, $rows, array('id' => 'attachments'));
  429. }
  430. }
  431. /**
  432. * Determine how much disk space is occupied by a user's uploaded files.
  433. *
  434. * @param $uid
  435. * The integer user id of a user.
  436. * @return
  437. * The amount of disk space used by the user in bytes.
  438. */
  439. function upload_space_used($uid) {
  440. 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));
  441. }
  442. /**
  443. * Determine how much disk space is occupied by uploaded files.
  444. *
  445. * @return
  446. * The amount of disk space used by uploaded files in bytes.
  447. */
  448. function upload_total_space_used() {
  449. return db_result(db_query('SELECT SUM(filesize) FROM {files}'));
  450. }
  451. /**
  452. * Munge the filename as needed for security purposes.
  453. *
  454. * @param $filename
  455. * The name of a file to modify.
  456. * @param $extensions
  457. * A space separated list of valid extensions. If this is blank, we'll use
  458. * the admin-defined defaults for the user role from upload_extensions_$rid.
  459. * @param $alerts
  460. * Whether alerts (watchdog, drupal_set_message()) should be displayed.
  461. * @return $filename
  462. * The potentially modified $filename.
  463. */
  464. function upload_munge_filename($filename, $extensions = NULL, $alerts = 1) {
  465. global $user;
  466. $original = $filename;
  467. // Allow potentially insecure uploads for very savvy users and admin
  468. if (!variable_get('allow_insecure_uploads', 0)) {
  469. if (!isset($extensions)) {
  470. $extensions = '';
  471. foreach ($user->roles as $rid => $name) {
  472. $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'));
  473. }
  474. }
  475. $whitelist = array_unique(explode(' ', trim($extensions)));
  476. $filename_parts = explode('.', $filename);
  477. $new_filename = array_shift($filename_parts); // Remove file basename.
  478. $final_extension = array_pop($filename_parts); // Remove final extension.
  479. foreach($filename_parts as $filename_part) {
  480. $new_filename .= ".$filename_part";
  481. if (!in_array($filename_part, $whitelist) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $filename_part)) {
  482. $new_filename .= '_';
  483. }
  484. }
  485. $filename = "$new_filename.$final_extension";
  486. }
  487. if ($alerts && $original != $filename) {
  488. $message = t('Your filename has been renamed to conform to site policy.');
  489. drupal_set_message($message);
  490. }
  491. return $filename;
  492. }
  493. /**
  494. * Undo the effect of upload_munge_filename().
  495. */
  496. function upload_unmunge_filename($filename) {
  497. return str_replace('_.', '.', $filename);
  498. }
  499. function upload_save(&$node) {
  500. if (!is_array($node->files)) {
  501. return;
  502. }
  503. foreach ($node->files as $fid => $file) {
  504. // Convert file to object for compatibility
  505. $file = (object)$file;
  506. // Remove file. Process removals first since no further processing
  507. // will be required.
  508. if ($file->remove) {
  509. // Remove file previews...
  510. if (strpos($file->fid, 'upload') !== false) {
  511. file_delete($file->filepath);
  512. }
  513. // Remove managed files.
  514. else {
  515. db_query('DELETE FROM {file_revisions} WHERE fid = %d AND vid = %d', $fid, $node->vid);
  516. // Only delete a file if it isn't used by any revision
  517. $count = db_result(db_query('SELECT COUNT(fid) FROM {file_revisions} WHERE fid = %d', $fid));
  518. if ($count < 1) {
  519. db_query('DELETE FROM {files} WHERE fid = %d', $fid);
  520. file_delete($file->filepath);
  521. }
  522. }
  523. }
  524. // New file upload
  525. elseif (strpos($file->fid, 'upload') !== false) {
  526. if ($file = file_save_upload($file, $file->filename)) {
  527. $file->fid = db_next_id('{files}_fid');
  528. 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);
  529. db_query("INSERT INTO {file_revisions} (fid, vid, list, description) VALUES (%d, %d, %d, '%s')", $file->fid, $node->vid, $file->list, $file->description);
  530. // tell other modules where the file was stored.
  531. $node->files[$fid] = $file;
  532. }
  533. unset($_SESSION['file_previews'][$fid]);
  534. }
  535. // Create a new revision, as needed
  536. elseif ($node->old_vid && is_numeric($fid)) {
  537. db_query("INSERT INTO {file_revisions} (fid, vid, list, description) VALUES (%d, %d, %d, '%s')", $file->fid, $node->vid, $file->list, $file->description);
  538. }
  539. // Update existing revision
  540. else {
  541. db_query("UPDATE {file_revisions} SET list = %d, description = '%s' WHERE fid = %d AND vid = %d", $file->list, $file->description, $file->fid, $node->vid);
  542. }
  543. }
  544. }
  545. function upload_delete($node) {
  546. $files = array();
  547. $result = db_query('SELECT * FROM {files} WHERE nid = %d', $node->nid);
  548. while ($file = db_fetch_object($result)) {
  549. $files[$file->fid] = $file;
  550. }
  551. foreach ($files as $fid => $file) {
  552. // Delete all file revision information associated with the node
  553. db_query('DELETE FROM {file_revisions} WHERE fid = %d', $fid);
  554. file_delete($file->filepath);
  555. }
  556. // Delete all files associated with the node
  557. db_query('DELETE FROM {files} WHERE nid = %d', $node->nid);
  558. }
  559. function upload_delete_revision($node) {
  560. if (is_array($node->files)) {
  561. foreach ($node->files as $file) {
  562. // Check if the file will be used after this revision is deleted
  563. $count = db_result(db_query('SELECT COUNT(fid) FROM {file_revisions} WHERE fid = %d', $file->fid));
  564. // if the file won't be used, delete it
  565. if ($count < 2) {
  566. db_query('DELETE FROM {files} WHERE fid = %d', $file->fid);
  567. file_delete($file->filepath);
  568. }
  569. }
  570. }
  571. // delete the revision
  572. db_query('DELETE FROM {file_revisions} WHERE vid = %d', $node->vid);
  573. }
  574. function _upload_form($node) {
  575. $form['#theme'] = 'upload_form_new';
  576. if (is_array($node->files) && count($node->files)) {
  577. $form['files']['#theme'] = 'upload_form_current';
  578. $form['files']['#tree'] = TRUE;
  579. foreach ($node->files as $key => $file) {
  580. $description = file_create_url((strpos($file->fid, 'upload') === false ? $file->filepath : file_create_filename($file->filename, file_create_path())));
  581. $description = "<small>". check_plain($description) ."</small>";
  582. $form['files'][$key]['description'] = array('#type' => 'textfield', '#default_value' => (strlen($file->description)) ? $file->description : $file->filename, '#maxlength' => 256, '#description' => $description );
  583. $form['files'][$key]['size'] = array('#type' => 'markup', '#value' => format_size($file->filesize));
  584. $form['files'][$key]['remove'] = array('#type' => 'checkbox', '#default_value' => $file->remove);
  585. $form['files'][$key]['list'] = array('#type' => 'checkbox', '#default_value' => $file->list);
  586. // if the file was uploaded this page request, set value. this fixes the problem
  587. // formapi has recognizing new checkboxes. see comments in _upload_prepare.
  588. if ($_SESSION['file_current_upload'] == $file->fid) {
  589. $form['files'][$key]['list']['#value'] = variable_get('upload_list_default',1);
  590. }
  591. $form['files'][$key]['filename'] = array('#type' => 'value', '#value' => $file->filename);
  592. $form['files'][$key]['filepath'] = array('#type' => 'value', '#value' => $file->filepath);
  593. $form['files'][$key]['filemime'] = array('#type' => 'value', '#value' => $file->filemime);
  594. $form['files'][$key]['filesize'] = array('#type' => 'value', '#value' => $file->filesize);
  595. $form['files'][$key]['fid'] = array('#type' => 'value', '#value' => $file->fid);
  596. }
  597. }
  598. if (user_access('upload files')) {
  599. // This div is hidden when the user uploads through JS.
  600. $form['new'] = array(
  601. '#prefix' => '<div id="attach-hide">',
  602. '#suffix' => '</div>',
  603. );
  604. $form['new']['upload'] = array('#type' => 'file', '#title' => t('Attach new file'), '#size' => 40);
  605. $form['new']['attach'] = array('#type' => 'button', '#value' => t('Attach'), '#name'=> 'attach', '#attributes' => array('id' => 'attach'));
  606. // The class triggers the js upload behaviour.
  607. $form['attach'] = array('#type' => 'hidden', '#value' => url('upload/js', NULL, NULL, TRUE), '#attributes' => array('class' => 'upload'));
  608. }
  609. // Needed for JS
  610. $form['current']['vid'] = array('#type' => 'hidden', '#value' => $node->vid);
  611. return $form;
  612. }
  613. /**
  614. * Theme the attachments list.
  615. */
  616. function theme_upload_form_current(&$form) {
  617. $header = array(t('Delete'), t('List'), t('Description'), t('Size'));
  618. foreach (element_children($form) as $key) {
  619. $row = array();
  620. $row[] = form_render($form[$key]['remove']);
  621. $row[] = form_render($form[$key]['list']);
  622. $row[] = form_render($form[$key]['description']);
  623. $row[] = form_render($form[$key]['size']);
  624. $rows[] = $row;
  625. }
  626. $output = theme('table', $header, $rows);
  627. $output .= form_render($form);
  628. return $output;
  629. }
  630. /**
  631. * Theme the attachment form.
  632. * Note: required to output prefix/suffix.
  633. */
  634. function theme_upload_form_new($form) {
  635. $output = form_render($form);
  636. return $output;
  637. }
  638. function upload_load($node) {
  639. $files = array();
  640. if ($node->vid) {
  641. $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);
  642. while ($file = db_fetch_object($result)) {
  643. $files[$file->fid] = $file;
  644. }
  645. }
  646. return $files;
  647. }
  648. /**
  649. * Check an upload, if it is an image, make sure it fits within the
  650. * maximum dimensions allowed.
  651. */
  652. function _upload_image($file) {
  653. $info = image_get_info($file->filepath);
  654. if ($info) {
  655. list($width, $height) = explode('x', variable_get('upload_max_resolution', 0));
  656. if ($width && $height) {
  657. $result = image_scale($file->filepath, $file->filepath, $width, $height);
  658. if ($result) {
  659. $file->filesize = filesize($file->filepath);
  660. 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)))));
  661. }
  662. }
  663. }
  664. return $file;
  665. }
  666. /**
  667. * Menu-callback for JavaScript-based uploads.
  668. */
  669. function upload_js() {
  670. // We only do the upload.module part of the node validation process.
  671. $node = (object)$_POST['edit'];
  672. // Load existing node files.
  673. $node->files = upload_load($node);
  674. // Handle new uploads, and merge tmp files into node-files.
  675. _upload_prepare($node);
  676. _upload_validate($node);
  677. $form = _upload_form($node);
  678. foreach (module_implements('form_alter') as $module) {
  679. $function = $module .'_form_alter';
  680. $function('upload_js', $form);
  681. }
  682. $form = form_builder('upload_js', $form);
  683. $output = theme('status_messages') . form_render($form);
  684. // We send the updated file attachments form.
  685. print drupal_to_js(array('status' => TRUE, 'data' => $output));
  686. exit;
  687. }
Login or register to post comments