file.inc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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, seperated 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 . '://' . $directory . '/webform');
  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. * Pre-render callback to allow access to uploaded files.
  304. *
  305. * Files that have not yet been saved into a submission must be accessible to
  306. * the user who uploaded it, but no one else. After the submission is saved,
  307. * access is granted through the file_usage table. Before then, we use a
  308. * $_SESSION value to record a user's upload.
  309. *
  310. * @see webform_file_download()
  311. */
  312. function webform_file_allow_access($element) {
  313. if (!empty($element['#value']['fid'])) {
  314. $fid = $element['#value']['fid'];
  315. $_SESSION['webform_files'][$fid] = $fid;
  316. }
  317. return $element;
  318. }
  319. /**
  320. * Implements _webform_display_component().
  321. */
  322. function _webform_display_file($component, $value, $format = 'html') {
  323. $fid = isset($value[0]) ? $value[0] : NULL;
  324. return array(
  325. '#title' => $component['name'],
  326. '#value' => $fid ? webform_get_file($fid) : NULL,
  327. '#weight' => $component['weight'],
  328. '#theme' => 'webform_display_file',
  329. '#theme_wrappers' => $format == 'text' ? array('webform_element_text') : array('webform_element'),
  330. '#format' => $format,
  331. '#translatable' => array('title'),
  332. );
  333. }
  334. /**
  335. * Format the output of text data for this component
  336. */
  337. function theme_webform_display_file($variables) {
  338. $element = $variables['element'];
  339. $file = $element['#value'];
  340. $url = !empty($file) ? webform_file_url($file->uri) : t('no upload');
  341. return !empty($file) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url)) : ' ';
  342. }
  343. /**
  344. * Implements _webform_delete_component().
  345. */
  346. function _webform_delete_file($component, $value) {
  347. // Delete an individual submission file.
  348. if (!empty($value[0]) && ($file = webform_get_file($value[0]))) {
  349. file_delete($file);
  350. }
  351. }
  352. /**
  353. * Implements _webform_attachments_component().
  354. */
  355. function _webform_attachments_file($component, $value) {
  356. $file = (array) webform_get_file($value[0]);
  357. //This is necessary until the next release of mimemail is out, see [#1388786]
  358. $file['filepath'] = $file['uri'];
  359. $files = array($file);
  360. return $files;
  361. }
  362. /**
  363. * Implements _webform_analysis_component().
  364. */
  365. function _webform_analysis_file($component, $sids = array()) {
  366. $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
  367. ->fields('wsd', array('no', 'data'))
  368. ->condition('nid', $component['nid'])
  369. ->condition('cid', $component['cid']);
  370. if (count($sids)) {
  371. $query->condition('sid', $sids, 'IN');
  372. }
  373. $nonblanks = 0;
  374. $sizetotal = 0;
  375. $submissions = 0;
  376. $result = $query->execute();
  377. foreach ($result as $data) {
  378. $file = webform_get_file($data['data']);
  379. if (isset($file->filesize)) {
  380. $nonblanks++;
  381. $sizetotal += $file->filesize;
  382. }
  383. $submissions++;
  384. }
  385. $rows[0] = array(t('Left Blank'), ($submissions - $nonblanks));
  386. $rows[1] = array(t('User uploaded file'), $nonblanks);
  387. $rows[2] = array(t('Average uploaded file size'), ($sizetotal != 0 ? (int) (($sizetotal/$nonblanks)/1024) . ' KB' : '0'));
  388. return $rows;
  389. }
  390. /**
  391. * Implements _webform_table_component().
  392. */
  393. function _webform_table_file($component, $value) {
  394. $output = '';
  395. $file = webform_get_file($value[0]);
  396. if (!empty($file->fid)) {
  397. $output = '<a href="' . webform_file_url($file->uri) . '">' . check_plain(webform_file_name($file->uri)) . '</a>';
  398. $output .= ' (' . (int) ($file->filesize/1024) . ' KB)';
  399. }
  400. return $output;
  401. }
  402. /**
  403. * Implements _webform_csv_headers_component().
  404. */
  405. function _webform_csv_headers_file($component, $export_options) {
  406. $header = array();
  407. // Two columns in header.
  408. $header[0] = array('', '');
  409. $header[1] = array($component['name'], '');
  410. $header[2] = array(t('Name'), t('Filesize (KB)'));
  411. return $header;
  412. }
  413. /**
  414. * Implements _webform_csv_data_component().
  415. */
  416. function _webform_csv_data_file($component, $export_options, $value) {
  417. $file = webform_get_file($value[0]);
  418. return empty($file->filename) ? array('', '') : array(webform_file_url($file->uri), (int) ($file->filesize/1024));
  419. }
  420. /**
  421. * Helper function to create proper file names for uploaded file.
  422. */
  423. function webform_file_name($filepath) {
  424. if (!empty($filepath)) {
  425. $info = pathinfo($filepath);
  426. $file_name = $info['basename'];
  427. }
  428. return isset($file_name) ? $file_name : '';
  429. }
  430. /**
  431. * Helper function to create proper URLs for uploaded file.
  432. */
  433. function webform_file_url($uri) {
  434. if (!empty($uri)) {
  435. $file_url = file_create_url($uri);
  436. }
  437. return isset($file_url) ? $file_url : '';
  438. }
  439. /**
  440. * Helper function to load a file from the database.
  441. */
  442. function webform_get_file($fid) {
  443. // Simple check to prevent loading of NULL values, which throws an entity
  444. // system error.
  445. return $fid ? file_load($fid) : FALSE;
  446. }
  447. /**
  448. * Given a submission with file_usage set, add or remove file usage entries.
  449. */
  450. function webform_file_usage_adjust($submission) {
  451. if (isset($submission->file_usage)) {
  452. $files = file_load_multiple($submission->file_usage['added_fids']);
  453. foreach ($files as $file) {
  454. $file->status = 1;
  455. file_save($file);
  456. file_usage_add($file, 'webform', 'submission', $submission->sid);
  457. }
  458. $files = file_load_multiple($submission->file_usage['deleted_fids']);
  459. foreach ($files as $file) {
  460. file_usage_delete($file, 'webform', 'submission', $submission->sid);
  461. file_delete($file);
  462. }
  463. }
  464. }