file.inc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. <?php
  2. /**
  3. * @file
  4. * Webform module file component.
  5. */
  6. /**
  7. * Implements _webform_defaults_component().
  8. */
  9. function _webform_defaults_file() {
  10. return array(
  11. 'name' => '',
  12. 'form_key' => NULL,
  13. 'mandatory' => 0,
  14. 'pid' => 0,
  15. 'weight' => 0,
  16. 'extra' => array(
  17. 'filtering' => array(
  18. 'types' => array('gif', 'jpg', 'png'),
  19. 'addextensions' => '',
  20. 'size' => '2 MB',
  21. ),
  22. 'scheme' => 'public',
  23. 'directory' => '',
  24. 'progress_indicator' => 'throbber',
  25. 'title_display' => 0,
  26. 'description' => '',
  27. 'attributes' => array(),
  28. 'private' => FALSE,
  29. ),
  30. );
  31. }
  32. /**
  33. * Implements _webform_theme_component().
  34. */
  35. function _webform_theme_file() {
  36. return array(
  37. 'webform_edit_file_extensions' => array(
  38. 'render element' => 'element',
  39. 'file' => 'components/file.inc',
  40. ),
  41. 'webform_display_file' => array(
  42. 'render element' => 'element',
  43. 'file' => 'components/file.inc',
  44. ),
  45. );
  46. }
  47. /**
  48. * Implements _webform_edit_component().
  49. */
  50. function _webform_edit_file($component) {
  51. $form = array();
  52. $form['#element_validate'] = array('_webform_edit_file_check_directory');
  53. $form['#after_build'] = array('_webform_edit_file_check_directory');
  54. $form['validation']['size'] = array(
  55. '#type' => 'textfield',
  56. '#title' => t('Max upload size'),
  57. '#default_value' => $component['extra']['filtering']['size'],
  58. '#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()))),
  59. '#size' => 10,
  60. '#parents' => array('extra', 'filtering', 'size'),
  61. '#element_validate' => array('_webform_edit_file_size_validate'),
  62. '#weight' => 1,
  63. );
  64. $form['validation']['extensions'] = array(
  65. '#element_validate' => array('_webform_edit_file_extensions_validate'),
  66. '#parents' => array('extra', 'filtering'),
  67. '#theme' => 'webform_edit_file_extensions',
  68. '#theme_wrappers' => array('form_element'),
  69. '#title' => t('Allowed file extensions'),
  70. '#attached' => array(
  71. 'js' => array(drupal_get_path('module', 'webform') . '/js/webform-admin.js'),
  72. 'css' => array(drupal_get_path('module', 'webform') . '/css/webform-admin.css'),
  73. ),
  74. '#weight' => 2,
  75. );
  76. // Find the list of all currently valid extensions.
  77. $current_types = isset($component['extra']['filtering']['types']) ? $component['extra']['filtering']['types'] : array();
  78. $types = array('gif', 'jpg', 'png');
  79. $form['validation']['extensions']['types']['webimages'] = array(
  80. '#type' => 'checkboxes',
  81. '#title' => t('Web images'),
  82. '#options' => drupal_map_assoc($types),
  83. '#default_value' => array_intersect($current_types, $types),
  84. );
  85. $types = array('bmp', 'eps', 'tif', 'pict', 'psd');
  86. $form['validation']['extensions']['types']['desktopimages'] = array(
  87. '#type' => 'checkboxes',
  88. '#title' => t('Desktop images'),
  89. '#options' => drupal_map_assoc($types),
  90. '#default_value' => array_intersect($current_types, $types),
  91. );
  92. $types = array('txt', 'rtf', 'html', 'odf', 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'xml');
  93. $form['validation']['extensions']['types']['documents'] = array(
  94. '#type' => 'checkboxes',
  95. '#title' => t('Documents'),
  96. '#options' => drupal_map_assoc($types),
  97. '#default_value' => array_intersect($current_types, $types),
  98. );
  99. $types = array('avi', 'mov', 'mp3', 'ogg', 'wav');
  100. $form['validation']['extensions']['types']['media'] = array(
  101. '#type' => 'checkboxes',
  102. '#title' => t('Media'),
  103. '#options' => drupal_map_assoc($types),
  104. '#default_value' => array_intersect($current_types, $types),
  105. );
  106. $types = array('bz2', 'dmg', 'gz', 'jar', 'rar', 'sit', 'tar', 'zip');
  107. $form['validation']['extensions']['types']['archives'] = array(
  108. '#type' => 'checkboxes',
  109. '#title' => t('Archives'),
  110. '#options' => drupal_map_assoc($types),
  111. '#default_value' => array_intersect($current_types, $types),
  112. );
  113. $form['validation']['extensions']['addextensions'] = array(
  114. '#type' => 'textfield',
  115. '#title' => t('Additional extensions'),
  116. '#default_value' => $component['extra']['filtering']['addextensions'],
  117. '#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.'),
  118. '#size' => 20,
  119. '#weight' => 3,
  120. );
  121. $scheme_options = array();
  122. foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $stream_wrapper) {
  123. $scheme_options[$scheme] = $stream_wrapper['name'];
  124. }
  125. $form['extra']['scheme'] = array(
  126. '#type' => 'radios',
  127. '#title' => t('Upload destination'),
  128. '#options' => $scheme_options,
  129. '#default_value' => $component['extra']['scheme'],
  130. '#description' => t('Private file storage has significantly more overhead than public files, but restricts file access to users who can view submissions.'),
  131. '#weight' => 4,
  132. '#access' => count($scheme_options) > 1,
  133. );
  134. $form['extra']['directory'] = array(
  135. '#type' => 'textfield',
  136. '#title' => t('Upload directory'),
  137. '#default_value' => $component['extra']['directory'],
  138. '#description' => t('You may optionally specify a sub-directory to store your files.'),
  139. '#weight' => 5,
  140. '#field_prefix' => 'webform/',
  141. );
  142. $form['display']['progress_indicator'] = array(
  143. '#type' => 'radios',
  144. '#title' => t('Progress indicator'),
  145. '#options' => array(
  146. 'throbber' => t('Throbber'),
  147. 'bar' => t('Bar with progress meter'),
  148. ),
  149. '#default_value' => $component['extra']['progress_indicator'],
  150. '#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.'),
  151. '#weight' => 16,
  152. '#access' => file_progress_implementation(),
  153. '#parents' => array('extra', 'progress_indicator'),
  154. );
  155. // TODO: Make managed_file respect the "size" parameter.
  156. /*
  157. $form['display']['width'] = array(
  158. '#type' => 'textfield',
  159. '#title' => t('Width'),
  160. '#default_value' => $component['extra']['width'],
  161. '#description' => t('Width of the file field.') . ' ' . t('Leaving blank will use the default size.'),
  162. '#size' => 5,
  163. '#maxlength' => 10,
  164. '#weight' => 4,
  165. '#parents' => array('extra', 'width')
  166. );
  167. */
  168. return $form;
  169. }
  170. /**
  171. * A Form API element validate function to check filesize is valid.
  172. */
  173. function _webform_edit_file_size_validate($element) {
  174. if (!empty($element['#value'])) {
  175. $set_filesize = parse_size($element['#value']);
  176. if ($set_filesize == FALSE) {
  177. form_error($element, t('File size @value is not a valid filesize. Use a value such as 2 MB or 800 KB.', array('@value' => $element['#value'])));
  178. }
  179. else {
  180. $max_filesize = parse_size(file_upload_max_size());
  181. if ($max_filesize < $set_filesize) {
  182. form_error($element, t('An upload size of @value is too large, you are allow to upload files @max or less.', array('@value' => $element['#value'], '@max' => format_size($max_filesize))));
  183. }
  184. }
  185. }
  186. }
  187. /**
  188. * A Form API after build and validate function.
  189. *
  190. * Ensure that the destination directory exists and is writable.
  191. */
  192. function _webform_edit_file_check_directory($element) {
  193. $scheme = $element['extra']['scheme']['#value'];
  194. $directory = $element['extra']['directory']['#value'];
  195. $destination_dir = file_stream_wrapper_uri_normalize($scheme . '://webform/' . $directory);
  196. // Sanity check input to prevent use parent (../) directories.
  197. if (preg_match('/\.\.[\/\\\]/', $destination_dir . '/')) {
  198. form_error($element['extra']['directory'], t('The save directory %directory is not valid.', array('%directory' => $directory)));
  199. }
  200. else {
  201. $destination_success = file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
  202. if (!$destination_success) {
  203. form_error($element['extra']['directory'], t('The save directory %directory could not be created. Check that the webform files directory is writable.', array('%directory' => $directory)));
  204. }
  205. }
  206. return $element;
  207. }
  208. /**
  209. * A Form API element validate function.
  210. *
  211. * Change the submitted values of the component so that all filtering extensions
  212. * are saved as a single array.
  213. */
  214. function _webform_edit_file_extensions_validate($element, &$form_state) {
  215. // Predefined types.
  216. $extensions = array();
  217. foreach (element_children($element['types']) as $category) {
  218. foreach (array_keys($element['types'][$category]['#value']) as $extension) {
  219. if ($element['types'][$category][$extension]['#value']) {
  220. $extensions[] = $extension;
  221. }
  222. }
  223. }
  224. // Additional types.
  225. $additional_extensions = explode(',', $element['addextensions']['#value']);
  226. foreach ($additional_extensions as $extension) {
  227. $clean_extension = drupal_strtolower(trim($extension));
  228. if (!empty($clean_extension) && !in_array($clean_extension, $extensions)) {
  229. $extensions[] = $clean_extension;
  230. }
  231. }
  232. form_set_value($element['types'], $extensions, $form_state);
  233. }
  234. /**
  235. * Output the list of allowed extensions as checkboxes.
  236. */
  237. function theme_webform_edit_file_extensions($variables) {
  238. $element = $variables['element'];
  239. // Format the components into a table.
  240. $rows = array();
  241. foreach (element_children($element['types']) as $filtergroup) {
  242. $row = array();
  243. $first_row = count($rows);
  244. if ($element['types'][$filtergroup]['#type'] == 'checkboxes') {
  245. $select_link = ' <a href="#" class="webform-select-link webform-select-link-' . $filtergroup . '">(' . t('select') . ')</a>';
  246. $row[] = $element['types'][$filtergroup]['#title'];
  247. $row[] = array('data' => $select_link, 'width' => 40);
  248. $row[] = array('data' => drupal_render_children($element['types'][$filtergroup]), 'class' => array('webform-file-extensions', 'webform-select-group-' . $filtergroup));
  249. $rows[] = array('data' => $row);
  250. unset($element['types'][$filtergroup]);
  251. }
  252. }
  253. // Add the row for additional types.
  254. $row = array();
  255. $title = $element['addextensions']['#title'];
  256. $element['addextensions']['#title'] = NULL;
  257. $row[] = array('data' => $title, 'colspan' => 2);
  258. $row[] = drupal_render($element['addextensions']);
  259. $rows[] = $row;
  260. $header = array(array('data' => t('Category'), 'colspan' => '2'), array('data' => t('Types')));
  261. // Create the table inside the form.
  262. $element['types']['table'] = array(
  263. '#theme' => 'table',
  264. '#header' => $header,
  265. '#rows' => $rows,
  266. '#attributes' => array('class' => array('webform-file-extensions')),
  267. );
  268. return drupal_render_children($element);
  269. }
  270. /**
  271. * Implements _webform_render_component().
  272. */
  273. function _webform_render_file($component, $value = NULL, $filter = TRUE) {
  274. $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
  275. // Cap the upload size according to the PHP limit.
  276. $max_filesize = parse_size(file_upload_max_size());
  277. $set_filesize = $component['extra']['filtering']['size'];
  278. if (!empty($set_filesize) && parse_size($set_filesize) < $max_filesize) {
  279. $max_filesize = parse_size($set_filesize);
  280. }
  281. $element = array(
  282. '#type' => 'managed_file',
  283. '#title' => $filter ? _webform_filter_xss($component['name']) : $component['name'],
  284. '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
  285. '#required' => $component['mandatory'],
  286. '#default_value' => isset($value[0]) ? $value[0] : NULL,
  287. '#attributes' => $component['extra']['attributes'],
  288. '#upload_validators' => array(
  289. 'file_validate_size' => array($max_filesize),
  290. 'file_validate_extensions' => array(implode(' ', $component['extra']['filtering']['types'])),
  291. ),
  292. '#pre_render' => array_merge(element_info_property('managed_file', '#pre_render'), array('webform_file_allow_access')),
  293. '#upload_location' => $component['extra']['scheme'] . '://webform/' . $component['extra']['directory'],
  294. '#progress_indicator' => $component['extra']['progress_indicator'],
  295. '#description' => $filter ? _webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
  296. '#weight' => $component['weight'],
  297. '#theme_wrappers' => array('webform_element'),
  298. '#translatable' => array('title', 'description'),
  299. );
  300. return $element;
  301. }
  302. /**
  303. * Implements _webform_submit_component().
  304. */
  305. function _webform_submit_file($component, $value) {
  306. if (is_array($value)) {
  307. return !empty($value['fid']) ? $value['fid'] : '';
  308. }
  309. else {
  310. return !empty($value) ? $value : '';
  311. }
  312. }
  313. /**
  314. * Pre-render callback to allow access to uploaded files.
  315. *
  316. * Files that have not yet been saved into a submission must be accessible to
  317. * the user who uploaded it, but no one else. After the submission is saved,
  318. * access is granted through the file_usage table. Before then, we use a
  319. * $_SESSION value to record a user's upload.
  320. *
  321. * @see webform_file_download()
  322. */
  323. function webform_file_allow_access($element) {
  324. if (!empty($element['#value']['fid'])) {
  325. $fid = $element['#value']['fid'];
  326. $_SESSION['webform_files'][$fid] = $fid;
  327. }
  328. return $element;
  329. }
  330. /**
  331. * Implements _webform_display_component().
  332. */
  333. function _webform_display_file($component, $value, $format = 'html') {
  334. $fid = isset($value[0]) ? $value[0] : NULL;
  335. return array(
  336. '#title' => $component['name'],
  337. '#value' => $fid ? webform_get_file($fid) : NULL,
  338. '#weight' => $component['weight'],
  339. '#theme' => 'webform_display_file',
  340. '#theme_wrappers' => $format == 'text' ? array('webform_element_text') : array('webform_element'),
  341. '#format' => $format,
  342. '#translatable' => array('title'),
  343. );
  344. }
  345. /**
  346. * Format the output of text data for this component
  347. */
  348. function theme_webform_display_file($variables) {
  349. $element = $variables['element'];
  350. $file = $element['#value'];
  351. $url = !empty($file) ? webform_file_url($file->uri) : t('no upload');
  352. return !empty($file) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url)) : ' ';
  353. }
  354. /**
  355. * Implements _webform_delete_component().
  356. */
  357. function _webform_delete_file($component, $value) {
  358. // Delete an individual submission file.
  359. if (!empty($value[0]) && ($file = webform_get_file($value[0]))) {
  360. file_usage_delete($file, 'webform');
  361. file_delete($file);
  362. }
  363. }
  364. /**
  365. * Implements _webform_attachments_component().
  366. */
  367. function _webform_attachments_file($component, $value) {
  368. $file = (array) webform_get_file($value[0]);
  369. //This is necessary until the next release of mimemail is out, see [#1388786]
  370. $file['filepath'] = $file['uri'];
  371. $files = array($file);
  372. return $files;
  373. }
  374. /**
  375. * Implements _webform_analysis_component().
  376. */
  377. function _webform_analysis_file($component, $sids = array()) {
  378. $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
  379. ->fields('wsd', array('no', 'data'))
  380. ->condition('nid', $component['nid'])
  381. ->condition('cid', $component['cid']);
  382. if (count($sids)) {
  383. $query->condition('sid', $sids, 'IN');
  384. }
  385. $nonblanks = 0;
  386. $sizetotal = 0;
  387. $submissions = 0;
  388. $result = $query->execute();
  389. foreach ($result as $data) {
  390. $file = webform_get_file($data['data']);
  391. if (isset($file->filesize)) {
  392. $nonblanks++;
  393. $sizetotal += $file->filesize;
  394. }
  395. $submissions++;
  396. }
  397. $rows[0] = array(t('Left Blank'), ($submissions - $nonblanks));
  398. $rows[1] = array(t('User uploaded file'), $nonblanks);
  399. $rows[2] = array(t('Average uploaded file size'), ($sizetotal != 0 ? (int) (($sizetotal/$nonblanks)/1024) . ' KB' : '0'));
  400. return $rows;
  401. }
  402. /**
  403. * Implements _webform_table_component().
  404. */
  405. function _webform_table_file($component, $value) {
  406. $output = '';
  407. $file = webform_get_file($value[0]);
  408. if (!empty($file->fid)) {
  409. $output = '<a href="' . webform_file_url($file->uri) . '">' . check_plain(webform_file_name($file->uri)) . '</a>';
  410. $output .= ' (' . (int) ($file->filesize/1024) . ' KB)';
  411. }
  412. return $output;
  413. }
  414. /**
  415. * Implements _webform_csv_headers_component().
  416. */
  417. function _webform_csv_headers_file($component, $export_options) {
  418. $header = array();
  419. // Two columns in header.
  420. $header[0] = array('', '');
  421. $header[1] = array($component['name'], '');
  422. $header[2] = array(t('Name'), t('Filesize (KB)'));
  423. return $header;
  424. }
  425. /**
  426. * Implements _webform_csv_data_component().
  427. */
  428. function _webform_csv_data_file($component, $export_options, $value) {
  429. $file = webform_get_file($value[0]);
  430. return empty($file->filename) ? array('', '') : array(webform_file_url($file->uri), (int) ($file->filesize/1024));
  431. }
  432. /**
  433. * Helper function to create proper file names for uploaded file.
  434. */
  435. function webform_file_name($filepath) {
  436. if (!empty($filepath)) {
  437. $info = pathinfo($filepath);
  438. $file_name = $info['basename'];
  439. }
  440. return isset($file_name) ? $file_name : '';
  441. }
  442. /**
  443. * Helper function to create proper URLs for uploaded file.
  444. */
  445. function webform_file_url($uri) {
  446. if (!empty($uri)) {
  447. $file_url = file_create_url($uri);
  448. }
  449. return isset($file_url) ? $file_url : '';
  450. }
  451. /**
  452. * Helper function to load a file from the database.
  453. */
  454. function webform_get_file($fid) {
  455. // Simple check to prevent loading of NULL values, which throws an entity
  456. // system error.
  457. return $fid ? file_load($fid) : FALSE;
  458. }
  459. /**
  460. * Given a submission with file_usage set, add or remove file usage entries.
  461. */
  462. function webform_file_usage_adjust($submission) {
  463. if (isset($submission->file_usage)) {
  464. $files = file_load_multiple($submission->file_usage['added_fids']);
  465. foreach ($files as $file) {
  466. $file->status = 1;
  467. file_save($file);
  468. file_usage_add($file, 'webform', 'submission', $submission->sid);
  469. }
  470. $files = file_load_multiple($submission->file_usage['deleted_fids']);
  471. foreach ($files as $file) {
  472. file_usage_delete($file, 'webform', 'submission', $submission->sid);
  473. file_delete($file);
  474. }
  475. }
  476. }