file.inc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. <?php
  2. /**
  3. * @file
  4. * Webform module file component.
  5. */
  6. /**
  7. * Implements _webform_defaults_component().
  8. */
  9. function _webform_defaults_file() {
  10. // If private file storage is enabled, make it the default for security
  11. // reasons. See: https://www.drupal.org/psa-2016-003
  12. $available_schemes = file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE);
  13. $scheme = isset($available_schemes['private']) ? 'private' : 'public';
  14. return array(
  15. 'name' => '',
  16. 'form_key' => NULL,
  17. 'required' => 0,
  18. 'pid' => 0,
  19. 'weight' => 0,
  20. 'extra' => array(
  21. 'filtering' => array(
  22. 'types' => array('gif', 'jpg', 'png'),
  23. 'addextensions' => '',
  24. 'size' => '2 MB',
  25. ),
  26. 'rename' => '',
  27. 'scheme' => $scheme,
  28. 'directory' => '',
  29. 'progress_indicator' => 'throbber',
  30. 'title_display' => 0,
  31. 'description' => '',
  32. 'description_above' => FALSE,
  33. 'attributes' => array(),
  34. 'private' => FALSE,
  35. 'analysis' => FALSE,
  36. ),
  37. );
  38. }
  39. /**
  40. * Implements _webform_theme_component().
  41. */
  42. function _webform_theme_file() {
  43. return array(
  44. 'webform_edit_file_extensions' => array(
  45. 'render element' => 'element',
  46. 'file' => 'components/file.inc',
  47. ),
  48. 'webform_display_file' => array(
  49. 'render element' => 'element',
  50. 'file' => 'components/file.inc',
  51. ),
  52. 'webform_managed_file' => array(
  53. 'render element' => 'element',
  54. 'file' => 'components/file.inc',
  55. ),
  56. );
  57. }
  58. /**
  59. * Implements _webform_edit_component().
  60. */
  61. function _webform_edit_file($component) {
  62. $form = array();
  63. $form['#element_validate'] = array('_webform_edit_file_check_directory');
  64. $form['#after_build'] = array('_webform_edit_file_check_directory');
  65. $form['validation']['size'] = array(
  66. '#type' => 'textfield',
  67. '#title' => t('Max upload size'),
  68. '#default_value' => $component['extra']['filtering']['size'],
  69. '#description' => t('Enter the max file size a user may upload such as 2 MB or 800 KB. Your server has a max upload size of @size.', array('@size' => format_size(file_upload_max_size()))),
  70. '#size' => 10,
  71. '#parents' => array('extra', 'filtering', 'size'),
  72. '#element_validate' => array('_webform_edit_file_size_validate'),
  73. '#weight' => 1,
  74. );
  75. $form['validation']['extensions'] = array(
  76. '#element_validate' => array('_webform_edit_file_extensions_validate'),
  77. '#parents' => array('extra', 'filtering'),
  78. '#theme' => 'webform_edit_file_extensions',
  79. '#theme_wrappers' => array('form_element'),
  80. '#title' => t('Allowed file extensions'),
  81. '#attached' => array(
  82. 'js' => array(drupal_get_path('module', 'webform') . '/js/webform-admin.js'),
  83. 'css' => array(drupal_get_path('module', 'webform') . '/css/webform-admin.css'),
  84. ),
  85. '#type' => 'webform_file_extensions',
  86. '#weight' => 2,
  87. );
  88. // Find the list of all currently valid extensions.
  89. $current_types = isset($component['extra']['filtering']['types']) ? $component['extra']['filtering']['types'] : array();
  90. $types = array('gif', 'jpg', 'png');
  91. $form['validation']['extensions']['types']['webimages'] = array(
  92. '#type' => 'checkboxes',
  93. '#title' => t('Web images'),
  94. '#options' => drupal_map_assoc($types),
  95. '#default_value' => array_intersect($current_types, $types),
  96. );
  97. $types = array('bmp', 'eps', 'tif', 'pict', 'psd');
  98. $form['validation']['extensions']['types']['desktopimages'] = array(
  99. '#type' => 'checkboxes',
  100. '#title' => t('Desktop images'),
  101. '#options' => drupal_map_assoc($types),
  102. '#default_value' => array_intersect($current_types, $types),
  103. );
  104. $types = array('txt', 'rtf', 'html', 'pdf', 'doc', 'docx', 'odt', 'ppt', 'pptx', 'odp', 'xls', 'xlsx', 'ods', 'xml');
  105. $form['validation']['extensions']['types']['documents'] = array(
  106. '#type' => 'checkboxes',
  107. '#title' => t('Documents'),
  108. '#options' => drupal_map_assoc($types),
  109. '#default_value' => array_intersect($current_types, $types),
  110. );
  111. $types = array('avi', 'mov', 'mp3', 'ogg', 'wav');
  112. $form['validation']['extensions']['types']['media'] = array(
  113. '#type' => 'checkboxes',
  114. '#title' => t('Media'),
  115. '#options' => drupal_map_assoc($types),
  116. '#default_value' => array_intersect($current_types, $types),
  117. );
  118. $types = array('bz2', 'dmg', 'gz', 'jar', 'rar', 'sit', 'tar', 'zip');
  119. $form['validation']['extensions']['types']['archives'] = array(
  120. '#type' => 'checkboxes',
  121. '#title' => t('Archives'),
  122. '#options' => drupal_map_assoc($types),
  123. '#default_value' => array_intersect($current_types, $types),
  124. );
  125. $form['validation']['extensions']['addextensions'] = array(
  126. '#type' => 'textfield',
  127. '#title' => t('Additional extensions'),
  128. '#default_value' => $component['extra']['filtering']['addextensions'],
  129. '#description' => t('Enter a list of additional file extensions for this upload field, separated by commas.<br /> Entered extensions will be appended to checked items above.'),
  130. '#size' => 20,
  131. '#weight' => 3,
  132. );
  133. $scheme_options = array();
  134. foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $stream_wrapper) {
  135. $scheme_options[$scheme] = $stream_wrapper['name'];
  136. }
  137. $form['extra']['scheme'] = array(
  138. '#type' => 'radios',
  139. '#title' => t('Upload destination'),
  140. '#options' => $scheme_options,
  141. '#default_value' => $component['extra']['scheme'],
  142. '#description' => t('Public files upload destination is dangerous for forms that are available to anonymous and/or untrusted users. For more information, see <a href="@psa">DRUPAL-PSA-2016-003</a>.', array('@psa' => 'https://www.drupal.org/psa-2016-003')),
  143. '#weight' => 4,
  144. '#access' => count($scheme_options) > 1,
  145. );
  146. $form['extra']['directory'] = array(
  147. '#type' => 'textfield',
  148. '#title' => t('Upload directory'),
  149. '#default_value' => $component['extra']['directory'],
  150. '#description' => t('You may optionally specify a sub-directory to store your files.') . ' ' . theme('webform_token_help'),
  151. '#weight' => 5,
  152. '#field_prefix' => 'webform/',
  153. );
  154. $form['extra']['rename'] = array(
  155. '#type' => 'textfield',
  156. '#title' => t('Rename files'),
  157. '#default_value' => $component['extra']['rename'],
  158. '#description' => t('You may optionally use tokens to create a pattern used to rename files upon submission. Omit the extension; it will be added automatically.') . ' ' . theme('webform_token_help', array('groups' => array('node', 'submission'))),
  159. '#weight' => 6,
  160. '#element_validate' => array('_webform_edit_file_rename_validate'),
  161. '#access' => webform_variable_get('webform_token_access'),
  162. );
  163. $form['display']['progress_indicator'] = array(
  164. '#type' => 'radios',
  165. '#title' => t('Progress indicator'),
  166. '#options' => array(
  167. 'throbber' => t('Throbber'),
  168. 'bar' => t('Bar with progress meter'),
  169. ),
  170. '#default_value' => $component['extra']['progress_indicator'],
  171. '#description' => t('The throbber display does not show the status of uploads but takes up less space. The progress bar is helpful for monitoring progress on large uploads.'),
  172. '#weight' => 16,
  173. '#access' => file_progress_implementation(),
  174. '#parents' => array('extra', 'progress_indicator'),
  175. );
  176. return $form;
  177. }
  178. /**
  179. * Form API validator ensures rename string is empty or contains one token.
  180. *
  181. * A Form API element validate function to ensure that the rename string is
  182. * either empty or contains at least one token.
  183. */
  184. function _webform_edit_file_rename_validate($element, &$form_state, $form) {
  185. $rename = trim($form_state['values']['extra']['rename']);
  186. form_set_value($element, $rename, $form_state);
  187. if (strlen($rename) && !count(token_scan($rename))) {
  188. form_error($element, t('To create unique file names, use at least one token in the file name pattern.'));
  189. }
  190. }
  191. /**
  192. * A Form API element validate function to check filesize is valid.
  193. */
  194. function _webform_edit_file_size_validate($element) {
  195. if (!empty($element['#value'])) {
  196. $set_filesize = parse_size($element['#value']);
  197. if ($set_filesize == FALSE) {
  198. form_error($element, t('File size @value is not a valid file size. Use a value such as 2 MB or 800 KB.', array('@value' => $element['#value'])));
  199. }
  200. else {
  201. $max_filesize = parse_size(file_upload_max_size());
  202. if ($max_filesize < $set_filesize) {
  203. form_error($element, t('An upload size of @value is too large. You are allowed to upload files that are @max or less.', array('@value' => $element['#value'], '@max' => format_size($max_filesize))));
  204. }
  205. }
  206. }
  207. }
  208. /**
  209. * A Form API after build and validate function.
  210. *
  211. * Ensure that the destination directory exists and is writable.
  212. */
  213. function _webform_edit_file_check_directory($element) {
  214. $scheme = $element['extra']['scheme']['#value'];
  215. $directory = $element['extra']['directory']['#value'];
  216. $destination_dir = file_stream_wrapper_uri_normalize($scheme . '://webform/' . $directory);
  217. $tokenized_dir = drupal_strtolower(webform_replace_tokens($destination_dir, $element['#node']));
  218. // Sanity check input to prevent use parent (../) directories.
  219. if (preg_match('/\.\.[\/\\\]/', $tokenized_dir . '/')) {
  220. form_error($element['extra']['directory'], t('The save directory %directory is not valid.', array('%directory' => $tokenized_dir)));
  221. }
  222. else {
  223. if (!file_prepare_directory($tokenized_dir, FILE_CREATE_DIRECTORY)) {
  224. form_error($element['extra']['directory'], t('The save directory %directory could not be created. Check that the webform files directory is writable.', array('%directory' => $tokenized_dir)));
  225. }
  226. }
  227. return $element;
  228. }
  229. /**
  230. * A Form API element validate function.
  231. *
  232. * Change the submitted values of the component so that all filtering extensions
  233. * are saved as a single array.
  234. */
  235. function _webform_edit_file_extensions_validate($element, &$form_state) {
  236. // Predefined types.
  237. $extensions = array();
  238. foreach (element_children($element['types']) as $category) {
  239. foreach (array_keys($element['types'][$category]['#value']) as $extension) {
  240. if ($element['types'][$category][$extension]['#value']) {
  241. $extensions[] = $extension;
  242. // "jpeg" is an exception. It is allowed anytime "jpg" is allowed.
  243. if ($extension == 'jpg') {
  244. $extensions[] = 'jpeg';
  245. }
  246. }
  247. }
  248. }
  249. // Additional types.
  250. $additional_extensions = explode(',', $element['addextensions']['#value']);
  251. foreach ($additional_extensions as $extension) {
  252. $clean_extension = drupal_strtolower(trim($extension));
  253. if (!empty($clean_extension) && !in_array($clean_extension, $extensions)) {
  254. $extensions[] = $clean_extension;
  255. }
  256. }
  257. form_set_value($element['types'], $extensions, $form_state);
  258. }
  259. /**
  260. * Output the list of allowed extensions as checkboxes.
  261. */
  262. function theme_webform_edit_file_extensions($variables) {
  263. $element = $variables['element'];
  264. // Format the components into a table.
  265. $rows = array();
  266. foreach (element_children($element['types']) as $filtergroup) {
  267. $row = array();
  268. if ($element['types'][$filtergroup]['#type'] == 'checkboxes') {
  269. $select_link = ' <a href="#" class="webform-select-link webform-select-link-' . $filtergroup . '">(' . t('select') . ')</a>';
  270. $row[] = $element['types'][$filtergroup]['#title'];
  271. $row[] = array('data' => $select_link, 'width' => 40);
  272. $row[] = array('data' => drupal_render_children($element['types'][$filtergroup]), 'class' => array('webform-file-extensions', 'webform-select-group-' . $filtergroup));
  273. $rows[] = array('data' => $row);
  274. unset($element['types'][$filtergroup]);
  275. }
  276. }
  277. // Add the row for additional types.
  278. if (!isset($element['addextensions']['#access']) || $element['addextensions']['#access']) {
  279. $row = array();
  280. $title = $element['addextensions']['#title'];
  281. $element['addextensions']['#title'] = NULL;
  282. $row[] = array('data' => $title, 'colspan' => 2);
  283. $row[] = drupal_render($element['addextensions']);
  284. $rows[] = $row;
  285. }
  286. $header = array(array('data' => t('Category'), 'colspan' => '2'), array('data' => t('Types')));
  287. // Create the table inside the form.
  288. $element['types']['table'] = array(
  289. '#theme' => 'table',
  290. '#header' => $header,
  291. '#rows' => $rows,
  292. '#attributes' => array('class' => array('webform-file-extensions')),
  293. );
  294. return drupal_render_children($element);
  295. }
  296. /**
  297. * Implements _webform_render_component().
  298. */
  299. function _webform_render_file($component, $value = NULL, $filter = TRUE, $submission = NULL) {
  300. $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
  301. // Cap the upload size according to the PHP limit.
  302. $max_filesize = parse_size(file_upload_max_size());
  303. $set_filesize = $component['extra']['filtering']['size'];
  304. if (!empty($set_filesize) && parse_size($set_filesize) < $max_filesize) {
  305. $max_filesize = parse_size($set_filesize);
  306. }
  307. $element = array(
  308. '#type' => 'managed_file',
  309. '#theme' => 'webform_managed_file',
  310. '#title' => $filter ? webform_filter_xss($component['name']) : $component['name'],
  311. '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
  312. '#required' => $component['required'],
  313. '#default_value' => isset($value[0]) ? $value[0] : NULL,
  314. '#attributes' => $component['extra']['attributes'],
  315. '#upload_validators' => array(
  316. 'file_validate_size' => array($max_filesize),
  317. 'file_validate_extensions' => array(implode(' ', $component['extra']['filtering']['types'])),
  318. ),
  319. '#pre_render' => array_merge(element_info_property('managed_file', '#pre_render'), array('webform_file_allow_access')),
  320. '#upload_location' => $component['extra']['scheme'] . '://webform/' . ($filter
  321. ? drupal_strtolower(webform_replace_tokens($component['extra']['directory'], $node))
  322. : $component['extra']['directory']),
  323. '#progress_indicator' => $component['extra']['progress_indicator'],
  324. '#description' => $filter ? webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
  325. '#weight' => $component['weight'],
  326. '#theme_wrappers' => array('webform_element'),
  327. '#translatable' => array('title', 'description'),
  328. );
  329. if ($filter) {
  330. $element['#description'] = theme('file_upload_help', array('description' => $element['#description'], 'upload_validators' => $element['#upload_validators']));
  331. }
  332. return $element;
  333. }
  334. /**
  335. * Returns HTML for a webform managed file element.
  336. *
  337. * See #2495821 and #2497909. The core theme_file_managed_file creates a
  338. * wrapper around the element with the element's id, thereby creating 2 elements
  339. * with the same id.
  340. *
  341. * @param array $variables
  342. * An associative array containing:
  343. * - element: A render element representing the file.
  344. *
  345. * @return string
  346. * The HTML.
  347. */
  348. function theme_webform_managed_file($variables) {
  349. $element = $variables['element'];
  350. $attributes = array();
  351. // For webform use, do not add the id to the wrapper.
  352. // @code
  353. // if (isset($element['#id'])) {
  354. // $attributes['id'] = $element['#id'];
  355. // }
  356. // @endcode
  357. if (!empty($element['#attributes']['class'])) {
  358. $attributes['class'] = (array) $element['#attributes']['class'];
  359. }
  360. $attributes['class'][] = 'form-managed-file';
  361. // This wrapper is required to apply JS behaviors and CSS styling.
  362. $output = '';
  363. $output .= '<div' . drupal_attributes($attributes) . '>';
  364. $output .= drupal_render_children($element);
  365. $output .= '</div>';
  366. return $output;
  367. }
  368. /**
  369. * Implements _webform_submit_component().
  370. */
  371. function _webform_submit_file($component, $value) {
  372. $fid = is_array($value)
  373. ? (!empty($value['fid']) ? $value['fid'] : '')
  374. : (!empty($value) ? $value : '');
  375. // Extend access to this file, even if the submission has not been saved yet.
  376. // This may happen when previewing a private file which was selected but not
  377. // explicitly uploaded, and then previewed.
  378. if ($fid) {
  379. $_SESSION['webform_files'][$fid] = $fid;
  380. }
  381. return $fid;
  382. }
  383. /**
  384. * Pre-render callback to allow access to uploaded files.
  385. *
  386. * Files that have not yet been saved into a submission must be accessible to
  387. * the user who uploaded it, but no one else. After the submission is saved,
  388. * access is granted through the file_usage table. Before then, we use a
  389. * $_SESSION value to record a user's upload.
  390. *
  391. * @see webform_file_download()
  392. */
  393. function webform_file_allow_access($element) {
  394. if (!empty($element['#value']['fid'])) {
  395. $fid = $element['#value']['fid'];
  396. $_SESSION['webform_files'][$fid] = $fid;
  397. }
  398. return $element;
  399. }
  400. /**
  401. * Implements _webform_display_component().
  402. */
  403. function _webform_display_file($component, $value, $format = 'html', $submission = array()) {
  404. $fid = isset($value[0]) ? $value[0] : NULL;
  405. return array(
  406. '#title' => $component['name'],
  407. '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
  408. '#value' => $fid ? webform_get_file($fid) : NULL,
  409. '#weight' => $component['weight'],
  410. '#theme' => 'webform_display_file',
  411. '#theme_wrappers' => $format == 'text' ? array('webform_element_text') : array('webform_element'),
  412. '#format' => $format,
  413. '#translatable' => array('title'),
  414. );
  415. }
  416. /**
  417. * Format the output of text data for this component.
  418. */
  419. function theme_webform_display_file($variables) {
  420. $element = $variables['element'];
  421. $file = $element['#value'];
  422. $url = !empty($file) ? webform_file_url($file->uri) : t('no upload');
  423. return !empty($file) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url)) : ' ';
  424. }
  425. /**
  426. * Implements _webform_delete_component().
  427. */
  428. function _webform_delete_file($component, $value) {
  429. // Delete an individual submission file.
  430. if (!empty($value[0]) && ($file = webform_get_file($value[0]))) {
  431. file_usage_delete($file, 'webform');
  432. file_delete($file);
  433. }
  434. }
  435. /**
  436. * Implements _webform_attachments_component().
  437. */
  438. function _webform_attachments_file($component, $value) {
  439. $file = (array) webform_get_file($value[0]);
  440. $files = array($file);
  441. return $files;
  442. }
  443. /**
  444. * Implements _webform_analysis_component().
  445. */
  446. function _webform_analysis_file($component, $sids = array(), $single = FALSE, $join = NULL) {
  447. $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
  448. ->fields('wsd', array('no', 'data'))
  449. ->condition('wsd.nid', $component['nid'])
  450. ->condition('wsd.cid', $component['cid']);
  451. if (count($sids)) {
  452. $query->condition('wsd.sid', $sids, 'IN');
  453. }
  454. if ($join) {
  455. $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
  456. }
  457. $nonblanks = 0;
  458. $sizetotal = 0;
  459. $submissions = 0;
  460. $result = $query->execute();
  461. foreach ($result as $data) {
  462. $file = webform_get_file($data['data']);
  463. if (isset($file->filesize)) {
  464. $nonblanks++;
  465. $sizetotal += $file->filesize;
  466. }
  467. $submissions++;
  468. }
  469. $rows[0] = array(t('Left Blank'), ($submissions - $nonblanks));
  470. $rows[1] = array(t('User uploaded file'), $nonblanks);
  471. $other[0] = array(t('Average uploaded file size'), ($sizetotal != 0 ? (int) (($sizetotal / $nonblanks) / 1024) . ' KB' : '0'));
  472. return array(
  473. 'table_rows' => $rows,
  474. 'other_data' => $other,
  475. );
  476. }
  477. /**
  478. * Implements _webform_table_component().
  479. */
  480. function _webform_table_file($component, $value) {
  481. $output = '';
  482. $file = webform_get_file($value[0]);
  483. if (!empty($file->fid)) {
  484. $output = '<a href="' . webform_file_url($file->uri) . '">' . check_plain(webform_file_name($file->uri)) . '</a>';
  485. $output .= ' (' . (int) ($file->filesize / 1024) . ' KB)';
  486. }
  487. return $output;
  488. }
  489. /**
  490. * Implements _webform_csv_headers_component().
  491. */
  492. function _webform_csv_headers_file($component, $export_options) {
  493. $header = array();
  494. // Two columns in header.
  495. $header[0] = array('', '');
  496. $header[1] = array($export_options['header_keys'] ? $component['form_key'] : $component['name'], '');
  497. $header[2] = array(t('Name'), t('Filesize (KB)'));
  498. return $header;
  499. }
  500. /**
  501. * Implements _webform_csv_data_component().
  502. */
  503. function _webform_csv_data_file($component, $export_options, $value) {
  504. $file = webform_get_file($value[0]);
  505. return empty($file->filename) ? array('', '') : array(webform_file_url($file->uri), (int) ($file->filesize / 1024));
  506. }
  507. /**
  508. * Helper function to create proper file names for uploaded file.
  509. */
  510. function webform_file_name($filepath) {
  511. if (!empty($filepath)) {
  512. $info = pathinfo($filepath);
  513. $file_name = $info['basename'];
  514. }
  515. return isset($file_name) ? $file_name : '';
  516. }
  517. /**
  518. * Helper function to create proper URLs for uploaded file.
  519. */
  520. function webform_file_url($uri) {
  521. if (!empty($uri)) {
  522. $file_url = file_create_url($uri);
  523. }
  524. return isset($file_url) ? $file_url : '';
  525. }
  526. /**
  527. * Helper function to load a file from the database.
  528. */
  529. function webform_get_file($fid) {
  530. // Simple check to prevent loading of NULL values, which throws an entity
  531. // system error.
  532. return $fid ? file_load($fid) : FALSE;
  533. }
  534. /**
  535. * Given a submission with file_usage set, add or remove file usage entries.
  536. */
  537. function webform_file_usage_adjust($submission) {
  538. if (isset($submission->file_usage)) {
  539. $files = file_load_multiple($submission->file_usage['added_fids']);
  540. foreach ($files as $file) {
  541. $file->status = 1;
  542. file_save($file);
  543. file_usage_add($file, 'webform', 'submission', $submission->sid);
  544. }
  545. $files = file_load_multiple($submission->file_usage['deleted_fids']);
  546. foreach ($files as $file) {
  547. file_usage_delete($file, 'webform', 'submission', $submission->sid);
  548. file_delete($file);
  549. }
  550. }
  551. }
  552. /**
  553. * Rename any files which are eligible for renaming.
  554. *
  555. * Renames if this submission is being submitted for the first time.
  556. */
  557. function webform_file_rename($node, $submission) {
  558. if (isset($submission->file_usage)) {
  559. foreach ($submission->file_usage['renameable'] as $cid => $fids) {
  560. foreach ($fids as $fid) {
  561. webform_file_process_rename($node, $submission, $node->webform['components'][$cid], $fid);
  562. }
  563. }
  564. }
  565. }
  566. /**
  567. * Renames the uploaded file name using tokens.
  568. *
  569. * @param object $node
  570. * The webform node object.
  571. * @param object $submission
  572. * The webform submission object.
  573. * @param array $component
  574. * Component settings array for which fid is going to be processed.
  575. * @param int $fid
  576. * A file id to be processed.
  577. */
  578. function webform_file_process_rename($node, $submission, $component, $fid) {
  579. $file = webform_get_file($fid);
  580. if ($file) {
  581. // Get the destination uri.
  582. $destination_dir = $component['extra']['scheme'] . '://webform/' . drupal_strtolower(webform_replace_tokens($component['extra']['directory'], $node));
  583. $destination_dir = file_stream_wrapper_uri_normalize($destination_dir);
  584. // Get the file extension.
  585. $info = pathinfo($file->uri);
  586. $extension = $info['extension'];
  587. // Prepare new file name without extension.
  588. $new_file_name = webform_replace_tokens($component['extra']['rename'], $node, $submission, NULL, TRUE);
  589. $new_file_name = trim($new_file_name);
  590. $new_file_name = _webform_transliterate($new_file_name);
  591. $new_file_name = str_replace('/', '_', $new_file_name);
  592. $new_file_name = preg_replace('/[^a-zA-Z0-9_\- ]/', '', $new_file_name);
  593. if (strlen($new_file_name)) {
  594. // Prepare the new uri with new filename.
  595. $destination = "$destination_dir/$new_file_name.$extension";
  596. // Compare the uri and Rename the file name.
  597. if ($file->uri != $destination) {
  598. file_move($file, $destination, FILE_EXISTS_RENAME);
  599. }
  600. }
  601. }
  602. }