5 * Webform module file component.
9 * Implements _webform_defaults_component().
11 function _webform_defaults_file() {
20 'types' => array('gif', 'jpg', 'png'),
21 'addextensions' => '',
27 'progress_indicator' => 'throbber',
30 'description_above' => FALSE,
31 'attributes' => array(),
39 * Implements _webform_theme_component().
41 function _webform_theme_file() {
43 'webform_edit_file_extensions' => array(
44 'render element' => 'element',
45 'file' => 'components/file.inc',
47 'webform_display_file' => array(
48 'render element' => 'element',
49 'file' => 'components/file.inc',
51 'webform_managed_file' => array(
52 'render element' => 'element',
53 'file' => 'components/file.inc',
59 * Implements _webform_edit_component().
61 function _webform_edit_file($component) {
63 $form['#element_validate'] = array('_webform_edit_file_check_directory');
64 $form['#after_build'] = array('_webform_edit_file_check_directory');
66 $form['validation']['size'] = array(
67 '#type' => 'textfield',
68 '#title' => t('Max upload size'),
69 '#default_value' => $component['extra']['filtering']['size'],
70 '#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()))),
72 '#parents' => array('extra', 'filtering', 'size'),
73 '#element_validate' => array('_webform_edit_file_size_validate'),
77 $form['validation']['extensions'] = array(
78 '#element_validate' => array('_webform_edit_file_extensions_validate'),
79 '#parents' => array('extra', 'filtering'),
80 '#theme' => 'webform_edit_file_extensions',
81 '#theme_wrappers' => array('form_element'),
82 '#title' => t('Allowed file extensions'),
84 'js' => array(drupal_get_path('module', 'webform') . '/js/webform-admin.js'),
85 'css' => array(drupal_get_path('module', 'webform') . '/css/webform-admin.css'),
87 '#type' => 'webform_file_extensions',
91 // Find the list of all currently valid extensions.
92 $current_types = isset($component['extra']['filtering']['types']) ? $component['extra']['filtering']['types'] : array();
94 $types = array('gif', 'jpg', 'png');
95 $form['validation']['extensions']['types']['webimages'] = array(
96 '#type' => 'checkboxes',
97 '#title' => t('Web images'),
98 '#options' => drupal_map_assoc($types),
99 '#default_value' => array_intersect($current_types, $types),
102 $types = array('bmp', 'eps', 'tif', 'pict', 'psd');
103 $form['validation']['extensions']['types']['desktopimages'] = array(
104 '#type' => 'checkboxes',
105 '#title' => t('Desktop images'),
106 '#options' => drupal_map_assoc($types),
107 '#default_value' => array_intersect($current_types, $types),
110 $types = array('txt', 'rtf', 'html', 'pdf', 'doc', 'docx', 'odt', 'ppt', 'pptx', 'odp', 'xls', 'xlsx', 'ods', 'xml');
111 $form['validation']['extensions']['types']['documents'] = array(
112 '#type' => 'checkboxes',
113 '#title' => t('Documents'),
114 '#options' => drupal_map_assoc($types),
115 '#default_value' => array_intersect($current_types, $types),
118 $types = array('avi', 'mov', 'mp3', 'ogg', 'wav');
119 $form['validation']['extensions']['types']['media'] = array(
120 '#type' => 'checkboxes',
121 '#title' => t('Media'),
122 '#options' => drupal_map_assoc($types),
123 '#default_value' => array_intersect($current_types, $types),
126 $types = array('bz2', 'dmg', 'gz', 'jar', 'rar', 'sit', 'tar', 'zip');
127 $form['validation']['extensions']['types']['archives'] = array(
128 '#type' => 'checkboxes',
129 '#title' => t('Archives'),
130 '#options' => drupal_map_assoc($types),
131 '#default_value' => array_intersect($current_types, $types),
134 $form['validation']['extensions']['addextensions'] = array(
135 '#type' => 'textfield',
136 '#title' => t('Additional extensions'),
137 '#default_value' => $component['extra']['filtering']['addextensions'],
138 '#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.'),
143 $scheme_options = array();
144 foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $stream_wrapper) {
145 $scheme_options[$scheme] = $stream_wrapper['name'];
147 $form['extra']['scheme'] = array(
149 '#title' => t('Upload destination'),
150 '#options' => $scheme_options,
151 '#default_value' => $component['extra']['scheme'],
152 '#description' => t('Private file storage has significantly more overhead than public files, but restricts file access to users who can view submissions.'),
154 '#access' => count($scheme_options) > 1,
156 $form['extra']['directory'] = array(
157 '#type' => 'textfield',
158 '#title' => t('Upload directory'),
159 '#default_value' => $component['extra']['directory'],
160 '#description' => t('You may optionally specify a sub-directory to store your files.') . ' ' . theme('webform_token_help'),
162 '#field_prefix' => 'webform/',
165 $form['extra']['rename'] = array(
166 '#type' => 'textfield',
167 '#title' => t('Rename files'),
168 '#default_value' => $component['extra']['rename'],
169 '#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'))),
171 '#element_validate' => array('_webform_edit_file_rename_validate'),
172 '#access' => webform_variable_get('webform_token_access'),
175 $form['display']['progress_indicator'] = array(
177 '#title' => t('Progress indicator'),
179 'throbber' => t('Throbber'),
180 'bar' => t('Bar with progress meter'),
182 '#default_value' => $component['extra']['progress_indicator'],
183 '#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.'),
185 '#access' => file_progress_implementation(),
186 '#parents' => array('extra', 'progress_indicator'),
189 // TODO: Make managed_file respect the "size" parameter.
191 $form['display']['width'] = array(
192 '#type' => 'textfield',
193 '#title' => t('Width'),
194 '#default_value' => $component['extra']['width'],
195 '#description' => t('Width of the file field.') . ' ' . t('Leaving blank will use the default size.'),
199 '#parents' => array('extra', 'width')
207 * A Form API element validate function to ensure that the rename string is
208 * either empty or contains at least one token.
210 function _webform_edit_file_rename_validate($element, &$form_state, $form) {
211 $rename = trim($form_state['values']['extra']['rename']);
212 form_set_value($element, $rename, $form_state);
213 if (strlen($rename) && !count(token_scan($rename))) {
214 form_error($element, t('To create unique file names, use at least one token in the file name pattern.'));
219 * A Form API element validate function to check filesize is valid.
221 function _webform_edit_file_size_validate($element) {
222 if (!empty($element['#value'])) {
223 $set_filesize = parse_size($element['#value']);
224 if ($set_filesize == FALSE) {
225 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'])));
228 $max_filesize = parse_size(file_upload_max_size());
229 if ($max_filesize < $set_filesize) {
230 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))));
237 * A Form API after build and validate function.
239 * Ensure that the destination directory exists and is writable.
241 function _webform_edit_file_check_directory($element) {
242 $scheme = $element['extra']['scheme']['#value'];
243 $directory = $element['extra']['directory']['#value'];
245 $destination_dir = file_stream_wrapper_uri_normalize($scheme . '://webform/' . $directory);
246 $tokenized_dir = drupal_strtolower(webform_replace_tokens($destination_dir, $element['#node']));
248 // Sanity check input to prevent use parent (../) directories.
249 if (preg_match('/\.\.[\/\\\]/', $tokenized_dir . '/')) {
250 form_error($element['extra']['directory'], t('The save directory %directory is not valid.', array('%directory' => $tokenized_dir)));
253 if (!file_prepare_directory($tokenized_dir, FILE_CREATE_DIRECTORY)) {
254 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)));
262 * A Form API element validate function.
264 * Change the submitted values of the component so that all filtering extensions
265 * are saved as a single array.
267 function _webform_edit_file_extensions_validate($element, &$form_state) {
269 $extensions = array();
270 foreach (element_children($element['types']) as $category) {
271 foreach (array_keys($element['types'][$category]['#value']) as $extension) {
272 if ($element['types'][$category][$extension]['#value']) {
273 $extensions[] = $extension;
274 // jpeg is an exception. It is allowed anytime jpg is allowed.
275 if ($extension == 'jpg') {
276 $extensions[] = 'jpeg';
283 $additional_extensions = explode(',', $element['addextensions']['#value']);
284 foreach ($additional_extensions as $extension) {
285 $clean_extension = drupal_strtolower(trim($extension));
286 if (!empty($clean_extension) && !in_array($clean_extension, $extensions)) {
287 $extensions[] = $clean_extension;
291 form_set_value($element['types'], $extensions, $form_state);
295 * Output the list of allowed extensions as checkboxes.
297 function theme_webform_edit_file_extensions($variables) {
298 $element = $variables['element'];
300 // Format the components into a table.
302 foreach (element_children($element['types']) as $filtergroup) {
304 $first_row = count($rows);
305 if ($element['types'][$filtergroup]['#type'] == 'checkboxes') {
306 $select_link = ' <a href="#" class="webform-select-link webform-select-link-' . $filtergroup . '">(' . t('select') . ')</a>';
307 $row[] = $element['types'][$filtergroup]['#title'];
308 $row[] = array('data' => $select_link, 'width' => 40);
309 $row[] = array('data' => drupal_render_children($element['types'][$filtergroup]), 'class' => array('webform-file-extensions', 'webform-select-group-' . $filtergroup));
310 $rows[] = array('data' => $row);
311 unset($element['types'][$filtergroup]);
315 // Add the row for additional types.
317 $title = $element['addextensions']['#title'];
318 $element['addextensions']['#title'] = NULL;
319 $row[] = array('data' => $title, 'colspan' => 2);
320 $row[] = drupal_render($element['addextensions']);
323 $header = array(array('data' => t('Category'), 'colspan' => '2'), array('data' => t('Types')));
325 // Create the table inside the form.
326 $element['types']['table'] = array(
328 '#header' => $header,
330 '#attributes' => array('class' => array('webform-file-extensions')),
333 return drupal_render_children($element);
337 * Implements _webform_render_component().
339 function _webform_render_file($component, $value = NULL, $filter = TRUE, $submission = NULL) {
340 $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
342 // Cap the upload size according to the PHP limit.
343 $max_filesize = parse_size(file_upload_max_size());
344 $set_filesize = $component['extra']['filtering']['size'];
345 if (!empty($set_filesize) && parse_size($set_filesize) < $max_filesize) {
346 $max_filesize = parse_size($set_filesize);
350 '#type' => 'managed_file',
351 '#theme' => 'webform_managed_file',
352 '#title' => $filter ? webform_filter_xss($component['name']) : $component['name'],
353 '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
354 '#required' => $component['required'],
355 '#default_value' => isset($value[0]) ? $value[0] : NULL,
356 '#attributes' => $component['extra']['attributes'],
357 '#upload_validators' => array(
358 'file_validate_size' => array($max_filesize),
359 'file_validate_extensions' => array(implode(' ', $component['extra']['filtering']['types'])),
361 '#pre_render' => array_merge(element_info_property('managed_file', '#pre_render'), array('webform_file_allow_access')),
362 '#upload_location' => $component['extra']['scheme'] . '://webform/' . ($filter
363 ? drupal_strtolower(webform_replace_tokens($component['extra']['directory'], $node))
364 : $component['extra']['directory']),
365 '#progress_indicator' => $component['extra']['progress_indicator'],
366 '#description' => $filter ? webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
367 '#weight' => $component['weight'],
368 '#theme_wrappers' => array('webform_element'),
369 '#translatable' => array('title', 'description'),
373 $element['#description'] = theme('file_upload_help', array('description' => $element['#description'], 'upload_validators' => $element['#upload_validators']));
380 * Returns HTML for a webform managed file element.
382 * See #2495821 and #2497909. The core theme_file_managed_file creates a
383 * wrapper around the element with the element's id, thereby creating 2 elements
387 * An associative array containing:
388 * - element: A render element representing the file.
391 function theme_webform_managed_file($variables) {
392 $element = $variables['element'];
394 $attributes = array();
396 // For webform use, do not add the id to the wrapper.
397 //if (isset($element['#id'])) {
398 // $attributes['id'] = $element['#id'];
401 if (!empty($element['#attributes']['class'])) {
402 $attributes['class'] = (array) $element['#attributes']['class'];
404 $attributes['class'][] = 'form-managed-file';
406 // This wrapper is required to apply JS behaviors and CSS styling.
408 $output .= '<div' . drupal_attributes($attributes) . '>';
409 $output .= drupal_render_children($element);
416 * Implements _webform_submit_component().
418 function _webform_submit_file($component, $value) {
419 $fid = is_array($value)
420 ? (!empty($value['fid']) ? $value['fid'] : '')
421 : (!empty($value) ? $value : '');
422 // Extend access to this file, even if the submission has not been saved yet. This may happen when
423 // previewing a private file which was selected but not explicitly uploaded, and then previewed.
425 $_SESSION['webform_files'][$fid] = $fid;
431 * Pre-render callback to allow access to uploaded files.
433 * Files that have not yet been saved into a submission must be accessible to
434 * the user who uploaded it, but no one else. After the submission is saved,
435 * access is granted through the file_usage table. Before then, we use a
436 * $_SESSION value to record a user's upload.
438 * @see webform_file_download()
440 function webform_file_allow_access($element) {
441 if (!empty($element['#value']['fid'])) {
442 $fid = $element['#value']['fid'];
443 $_SESSION['webform_files'][$fid] = $fid;
450 * Implements _webform_display_component().
452 function _webform_display_file($component, $value, $format = 'html', $submission = array()) {
453 $fid = isset($value[0]) ? $value[0] : NULL;
455 '#title' => $component['name'],
456 '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
457 '#value' => $fid ? webform_get_file($fid) : NULL,
458 '#weight' => $component['weight'],
459 '#theme' => 'webform_display_file',
460 '#theme_wrappers' => $format == 'text' ? array('webform_element_text') : array('webform_element'),
461 '#format' => $format,
462 '#translatable' => array('title'),
467 * Format the output of text data for this component
469 function theme_webform_display_file($variables) {
470 $element = $variables['element'];
472 $file = $element['#value'];
473 $url = !empty($file) ? webform_file_url($file->uri) : t('no upload');
474 return !empty($file) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url)) : ' ';
478 * Implements _webform_delete_component().
480 function _webform_delete_file($component, $value) {
481 // Delete an individual submission file.
482 if (!empty($value[0]) && ($file = webform_get_file($value[0]))) {
483 file_usage_delete($file, 'webform');
489 * Implements _webform_attachments_component().
491 function _webform_attachments_file($component, $value) {
492 $file = (array) webform_get_file($value[0]);
493 //This is necessary until the next release of mimemail is out, see [#1388786]
494 $file['filepath'] = $file['uri'];
495 $files = array($file);
499 * Implements _webform_analysis_component().
501 function _webform_analysis_file($component, $sids = array(), $single = FALSE, $join = NULL) {
502 $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
503 ->fields('wsd', array('no', 'data'))
504 ->condition('wsd.nid', $component['nid'])
505 ->condition('wsd.cid', $component['cid']);
508 $query->condition('wsd.sid', $sids, 'IN');
512 $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
519 $result = $query->execute();
520 foreach ($result as $data) {
521 $file = webform_get_file($data['data']);
522 if (isset($file->filesize)) {
524 $sizetotal += $file->filesize;
529 $rows[0] = array(t('Left Blank'), ($submissions - $nonblanks));
530 $rows[1] = array(t('User uploaded file'), $nonblanks);
531 $other[0] = array(t('Average uploaded file size'), ($sizetotal != 0 ? (int) (($sizetotal/$nonblanks)/1024) . ' KB' : '0'));
533 'table_rows' => $rows,
534 'other_data' => $other,
539 * Implements _webform_table_component().
541 function _webform_table_file($component, $value) {
543 $file = webform_get_file($value[0]);
544 if (!empty($file->fid)) {
545 $output = '<a href="' . webform_file_url($file->uri) . '">' . check_plain(webform_file_name($file->uri)) . '</a>';
546 $output .= ' (' . (int) ($file->filesize/1024) . ' KB)';
552 * Implements _webform_csv_headers_component().
554 function _webform_csv_headers_file($component, $export_options) {
556 // Two columns in header.
557 $header[0] = array('', '');
558 $header[1] = array($export_options['header_keys'] ? $component['form_key'] : $component['name'], '');
559 $header[2] = array(t('Name'), t('Filesize (KB)'));
564 * Implements _webform_csv_data_component().
566 function _webform_csv_data_file($component, $export_options, $value) {
567 $file = webform_get_file($value[0]);
568 return empty($file->filename) ? array('', '') : array(webform_file_url($file->uri), (int) ($file->filesize/1024));
572 * Helper function to create proper file names for uploaded file.
574 function webform_file_name($filepath) {
575 if (!empty($filepath)) {
576 $info = pathinfo($filepath);
577 $file_name = $info['basename'];
579 return isset($file_name) ? $file_name : '';
583 * Helper function to create proper URLs for uploaded file.
585 function webform_file_url($uri) {
587 $file_url = file_create_url($uri);
589 return isset($file_url) ? $file_url : '';
593 * Helper function to load a file from the database.
595 function webform_get_file($fid) {
596 // Simple check to prevent loading of NULL values, which throws an entity
598 return $fid ? file_load($fid) : FALSE;
602 * Given a submission with file_usage set, add or remove file usage entries.
604 function webform_file_usage_adjust($submission) {
605 if (isset($submission->file_usage)) {
606 $files = file_load_multiple($submission->file_usage['added_fids']);
607 foreach ($files as $file) {
610 file_usage_add($file, 'webform', 'submission', $submission->sid);
613 $files = file_load_multiple($submission->file_usage['deleted_fids']);
614 foreach ($files as $file) {
615 file_usage_delete($file, 'webform', 'submission', $submission->sid);
622 * Rename any files which are eligible for renaming, if this submission is being
623 * submitted for the first time.
625 function webform_file_rename($node, $submission) {
626 if (isset($submission->file_usage)) {
627 foreach ($submission->file_usage['renameable'] as $cid => $fids) {
628 foreach ($fids as $fid) {
629 webform_file_process_rename($node, $submission, $node->webform['components'][$cid], $fid);
637 * Renames the uploaded file name using tokens.
640 * The webform node object.
642 * The webform submission object.
644 * Component settings array for which fid is going to be processed.
646 * A file id to be processed.
648 function webform_file_process_rename($node, $submission, $component, $fid) {
649 $file = webform_get_file($fid);
652 // Get the destination uri.
653 $destination_dir = $component['extra']['scheme'] . '://webform/' . drupal_strtolower(webform_replace_tokens($component['extra']['directory'], $node));
654 $destination_dir = file_stream_wrapper_uri_normalize($destination_dir);
656 // Get the file extension.
657 $info = pathinfo($file->uri);
658 $extension = $info['extension'];
660 // Prepare new file name without extension.
661 $new_file_name = webform_replace_tokens($component['extra']['rename'], $node, $submission, NULL, TRUE);
662 $new_file_name = trim($new_file_name);
663 $new_file_name = _webform_transliterate($new_file_name);
664 $new_file_name = str_replace('/', '_', $new_file_name);
665 $new_file_name = preg_replace('/[^a-zA-Z0-9_\- ]/', '', $new_file_name);
666 if (strlen($new_file_name)) {
667 // Prepare the new uri with new filename.
668 $destination = "$destination_dir/$new_file_name.$extension";
670 // Compare the uri and Rename the file name.
671 if ($file->uri != $destination) {
672 file_move($file, $destination, FILE_EXISTS_RENAME);