Projet

Général

Profil

Paste
Télécharger (23,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / webform / components / file.inc @ 8d02775b

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
  return $form;
195
}
196

    
197
/**
198
 * Form API validator ensures rename string is empty or contains one token.
199
 *
200
 * A Form API element validate function to ensure that the rename string is
201
 * either empty or contains at least one token.
202
 */
203
function _webform_edit_file_rename_validate($element, &$form_state, $form) {
204
  $rename = trim($form_state['values']['extra']['rename']);
205
  form_set_value($element, $rename, $form_state);
206
  if (strlen($rename) && !count(token_scan($rename))) {
207
    form_error($element, t('To create unique file names, use at least one token in the file name pattern.'));
208
  }
209
}
210

    
211
/**
212
 * A Form API element validate function to check filesize is valid.
213
 */
214
function _webform_edit_file_size_validate($element) {
215
  if (!empty($element['#value'])) {
216
    $set_filesize = parse_size($element['#value']);
217
    if ($set_filesize == FALSE) {
218
      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'])));
219
    }
220
    else {
221
      $max_filesize = parse_size(file_upload_max_size());
222
      if ($max_filesize < $set_filesize) {
223
        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))));
224
      }
225
    }
226
  }
227
}
228

    
229
/**
230
 * A Form API after build and validate function.
231
 *
232
 * Ensure that the destination directory exists and is writable.
233
 */
234
function _webform_edit_file_check_directory($element) {
235
  $scheme = $element['extra']['scheme']['#value'];
236
  $directory = $element['extra']['directory']['#value'];
237

    
238
  $destination_dir = file_stream_wrapper_uri_normalize($scheme . '://webform/' . $directory);
239
  $tokenized_dir = drupal_strtolower(webform_replace_tokens($destination_dir, $element['#node']));
240

    
241
  // Sanity check input to prevent use parent (../) directories.
242
  if (preg_match('/\.\.[\/\\\]/', $tokenized_dir . '/')) {
243
    form_error($element['extra']['directory'], t('The save directory %directory is not valid.', array('%directory' => $tokenized_dir)));
244
  }
245
  else {
246
    if (!file_prepare_directory($tokenized_dir, FILE_CREATE_DIRECTORY)) {
247
      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)));
248
    }
249
  }
250

    
251
  return $element;
252
}
253

    
254
/**
255
 * A Form API element validate function.
256
 *
257
 * Change the submitted values of the component so that all filtering extensions
258
 * are saved as a single array.
259
 */
260
function _webform_edit_file_extensions_validate($element, &$form_state) {
261
  // Predefined types.
262
  $extensions = array();
263
  foreach (element_children($element['types']) as $category) {
264
    foreach (array_keys($element['types'][$category]['#value']) as $extension) {
265
      if ($element['types'][$category][$extension]['#value']) {
266
        $extensions[] = $extension;
267
        // "jpeg" is an exception. It is allowed anytime "jpg" is allowed.
268
        if ($extension == 'jpg') {
269
          $extensions[] = 'jpeg';
270
        }
271
      }
272
    }
273
  }
274

    
275
  // Additional types.
276
  $additional_extensions = explode(',', $element['addextensions']['#value']);
277
  foreach ($additional_extensions as $extension) {
278
    $clean_extension = drupal_strtolower(trim($extension));
279
    if (!empty($clean_extension) && !in_array($clean_extension, $extensions)) {
280
      $extensions[] = $clean_extension;
281
    }
282
  }
283

    
284
  form_set_value($element['types'], $extensions, $form_state);
285
}
286

    
287
/**
288
 * Output the list of allowed extensions as checkboxes.
289
 */
290
function theme_webform_edit_file_extensions($variables) {
291
  $element = $variables['element'];
292

    
293
  // Format the components into a table.
294
  $rows = array();
295
  foreach (element_children($element['types']) as $filtergroup) {
296
    $row = array();
297
    if ($element['types'][$filtergroup]['#type'] == 'checkboxes') {
298
      $select_link = ' <a href="#" class="webform-select-link webform-select-link-' . $filtergroup . '">(' . t('select') . ')</a>';
299
      $row[] = $element['types'][$filtergroup]['#title'];
300
      $row[] = array('data' => $select_link, 'width' => 40);
301
      $row[] = array('data' => drupal_render_children($element['types'][$filtergroup]), 'class' => array('webform-file-extensions', 'webform-select-group-' . $filtergroup));
302
      $rows[] = array('data' => $row);
303
      unset($element['types'][$filtergroup]);
304
    }
305
  }
306

    
307
  // Add the row for additional types.
308
  if (!isset($element['addextensions']['#access']) || $element['addextensions']['#access']) {
309
    $row = array();
310
    $title = $element['addextensions']['#title'];
311
    $element['addextensions']['#title'] = NULL;
312
    $row[] = array('data' => $title, 'colspan' => 2);
313
    $row[] = drupal_render($element['addextensions']);
314
    $rows[] = $row;
315
  }
316

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

    
319
  // Create the table inside the form.
320
  $element['types']['table'] = array(
321
    '#theme' => 'table',
322
    '#header' => $header,
323
    '#rows' => $rows,
324
    '#attributes' => array('class' => array('webform-file-extensions')),
325
  );
326

    
327
  return drupal_render_children($element);
328
}
329

    
330
/**
331
 * Implements _webform_render_component().
332
 */
333
function _webform_render_file($component, $value = NULL, $filter = TRUE, $submission = NULL) {
334
  $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
335

    
336
  // Cap the upload size according to the PHP limit.
337
  $max_filesize = parse_size(file_upload_max_size());
338
  $set_filesize = $component['extra']['filtering']['size'];
339
  if (!empty($set_filesize) && parse_size($set_filesize) < $max_filesize) {
340
    $max_filesize = parse_size($set_filesize);
341
  }
342

    
343
  $element = array(
344
    '#type' => 'managed_file',
345
    '#theme' => 'webform_managed_file',
346
    '#title' => $filter ? webform_filter_xss($component['name']) : $component['name'],
347
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
348
    '#required' => $component['required'],
349
    '#default_value' => isset($value[0]) ? $value[0] : NULL,
350
    '#attributes' => $component['extra']['attributes'],
351
    '#upload_validators' => array(
352
      'file_validate_size' => array($max_filesize),
353
      'file_validate_extensions' => array(implode(' ', $component['extra']['filtering']['types'])),
354
    ),
355
    '#pre_render' => array_merge(element_info_property('managed_file', '#pre_render'), array('webform_file_allow_access')),
356
    '#upload_location' => $component['extra']['scheme'] . '://webform/' . ($filter
357
                                                                              ? drupal_strtolower(webform_replace_tokens($component['extra']['directory'], $node))
358
                                                                              : $component['extra']['directory']),
359
    '#progress_indicator' => $component['extra']['progress_indicator'],
360
    '#description' => $filter ? webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
361
    '#weight' => $component['weight'],
362
    '#theme_wrappers' => array('webform_element'),
363
    '#translatable' => array('title', 'description'),
364
  );
365

    
366
  if ($filter) {
367
    $element['#description'] = theme('file_upload_help', array('description' => $element['#description'], 'upload_validators' => $element['#upload_validators']));
368
  }
369

    
370
  return $element;
371
}
372

    
373
/**
374
 * Returns HTML for a webform managed file element.
375
 *
376
 * See #2495821 and #2497909. The core theme_file_managed_file creates a
377
 * wrapper around the element with the element's id, thereby creating 2 elements
378
 * with the same id.
379
 *
380
 * @param array $variables
381
 *   An associative array containing:
382
 *   - element: A render element representing the file.
383
 *
384
 * @return string
385
 *   The HTML.
386
 */
387
function theme_webform_managed_file($variables) {
388
  $element = $variables['element'];
389

    
390
  $attributes = array();
391

    
392
  // For webform use, do not add the id to the wrapper.
393
  // @code
394
  // if (isset($element['#id'])) {
395
  //   $attributes['id'] = $element['#id'];
396
  // }
397
  // @endcode
398
  if (!empty($element['#attributes']['class'])) {
399
    $attributes['class'] = (array) $element['#attributes']['class'];
400
  }
401
  $attributes['class'][] = 'form-managed-file';
402

    
403
  // This wrapper is required to apply JS behaviors and CSS styling.
404
  $output = '';
405
  $output .= '<div' . drupal_attributes($attributes) . '>';
406
  $output .= drupal_render_children($element);
407
  $output .= '</div>';
408
  return $output;
409
}
410

    
411
/**
412
 * Implements _webform_submit_component().
413
 */
414
function _webform_submit_file($component, $value) {
415
  $fid = is_array($value)
416
            ? (!empty($value['fid']) ? $value['fid'] : '')
417
            : (!empty($value) ? $value : '');
418
  // Extend access to this file, even if the submission has not been saved yet.
419
  // This may happen when previewing a private file which was selected but not
420
  // explicitly uploaded, and then previewed.
421
  if ($fid) {
422
    $_SESSION['webform_files'][$fid] = $fid;
423
  }
424
  return $fid;
425
}
426

    
427
/**
428
 * Pre-render callback to allow access to uploaded files.
429
 *
430
 * Files that have not yet been saved into a submission must be accessible to
431
 * the user who uploaded it, but no one else. After the submission is saved,
432
 * access is granted through the file_usage table. Before then, we use a
433
 * $_SESSION value to record a user's upload.
434
 *
435
 * @see webform_file_download()
436
 */
437
function webform_file_allow_access($element) {
438
  if (!empty($element['#value']['fid'])) {
439
    $fid = $element['#value']['fid'];
440
    $_SESSION['webform_files'][$fid] = $fid;
441
  }
442

    
443
  return $element;
444
}
445

    
446
/**
447
 * Implements _webform_display_component().
448
 */
449
function _webform_display_file($component, $value, $format = 'html', $submission = array()) {
450
  $fid = isset($value[0]) ? $value[0] : NULL;
451
  return array(
452
    '#title' => $component['name'],
453
    '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
454
    '#value' => $fid ? webform_get_file($fid) : NULL,
455
    '#weight' => $component['weight'],
456
    '#theme' => 'webform_display_file',
457
    '#theme_wrappers' => $format == 'text' ? array('webform_element_text') : array('webform_element'),
458
    '#format' => $format,
459
    '#translatable' => array('title'),
460
  );
461
}
462

    
463
/**
464
 * Format the output of text data for this component.
465
 */
466
function theme_webform_display_file($variables) {
467
  $element = $variables['element'];
468

    
469
  $file = $element['#value'];
470
  $url = !empty($file) ? webform_file_url($file->uri) : t('no upload');
471
  return !empty($file) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url)) : ' ';
472
}
473

    
474
/**
475
 * Implements _webform_delete_component().
476
 */
477
function _webform_delete_file($component, $value) {
478
  // Delete an individual submission file.
479
  if (!empty($value[0]) && ($file = webform_get_file($value[0]))) {
480
    file_usage_delete($file, 'webform');
481
    file_delete($file);
482
  }
483
}
484

    
485
/**
486
 * Implements _webform_attachments_component().
487
 */
488
function _webform_attachments_file($component, $value) {
489
  $file = (array) webform_get_file($value[0]);
490
  $files = array($file);
491
  return $files;
492
}
493

    
494
/**
495
 * Implements _webform_analysis_component().
496
 */
497
function _webform_analysis_file($component, $sids = array(), $single = FALSE, $join = NULL) {
498
  $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
499
    ->fields('wsd', array('no', 'data'))
500
    ->condition('wsd.nid', $component['nid'])
501
    ->condition('wsd.cid', $component['cid']);
502

    
503
  if (count($sids)) {
504
    $query->condition('wsd.sid', $sids, 'IN');
505
  }
506

    
507
  if ($join) {
508
    $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
509
  }
510

    
511
  $nonblanks = 0;
512
  $sizetotal = 0;
513
  $submissions = 0;
514

    
515
  $result = $query->execute();
516
  foreach ($result as $data) {
517
    $file = webform_get_file($data['data']);
518
    if (isset($file->filesize)) {
519
      $nonblanks++;
520
      $sizetotal += $file->filesize;
521
    }
522
    $submissions++;
523
  }
524

    
525
  $rows[0] = array(t('Left Blank'), ($submissions - $nonblanks));
526
  $rows[1] = array(t('User uploaded file'), $nonblanks);
527
  $other[0] = array(t('Average uploaded file size'), ($sizetotal != 0 ? (int) (($sizetotal / $nonblanks) / 1024) . ' KB' : '0'));
528
  return array(
529
    'table_rows' => $rows,
530
    'other_data' => $other,
531
  );
532
}
533

    
534
/**
535
 * Implements _webform_table_component().
536
 */
537
function _webform_table_file($component, $value) {
538
  $output = '';
539
  $file = webform_get_file($value[0]);
540
  if (!empty($file->fid)) {
541
    $output = '<a href="' . webform_file_url($file->uri) . '">' . check_plain(webform_file_name($file->uri)) . '</a>';
542
    $output .= ' (' . (int) ($file->filesize / 1024) . ' KB)';
543
  }
544
  return $output;
545
}
546

    
547
/**
548
 * Implements _webform_csv_headers_component().
549
 */
550
function _webform_csv_headers_file($component, $export_options) {
551
  $header = array();
552
  // Two columns in header.
553
  $header[0] = array('', '');
554
  $header[1] = array($export_options['header_keys'] ? $component['form_key'] : $component['name'], '');
555
  $header[2] = array(t('Name'), t('Filesize (KB)'));
556
  return $header;
557
}
558

    
559
/**
560
 * Implements _webform_csv_data_component().
561
 */
562
function _webform_csv_data_file($component, $export_options, $value) {
563
  $file = webform_get_file($value[0]);
564
  return empty($file->filename) ? array('', '') : array(webform_file_url($file->uri), (int) ($file->filesize / 1024));
565
}
566

    
567
/**
568
 * Helper function to create proper file names for uploaded file.
569
 */
570
function webform_file_name($filepath) {
571
  if (!empty($filepath)) {
572
    $info = pathinfo($filepath);
573
    $file_name = $info['basename'];
574
  }
575
  return isset($file_name) ? $file_name : '';
576
}
577

    
578
/**
579
 * Helper function to create proper URLs for uploaded file.
580
 */
581
function webform_file_url($uri) {
582
  if (!empty($uri)) {
583
    $file_url = file_create_url($uri);
584
  }
585
  return isset($file_url) ? $file_url : '';
586
}
587

    
588
/**
589
 * Helper function to load a file from the database.
590
 */
591
function webform_get_file($fid) {
592
  // Simple check to prevent loading of NULL values, which throws an entity
593
  // system error.
594
  return $fid ? file_load($fid) : FALSE;
595
}
596

    
597
/**
598
 * Given a submission with file_usage set, add or remove file usage entries.
599
 */
600
function webform_file_usage_adjust($submission) {
601
  if (isset($submission->file_usage)) {
602
    $files = file_load_multiple($submission->file_usage['added_fids']);
603
    foreach ($files as $file) {
604
      $file->status = 1;
605
      file_save($file);
606
      file_usage_add($file, 'webform', 'submission', $submission->sid);
607
    }
608

    
609
    $files = file_load_multiple($submission->file_usage['deleted_fids']);
610
    foreach ($files as $file) {
611
      file_usage_delete($file, 'webform', 'submission', $submission->sid);
612
      file_delete($file);
613
    }
614
  }
615
}
616

    
617
/**
618
 * Rename any files which are eligible for renaming.
619
 *
620
 * Renames if this submission is being submitted for the first time.
621
 */
622
function webform_file_rename($node, $submission) {
623
  if (isset($submission->file_usage)) {
624
    foreach ($submission->file_usage['renameable'] as $cid => $fids) {
625
      foreach ($fids as $fid) {
626
        webform_file_process_rename($node, $submission, $node->webform['components'][$cid], $fid);
627
      }
628
    }
629
  }
630
}
631

    
632
/**
633
 * Renames the uploaded file name using tokens.
634
 *
635
 * @param object $node
636
 *   The webform node object.
637
 * @param object $submission
638
 *   The webform submission object.
639
 * @param array $component
640
 *   Component settings array for which fid is going to be processed.
641
 * @param int $fid
642
 *   A file id to be processed.
643
 */
644
function webform_file_process_rename($node, $submission, $component, $fid) {
645
  $file = webform_get_file($fid);
646

    
647
  if ($file) {
648
    // Get the destination uri.
649
    $destination_dir = $component['extra']['scheme'] . '://webform/' . drupal_strtolower(webform_replace_tokens($component['extra']['directory'], $node));
650
    $destination_dir = file_stream_wrapper_uri_normalize($destination_dir);
651

    
652
    // Get the file extension.
653
    $info = pathinfo($file->uri);
654
    $extension = $info['extension'];
655

    
656
    // Prepare new file name without extension.
657
    $new_file_name = webform_replace_tokens($component['extra']['rename'], $node, $submission, NULL, TRUE);
658
    $new_file_name = trim($new_file_name);
659
    $new_file_name = _webform_transliterate($new_file_name);
660
    $new_file_name = str_replace('/', '_', $new_file_name);
661
    $new_file_name = preg_replace('/[^a-zA-Z0-9_\- ]/', '', $new_file_name);
662
    if (strlen($new_file_name)) {
663
      // Prepare the new uri with new filename.
664
      $destination = "$destination_dir/$new_file_name.$extension";
665

    
666
      // Compare the uri and Rename the file name.
667
      if ($file->uri != $destination) {
668
        file_move($file, $destination, FILE_EXISTS_RENAME);
669
      }
670
    }
671
  }
672
}