Project

General

Profile

Paste
Download (23.7 KB) Statistics
| Branch: | Revision:

root / drupal7 / sites / all / modules / webform / components / file.inc @ 01f36513

1
<?php
2

    
3
/**
4
 * @file
5
 * Webform module file component.
6
 */
7

    
8
/**
9
 * Implements _webform_defaults_component().
10
 */
11
function _webform_defaults_file() {
12
  // If private file storage is enabled, make it the default for security
13
  // reasons. See: https://www.drupal.org/psa-2016-003
14
  $available_schemes = file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE);
15
  $scheme = isset($available_schemes['private']) ? 'private' : 'public';
16

    
17
  return array(
18
    'name' => '',
19
    'form_key' => NULL,
20
    'required' => 0,
21
    'pid' => 0,
22
    'weight' => 0,
23
    'extra' => array(
24
      'filtering' => array(
25
        'types' => array('gif', 'jpg', 'png'),
26
        'addextensions' => '',
27
        'size' => '2 MB',
28
      ),
29
      'rename' => '',
30
      'scheme' => $scheme,
31
      'directory' => '',
32
      'progress_indicator' => 'throbber',
33
      'title_display' => 0,
34
      'description' => '',
35
      'description_above' => FALSE,
36
      'attributes' => array(),
37
      'private' => FALSE,
38
      'analysis' => FALSE,
39
    ),
40
  );
41
}
42

    
43
/**
44
 * Implements _webform_theme_component().
45
 */
46
function _webform_theme_file() {
47
  return array(
48
    'webform_edit_file_extensions' => array(
49
      'render element' => 'element',
50
      'file' => 'components/file.inc',
51
    ),
52
    'webform_display_file' => array(
53
      'render element' => 'element',
54
      'file' => 'components/file.inc',
55
    ),
56
    'webform_managed_file' => array(
57
      'render element' => 'element',
58
      'file' => 'components/file.inc',
59
    ),
60
  );
61
}
62

    
63
/**
64
 * Implements _webform_edit_component().
65
 */
66
function _webform_edit_file($component) {
67
  $form = array();
68
  $form['#element_validate'] = array('_webform_edit_file_check_directory');
69
  $form['#after_build'] = array('_webform_edit_file_check_directory');
70

    
71
  $form['validation']['size'] = array(
72
    '#type' => 'textfield',
73
    '#title' => t('Max upload size'),
74
    '#default_value' => $component['extra']['filtering']['size'],
75
    '#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()))),
76
    '#size' => 10,
77
    '#parents' => array('extra', 'filtering', 'size'),
78
    '#element_validate' => array('_webform_edit_file_size_validate'),
79
    '#weight' => 1,
80
  );
81

    
82
  $form['validation']['extensions'] = array(
83
    '#element_validate' => array('_webform_edit_file_extensions_validate'),
84
    '#parents' => array('extra', 'filtering'),
85
    '#theme' => 'webform_edit_file_extensions',
86
    '#theme_wrappers' => array('form_element'),
87
    '#title' => t('Allowed file extensions'),
88
    '#attached' => array(
89
      'js' => array(drupal_get_path('module', 'webform') . '/js/webform-admin.js'),
90
      'css' => array(drupal_get_path('module', 'webform') . '/css/webform-admin.css'),
91
    ),
92
    '#type' => 'webform_file_extensions',
93
    '#weight' => 2,
94
  );
95

    
96
  // Find the list of all currently valid extensions.
97
  $current_types = isset($component['extra']['filtering']['types']) ? $component['extra']['filtering']['types'] : array();
98

    
99
  $types = array('gif', 'jpg', 'png');
100
  $form['validation']['extensions']['types']['webimages'] = array(
101
    '#type' => 'checkboxes',
102
    '#title' => t('Web images'),
103
    '#options' => drupal_map_assoc($types),
104
    '#default_value' => array_intersect($current_types, $types),
105
  );
106

    
107
  $types = array('bmp', 'eps', 'tif', 'pict', 'psd');
108
  $form['validation']['extensions']['types']['desktopimages'] = array(
109
    '#type' => 'checkboxes',
110
    '#title' => t('Desktop images'),
111
    '#options' => drupal_map_assoc($types),
112
    '#default_value' => array_intersect($current_types, $types),
113
  );
114

    
115
  $types = array('txt', 'rtf', 'html', 'pdf', 'doc', 'docx', 'odt', 'ppt', 'pptx', 'odp', 'xls', 'xlsx', 'ods', 'xml');
116
  $form['validation']['extensions']['types']['documents'] = array(
117
    '#type' => 'checkboxes',
118
    '#title' => t('Documents'),
119
    '#options' => drupal_map_assoc($types),
120
    '#default_value' => array_intersect($current_types, $types),
121
  );
122

    
123
  $types = array('avi', 'mov', 'mp3', 'ogg', 'wav');
124
  $form['validation']['extensions']['types']['media'] = array(
125
    '#type' => 'checkboxes',
126
    '#title' => t('Media'),
127
    '#options' => drupal_map_assoc($types),
128
    '#default_value' => array_intersect($current_types, $types),
129
  );
130

    
131
  $types = array('bz2', 'dmg', 'gz', 'jar', 'rar', 'sit', 'tar', 'zip');
132
  $form['validation']['extensions']['types']['archives'] = array(
133
    '#type' => 'checkboxes',
134
    '#title' => t('Archives'),
135
    '#options' => drupal_map_assoc($types),
136
    '#default_value' => array_intersect($current_types, $types),
137
  );
138

    
139
  $form['validation']['extensions']['addextensions'] = array(
140
    '#type' => 'textfield',
141
    '#title' => t('Additional extensions'),
142
    '#default_value' => $component['extra']['filtering']['addextensions'],
143
    '#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.'),
144
    '#size' => 20,
145
    '#weight' => 3,
146
  );
147

    
148
  $scheme_options = array();
149
  foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $stream_wrapper) {
150
    $scheme_options[$scheme] = $stream_wrapper['name'];
151
  }
152
  $form['extra']['scheme'] = array(
153
    '#type' => 'radios',
154
    '#title' => t('Upload destination'),
155
    '#options' => $scheme_options,
156
    '#default_value' => $component['extra']['scheme'],
157
    '#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')),
158
    '#weight' => 4,
159
    '#access' => count($scheme_options) > 1,
160
  );
161
  $form['extra']['directory'] = array(
162
    '#type' => 'textfield',
163
    '#title' => t('Upload directory'),
164
    '#default_value' => $component['extra']['directory'],
165
    '#description' => t('You may optionally specify a sub-directory to store your files.') . ' ' . theme('webform_token_help'),
166
    '#weight' => 5,
167
    '#field_prefix' => 'webform/',
168
  );
169

    
170
  $form['extra']['rename'] = array(
171
    '#type' => 'textfield',
172
    '#title' => t('Rename files'),
173
    '#default_value' => $component['extra']['rename'],
174
    '#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'))),
175
    '#weight' => 6,
176
    '#element_validate' => array('_webform_edit_file_rename_validate'),
177
    '#access' => webform_variable_get('webform_token_access'),
178
  );
179

    
180
  $form['display']['progress_indicator'] = array(
181
    '#type' => 'radios',
182
    '#title' => t('Progress indicator'),
183
    '#options' => array(
184
      'throbber' => t('Throbber'),
185
      'bar' => t('Bar with progress meter'),
186
    ),
187
    '#default_value' => $component['extra']['progress_indicator'],
188
    '#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.'),
189
    '#weight' => 16,
190
    '#access' => file_progress_implementation(),
191
    '#parents' => array('extra', 'progress_indicator'),
192
  );
193

    
194
  // @todo: Make managed_file respect the "size" parameter.
195
  /*
196
  $form['display']['width'] = array(
197
  '#type' => 'textfield',
198
  '#title' => t('Width'),
199
  '#default_value' => $component['extra']['width'],
200
  '#description' => t('Width of the file field.') . ' ' . t('Leaving blank will use the default size.'),
201
  '#size' => 5,
202
  '#maxlength' => 10,
203
  '#weight' => 4,
204
  '#parents' => array('extra', 'width')
205
  );
206
   */
207

    
208
  return $form;
209
}
210

    
211
/**
212
 * Form API validator ensures rename string is empty or contains one token.
213
 *
214
 * A Form API element validate function to ensure that the rename string is
215
 * either empty or contains at least one token.
216
 */
217
function _webform_edit_file_rename_validate($element, &$form_state, $form) {
218
  $rename = trim($form_state['values']['extra']['rename']);
219
  form_set_value($element, $rename, $form_state);
220
  if (strlen($rename) && !count(token_scan($rename))) {
221
    form_error($element, t('To create unique file names, use at least one token in the file name pattern.'));
222
  }
223
}
224

    
225
/**
226
 * A Form API element validate function to check filesize is valid.
227
 */
228
function _webform_edit_file_size_validate($element) {
229
  if (!empty($element['#value'])) {
230
    $set_filesize = parse_size($element['#value']);
231
    if ($set_filesize == FALSE) {
232
      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'])));
233
    }
234
    else {
235
      $max_filesize = parse_size(file_upload_max_size());
236
      if ($max_filesize < $set_filesize) {
237
        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))));
238
      }
239
    }
240
  }
241
}
242

    
243
/**
244
 * A Form API after build and validate function.
245
 *
246
 * Ensure that the destination directory exists and is writable.
247
 */
248
function _webform_edit_file_check_directory($element) {
249
  $scheme = $element['extra']['scheme']['#value'];
250
  $directory = $element['extra']['directory']['#value'];
251

    
252
  $destination_dir = file_stream_wrapper_uri_normalize($scheme . '://webform/' . $directory);
253
  $tokenized_dir = drupal_strtolower(webform_replace_tokens($destination_dir, $element['#node']));
254

    
255
  // Sanity check input to prevent use parent (../) directories.
256
  if (preg_match('/\.\.[\/\\\]/', $tokenized_dir . '/')) {
257
    form_error($element['extra']['directory'], t('The save directory %directory is not valid.', array('%directory' => $tokenized_dir)));
258
  }
259
  else {
260
    if (!file_prepare_directory($tokenized_dir, FILE_CREATE_DIRECTORY)) {
261
      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
    }
263
  }
264

    
265
  return $element;
266
}
267

    
268
/**
269
 * A Form API element validate function.
270
 *
271
 * Change the submitted values of the component so that all filtering extensions
272
 * are saved as a single array.
273
 */
274
function _webform_edit_file_extensions_validate($element, &$form_state) {
275
  // Predefined types.
276
  $extensions = array();
277
  foreach (element_children($element['types']) as $category) {
278
    foreach (array_keys($element['types'][$category]['#value']) as $extension) {
279
      if ($element['types'][$category][$extension]['#value']) {
280
        $extensions[] = $extension;
281
        // "jpeg" is an exception. It is allowed anytime "jpg" is allowed.
282
        if ($extension == 'jpg') {
283
          $extensions[] = 'jpeg';
284
        }
285
      }
286
    }
287
  }
288

    
289
  // Additional types.
290
  $additional_extensions = explode(',', $element['addextensions']['#value']);
291
  foreach ($additional_extensions as $extension) {
292
    $clean_extension = drupal_strtolower(trim($extension));
293
    if (!empty($clean_extension) && !in_array($clean_extension, $extensions)) {
294
      $extensions[] = $clean_extension;
295
    }
296
  }
297

    
298
  form_set_value($element['types'], $extensions, $form_state);
299
}
300

    
301
/**
302
 * Output the list of allowed extensions as checkboxes.
303
 */
304
function theme_webform_edit_file_extensions($variables) {
305
  $element = $variables['element'];
306

    
307
  // Format the components into a table.
308
  $rows = array();
309
  foreach (element_children($element['types']) as $filtergroup) {
310
    $row = array();
311
    if ($element['types'][$filtergroup]['#type'] == 'checkboxes') {
312
      $select_link = ' <a href="#" class="webform-select-link webform-select-link-' . $filtergroup . '">(' . t('select') . ')</a>';
313
      $row[] = $element['types'][$filtergroup]['#title'];
314
      $row[] = array('data' => $select_link, 'width' => 40);
315
      $row[] = array('data' => drupal_render_children($element['types'][$filtergroup]), 'class' => array('webform-file-extensions', 'webform-select-group-' . $filtergroup));
316
      $rows[] = array('data' => $row);
317
      unset($element['types'][$filtergroup]);
318
    }
319
  }
320

    
321
  // Add the row for additional types.
322
  if (!isset($element['addextensions']['#access']) || $element['addextensions']['#access']) {
323
    $row = array();
324
    $title = $element['addextensions']['#title'];
325
    $element['addextensions']['#title'] = NULL;
326
    $row[] = array('data' => $title, 'colspan' => 2);
327
    $row[] = drupal_render($element['addextensions']);
328
    $rows[] = $row;
329
  }
330

    
331
  $header = array(array('data' => t('Category'), 'colspan' => '2'), array('data' => t('Types')));
332

    
333
  // Create the table inside the form.
334
  $element['types']['table'] = array(
335
    '#theme' => 'table',
336
    '#header' => $header,
337
    '#rows' => $rows,
338
    '#attributes' => array('class' => array('webform-file-extensions')),
339
  );
340

    
341
  return drupal_render_children($element);
342
}
343

    
344
/**
345
 * Implements _webform_render_component().
346
 */
347
function _webform_render_file($component, $value = NULL, $filter = TRUE, $submission = NULL) {
348
  $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
349

    
350
  // Cap the upload size according to the PHP limit.
351
  $max_filesize = parse_size(file_upload_max_size());
352
  $set_filesize = $component['extra']['filtering']['size'];
353
  if (!empty($set_filesize) && parse_size($set_filesize) < $max_filesize) {
354
    $max_filesize = parse_size($set_filesize);
355
  }
356

    
357
  $element = array(
358
    '#type' => 'managed_file',
359
    '#theme' => 'webform_managed_file',
360
    '#title' => $filter ? webform_filter_xss($component['name']) : $component['name'],
361
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
362
    '#required' => $component['required'],
363
    '#default_value' => isset($value[0]) ? $value[0] : NULL,
364
    '#attributes' => $component['extra']['attributes'],
365
    '#upload_validators' => array(
366
      'file_validate_size' => array($max_filesize),
367
      'file_validate_extensions' => array(implode(' ', $component['extra']['filtering']['types'])),
368
    ),
369
    '#pre_render' => array_merge(element_info_property('managed_file', '#pre_render'), array('webform_file_allow_access')),
370
    '#upload_location' => $component['extra']['scheme'] . '://webform/' . ($filter
371
                                                                              ? drupal_strtolower(webform_replace_tokens($component['extra']['directory'], $node))
372
                                                                              : $component['extra']['directory']),
373
    '#progress_indicator' => $component['extra']['progress_indicator'],
374
    '#description' => $filter ? webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
375
    '#weight' => $component['weight'],
376
    '#theme_wrappers' => array('webform_element'),
377
    '#translatable' => array('title', 'description'),
378
  );
379

    
380
  if ($filter) {
381
    $element['#description'] = theme('file_upload_help', array('description' => $element['#description'], 'upload_validators' => $element['#upload_validators']));
382
  }
383

    
384
  return $element;
385
}
386

    
387
/**
388
 * Returns HTML for a webform managed file element.
389
 *
390
 * See #2495821 and #2497909. The core theme_file_managed_file creates a
391
 * wrapper around the element with the element's id, thereby creating 2 elements
392
 * with the same id.
393
 *
394
 * @param $variables
395
 *   An associative array containing:
396
 *   - element: A render element representing the file.
397
 *
398
 * @return string
399
 *   The HTML.
400
 */
401
function theme_webform_managed_file($variables) {
402
  $element = $variables['element'];
403

    
404
  $attributes = array();
405

    
406
  // For webform use, do not add the id to the wrapper.
407
  // @code
408
  // if (isset($element['#id'])) {
409
  //   $attributes['id'] = $element['#id'];
410
  // }
411
  // @endcode
412
  if (!empty($element['#attributes']['class'])) {
413
    $attributes['class'] = (array) $element['#attributes']['class'];
414
  }
415
  $attributes['class'][] = 'form-managed-file';
416

    
417
  // This wrapper is required to apply JS behaviors and CSS styling.
418
  $output = '';
419
  $output .= '<div' . drupal_attributes($attributes) . '>';
420
  $output .= drupal_render_children($element);
421
  $output .= '</div>';
422
  return $output;
423
}
424

    
425
/**
426
 * Implements _webform_submit_component().
427
 */
428
function _webform_submit_file($component, $value) {
429
  $fid = is_array($value)
430
            ? (!empty($value['fid']) ? $value['fid'] : '')
431
            : (!empty($value) ? $value : '');
432
  // Extend access to this file, even if the submission has not been saved yet. This may happen when
433
  // previewing a private file which was selected but not explicitly uploaded, and then previewed.
434
  if ($fid) {
435
    $_SESSION['webform_files'][$fid] = $fid;
436
  }
437
  return $fid;
438
}
439

    
440
/**
441
 * Pre-render callback to allow access to uploaded files.
442
 *
443
 * Files that have not yet been saved into a submission must be accessible to
444
 * the user who uploaded it, but no one else. After the submission is saved,
445
 * access is granted through the file_usage table. Before then, we use a
446
 * $_SESSION value to record a user's upload.
447
 *
448
 * @see webform_file_download()
449
 */
450
function webform_file_allow_access($element) {
451
  if (!empty($element['#value']['fid'])) {
452
    $fid = $element['#value']['fid'];
453
    $_SESSION['webform_files'][$fid] = $fid;
454
  }
455

    
456
  return $element;
457
}
458

    
459
/**
460
 * Implements _webform_display_component().
461
 */
462
function _webform_display_file($component, $value, $format = 'html', $submission = array()) {
463
  $fid = isset($value[0]) ? $value[0] : NULL;
464
  return array(
465
    '#title' => $component['name'],
466
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
467
    '#value' => $fid ? webform_get_file($fid) : NULL,
468
    '#weight' => $component['weight'],
469
    '#theme' => 'webform_display_file',
470
    '#theme_wrappers' => $format == 'text' ? array('webform_element_text') : array('webform_element'),
471
    '#format' => $format,
472
    '#translatable' => array('title'),
473
  );
474
}
475

    
476
/**
477
 * Format the output of text data for this component.
478
 */
479
function theme_webform_display_file($variables) {
480
  $element = $variables['element'];
481

    
482
  $file = $element['#value'];
483
  $url = !empty($file) ? webform_file_url($file->uri) : t('no upload');
484
  return !empty($file) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url)) : ' ';
485
}
486

    
487
/**
488
 * Implements _webform_delete_component().
489
 */
490
function _webform_delete_file($component, $value) {
491
  // Delete an individual submission file.
492
  if (!empty($value[0]) && ($file = webform_get_file($value[0]))) {
493
    file_usage_delete($file, 'webform');
494
    file_delete($file);
495
  }
496
}
497

    
498
/**
499
 * Implements _webform_attachments_component().
500
 */
501
function _webform_attachments_file($component, $value) {
502
  $file = (array) webform_get_file($value[0]);
503
  $files = array($file);
504
  return $files;
505
}
506

    
507
/**
508
 * Implements _webform_analysis_component().
509
 */
510
function _webform_analysis_file($component, $sids = array(), $single = FALSE, $join = NULL) {
511
  $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
512
    ->fields('wsd', array('no', 'data'))
513
    ->condition('wsd.nid', $component['nid'])
514
    ->condition('wsd.cid', $component['cid']);
515

    
516
  if (count($sids)) {
517
    $query->condition('wsd.sid', $sids, 'IN');
518
  }
519

    
520
  if ($join) {
521
    $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
522
  }
523

    
524
  $nonblanks = 0;
525
  $sizetotal = 0;
526
  $submissions = 0;
527

    
528
  $result = $query->execute();
529
  foreach ($result as $data) {
530
    $file = webform_get_file($data['data']);
531
    if (isset($file->filesize)) {
532
      $nonblanks++;
533
      $sizetotal += $file->filesize;
534
    }
535
    $submissions++;
536
  }
537

    
538
  $rows[0] = array(t('Left Blank'), ($submissions - $nonblanks));
539
  $rows[1] = array(t('User uploaded file'), $nonblanks);
540
  $other[0] = array(t('Average uploaded file size'), ($sizetotal != 0 ? (int) (($sizetotal / $nonblanks) / 1024) . ' KB' : '0'));
541
  return array(
542
    'table_rows' => $rows,
543
    'other_data' => $other,
544
  );
545
}
546

    
547
/**
548
 * Implements _webform_table_component().
549
 */
550
function _webform_table_file($component, $value) {
551
  $output = '';
552
  $file = webform_get_file($value[0]);
553
  if (!empty($file->fid)) {
554
    $output = '<a href="' . webform_file_url($file->uri) . '">' . check_plain(webform_file_name($file->uri)) . '</a>';
555
    $output .= ' (' . (int) ($file->filesize / 1024) . ' KB)';
556
  }
557
  return $output;
558
}
559

    
560
/**
561
 * Implements _webform_csv_headers_component().
562
 */
563
function _webform_csv_headers_file($component, $export_options) {
564
  $header = array();
565
  // Two columns in header.
566
  $header[0] = array('', '');
567
  $header[1] = array($export_options['header_keys'] ? $component['form_key'] : $component['name'], '');
568
  $header[2] = array(t('Name'), t('Filesize (KB)'));
569
  return $header;
570
}
571

    
572
/**
573
 * Implements _webform_csv_data_component().
574
 */
575
function _webform_csv_data_file($component, $export_options, $value) {
576
  $file = webform_get_file($value[0]);
577
  return empty($file->filename) ? array('', '') : array(webform_file_url($file->uri), (int) ($file->filesize / 1024));
578
}
579

    
580
/**
581
 * Helper function to create proper file names for uploaded file.
582
 */
583
function webform_file_name($filepath) {
584
  if (!empty($filepath)) {
585
    $info = pathinfo($filepath);
586
    $file_name = $info['basename'];
587
  }
588
  return isset($file_name) ? $file_name : '';
589
}
590

    
591
/**
592
 * Helper function to create proper URLs for uploaded file.
593
 */
594
function webform_file_url($uri) {
595
  if (!empty($uri)) {
596
    $file_url = file_create_url($uri);
597
  }
598
  return isset($file_url) ? $file_url : '';
599
}
600

    
601
/**
602
 * Helper function to load a file from the database.
603
 */
604
function webform_get_file($fid) {
605
  // Simple check to prevent loading of NULL values, which throws an entity
606
  // system error.
607
  return $fid ? file_load($fid) : FALSE;
608
}
609

    
610
/**
611
 * Given a submission with file_usage set, add or remove file usage entries.
612
 */
613
function webform_file_usage_adjust($submission) {
614
  if (isset($submission->file_usage)) {
615
    $files = file_load_multiple($submission->file_usage['added_fids']);
616
    foreach ($files as $file) {
617
      $file->status = 1;
618
      file_save($file);
619
      file_usage_add($file, 'webform', 'submission', $submission->sid);
620
    }
621

    
622
    $files = file_load_multiple($submission->file_usage['deleted_fids']);
623
    foreach ($files as $file) {
624
      file_usage_delete($file, 'webform', 'submission', $submission->sid);
625
      file_delete($file);
626
    }
627
  }
628
}
629

    
630
/**
631
 * Rename any files which are eligible for renaming.
632
 *
633
 * Renames if this submission is being submitted for the first time.
634
 */
635
function webform_file_rename($node, $submission) {
636
  if (isset($submission->file_usage)) {
637
    foreach ($submission->file_usage['renameable'] as $cid => $fids) {
638
      foreach ($fids as $fid) {
639
        webform_file_process_rename($node, $submission, $node->webform['components'][$cid], $fid);
640
      }
641
    }
642
  }
643
}
644

    
645
/**
646
 * Renames the uploaded file name using tokens.
647
 *
648
 * @param $node
649
 *   The webform node object.
650
 * @param $submission
651
 *   The webform submission object.
652
 * @param $component
653
 *   Component settings array for which fid is going to be processed.
654
 * @param $fid
655
 *   A file id to be processed.
656
 */
657
function webform_file_process_rename($node, $submission, $component, $fid) {
658
  $file = webform_get_file($fid);
659

    
660
  if ($file) {
661
    // Get the destination uri.
662
    $destination_dir = $component['extra']['scheme'] . '://webform/' . drupal_strtolower(webform_replace_tokens($component['extra']['directory'], $node));
663
    $destination_dir = file_stream_wrapper_uri_normalize($destination_dir);
664

    
665
    // Get the file extension.
666
    $info = pathinfo($file->uri);
667
    $extension = $info['extension'];
668

    
669
    // Prepare new file name without extension.
670
    $new_file_name = webform_replace_tokens($component['extra']['rename'], $node, $submission, NULL, TRUE);
671
    $new_file_name = trim($new_file_name);
672
    $new_file_name = _webform_transliterate($new_file_name);
673
    $new_file_name = str_replace('/', '_', $new_file_name);
674
    $new_file_name = preg_replace('/[^a-zA-Z0-9_\- ]/', '', $new_file_name);
675
    if (strlen($new_file_name)) {
676
      // Prepare the new uri with new filename.
677
      $destination = "$destination_dir/$new_file_name.$extension";
678

    
679
      // Compare the uri and Rename the file name.
680
      if ($file->uri != $destination) {
681
        file_move($file, $destination, FILE_EXISTS_RENAME);
682
      }
683
    }
684
  }
685
}