Projet

Général

Profil

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

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

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
  return array(
13
    'name' => '',
14
    'form_key' => NULL,
15
    'required' => 0,
16
    'pid' => 0,
17
    'weight' => 0,
18
    'extra' => array(
19
      'filtering' => array(
20
        'types' => array('gif', 'jpg', 'png'),
21
        'addextensions' => '',
22
        'size' => '2 MB',
23
      ),
24
      'rename' => '',
25
      'scheme' => 'public',
26
      'directory' => '',
27
      'progress_indicator' => 'throbber',
28
      'title_display' => 0,
29
      'description' => '',
30
      'description_above' => FALSE,
31
      'attributes' => array(),
32
      'private' => FALSE,
33
      'analysis' => FALSE,
34
    ),
35
  );
36
}
37

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

    
58
/**
59
 * Implements _webform_edit_component().
60
 */
61
function _webform_edit_file($component) {
62
    $form = array();
63
    $form['#element_validate'] = array('_webform_edit_file_check_directory');
64
    $form['#after_build'] = array('_webform_edit_file_check_directory');
65

    
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()))),
71
      '#size' => 10,
72
      '#parents' => array('extra', 'filtering', 'size'),
73
      '#element_validate' => array('_webform_edit_file_size_validate'),
74
      '#weight' => 1,
75
    );
76

    
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'),
83
      '#attached' => array(
84
        'js' => array(drupal_get_path('module', 'webform') . '/js/webform-admin.js'),
85
        'css' => array(drupal_get_path('module', 'webform') . '/css/webform-admin.css'),
86
      ),
87
      '#type' => 'webform_file_extensions',
88
      '#weight' => 2,
89
    );
90

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

    
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),
100
    );
101

    
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),
108
    );
109

    
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),
116
    );
117

    
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),
124
    );
125

    
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),
132
    );
133

    
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.'),
139
      '#size' => 20,
140
      '#weight' => 3,
141
    );
142

    
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'];
146
    }
147
    $form['extra']['scheme'] = array(
148
      '#type' => 'radios',
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.'),
153
      '#weight' => 4,
154
      '#access' => count($scheme_options) > 1,
155
    );
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'),
161
      '#weight' => 5,
162
      '#field_prefix' => 'webform/',
163
    );
164

    
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'))),
170
      '#weight' => 6,
171
      '#element_validate' => array('_webform_edit_file_rename_validate'),
172
      '#access' => webform_variable_get('webform_token_access'),
173
    );
174

    
175
    $form['display']['progress_indicator'] = array(
176
      '#type' => 'radios',
177
      '#title' => t('Progress indicator'),
178
      '#options' => array(
179
        'throbber' => t('Throbber'),
180
        'bar' => t('Bar with progress meter'),
181
      ),
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.'),
184
      '#weight' => 16,
185
      '#access' => file_progress_implementation(),
186
      '#parents' => array('extra', 'progress_indicator'),
187
    );
188

    
189
    // TODO: Make managed_file respect the "size" parameter.
190
    /*
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.'),
196
      '#size' => 5,
197
      '#maxlength' => 10,
198
      '#weight' => 4,
199
      '#parents' => array('extra', 'width')
200
    );
201
    */
202

    
203
    return $form;
204
}
205

    
206
/**
207
 * A Form API element validate function to ensure that the rename string is
208
 * either empty or contains at least one token.
209
 */
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.'));
215
  }
216
}
217

    
218
/**
219
 * A Form API element validate function to check filesize is valid.
220
 */
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 file size. Use a value such as 2 MB or 800 KB.', array('@value' => $element['#value'])));
226
    }
227
    else {
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 allowed to upload files that are @max or less.', array('@value' => $element['#value'], '@max' => format_size($max_filesize))));
231
      }
232
    }
233
  }
234
}
235

    
236
/**
237
 * A Form API after build and validate function.
238
 *
239
 * Ensure that the destination directory exists and is writable.
240
 */
241
function _webform_edit_file_check_directory($element) {
242
  $scheme = $element['extra']['scheme']['#value'];
243
  $directory = $element['extra']['directory']['#value'];
244

    
245
  $destination_dir = file_stream_wrapper_uri_normalize($scheme . '://webform/' . $directory);
246
  $tokenized_dir = drupal_strtolower(webform_replace_tokens($destination_dir, $element['#node']));
247

    
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)));
251
  }
252
  else {
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)));
255
    }
256
  }
257

    
258
  return $element;
259
}
260

    
261
/**
262
 * A Form API element validate function.
263
 *
264
 * Change the submitted values of the component so that all filtering extensions
265
 * are saved as a single array.
266
 */
267
function _webform_edit_file_extensions_validate($element, &$form_state) {
268
  // Predefined types.
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';
277
        }
278
      }
279
    }
280
  }
281

    
282
  // Additional types.
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;
288
    }
289
  }
290

    
291
  form_set_value($element['types'], $extensions, $form_state);
292
}
293

    
294
/**
295
 * Output the list of allowed extensions as checkboxes.
296
 */
297
function theme_webform_edit_file_extensions($variables) {
298
  $element = $variables['element'];
299

    
300
  // Format the components into a table.
301
  $rows = array();
302
  foreach (element_children($element['types']) as $filtergroup) {
303
    $row = array();
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]);
312
    }
313
  }
314

    
315
  // Add the row for additional types.
316
  if (!isset($element['addextensions']['#access']) || $element['addextensions']['#access']) {
317
    $row = array();
318
    $title = $element['addextensions']['#title'];
319
    $element['addextensions']['#title'] = NULL;
320
    $row[] = array('data' => $title, 'colspan' => 2);
321
    $row[] = drupal_render($element['addextensions']);
322
    $rows[] = $row;
323
  }
324

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

    
327
  // Create the table inside the form.
328
  $element['types']['table'] = array(
329
    '#theme' => 'table',
330
    '#header' => $header,
331
    '#rows' => $rows,
332
    '#attributes' => array('class' => array('webform-file-extensions')),
333
  );
334

    
335
  return drupal_render_children($element);
336
}
337

    
338
/**
339
 * Implements _webform_render_component().
340
 */
341
function _webform_render_file($component, $value = NULL, $filter = TRUE, $submission = NULL) {
342
  $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
343

    
344
  // Cap the upload size according to the PHP limit.
345
  $max_filesize = parse_size(file_upload_max_size());
346
  $set_filesize = $component['extra']['filtering']['size'];
347
  if (!empty($set_filesize) && parse_size($set_filesize) < $max_filesize) {
348
    $max_filesize = parse_size($set_filesize);
349
  }
350

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

    
374
  if ($filter) {
375
    $element['#description'] = theme('file_upload_help', array('description' => $element['#description'], 'upload_validators' => $element['#upload_validators']));
376
  }
377

    
378
  return $element;
379
}
380

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

    
397
  $attributes = array();
398

    
399
  // For webform use, do not add the id to the wrapper.
400
  //if (isset($element['#id'])) {
401
  //  $attributes['id'] = $element['#id'];
402
  //}
403

    
404
  if (!empty($element['#attributes']['class'])) {
405
    $attributes['class'] = (array) $element['#attributes']['class'];
406
  }
407
  $attributes['class'][] = 'form-managed-file';
408

    
409
  // This wrapper is required to apply JS behaviors and CSS styling.
410
  $output = '';
411
  $output .= '<div' . drupal_attributes($attributes) . '>';
412
  $output .= drupal_render_children($element);
413
  $output .= '</div>';
414
  return $output;
415
}
416

    
417

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

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

    
449
  return $element;
450
}
451

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

    
469
/**
470
 * Format the output of text data for this component
471
 */
472
function theme_webform_display_file($variables) {
473
  $element = $variables['element'];
474

    
475
  $file = $element['#value'];
476
  $url = !empty($file) ? webform_file_url($file->uri) : t('no upload');
477
  return !empty($file) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url)) : ' ';
478
}
479

    
480
/**
481
 * Implements _webform_delete_component().
482
 */
483
function _webform_delete_file($component, $value) {
484
  // Delete an individual submission file.
485
  if (!empty($value[0]) && ($file = webform_get_file($value[0]))) {
486
    file_usage_delete($file, 'webform');
487
    file_delete($file);
488
  }
489
}
490

    
491
/**
492
 * Implements _webform_attachments_component().
493
 */
494
function _webform_attachments_file($component, $value) {
495
  $file = (array) webform_get_file($value[0]);
496
  //This is necessary until the next release of mimemail is out, see [#1388786]
497
  $file['filepath'] = $file['uri'];
498
  $files = array($file);
499
  return $files;
500
}
501
/**
502
 * Implements _webform_analysis_component().
503
 */
504
function _webform_analysis_file($component, $sids = array(), $single = FALSE, $join = NULL) {
505
  $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
506
    ->fields('wsd', array('no', 'data'))
507
    ->condition('wsd.nid', $component['nid'])
508
    ->condition('wsd.cid', $component['cid']);
509

    
510
  if (count($sids)) {
511
    $query->condition('wsd.sid', $sids, 'IN');
512
  }
513

    
514
  if ($join) {
515
    $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
516
  }
517

    
518
  $nonblanks = 0;
519
  $sizetotal = 0;
520
  $submissions = 0;
521

    
522
  $result = $query->execute();
523
  foreach ($result as $data) {
524
    $file = webform_get_file($data['data']);
525
    if (isset($file->filesize)) {
526
      $nonblanks++;
527
      $sizetotal += $file->filesize;
528
    }
529
    $submissions++;
530
  }
531

    
532
  $rows[0] = array(t('Left Blank'), ($submissions - $nonblanks));
533
  $rows[1] = array(t('User uploaded file'), $nonblanks);
534
  $other[0] = array(t('Average uploaded file size'), ($sizetotal != 0 ? (int) (($sizetotal/$nonblanks)/1024) . ' KB' : '0'));
535
  return array(
536
    'table_rows' => $rows,
537
    'other_data' => $other,
538
  );
539
}
540

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

    
554
/**
555
 * Implements _webform_csv_headers_component().
556
 */
557
function _webform_csv_headers_file($component, $export_options) {
558
  $header = array();
559
  // Two columns in header.
560
  $header[0] = array('', '');
561
  $header[1] = array($export_options['header_keys'] ? $component['form_key'] : $component['name'], '');
562
  $header[2] = array(t('Name'), t('Filesize (KB)'));
563
  return $header;
564
}
565

    
566
/**
567
 * Implements _webform_csv_data_component().
568
 */
569
function _webform_csv_data_file($component, $export_options, $value) {
570
  $file = webform_get_file($value[0]);
571
  return empty($file->filename) ? array('', '') : array(webform_file_url($file->uri), (int) ($file->filesize/1024));
572
}
573

    
574
/**
575
 * Helper function to create proper file names for uploaded file.
576
 */
577
function webform_file_name($filepath) {
578
  if (!empty($filepath)) {
579
    $info = pathinfo($filepath);
580
    $file_name = $info['basename'];
581
  }
582
  return isset($file_name) ? $file_name : '';
583
}
584

    
585
/**
586
 * Helper function to create proper URLs for uploaded file.
587
 */
588
function webform_file_url($uri) {
589
  if (!empty($uri)) {
590
    $file_url = file_create_url($uri);
591
  }
592
  return isset($file_url) ? $file_url : '';
593
}
594

    
595
/**
596
 * Helper function to load a file from the database.
597
 */
598
function webform_get_file($fid) {
599
  // Simple check to prevent loading of NULL values, which throws an entity
600
  // system error.
601
  return $fid ? file_load($fid) : FALSE;
602
}
603

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

    
616
    $files = file_load_multiple($submission->file_usage['deleted_fids']);
617
    foreach ($files as $file) {
618
      file_usage_delete($file, 'webform', 'submission', $submission->sid);
619
      file_delete($file);
620
    }
621
  }
622
}
623

    
624
/**
625
 * Rename any files which are eligible for renaming, if this submission is being
626
 * submitted for the first time.
627
 */
628
function webform_file_rename($node, $submission) {
629
  if (isset($submission->file_usage)) {
630
    foreach ($submission->file_usage['renameable'] as $cid => $fids) {
631
      foreach ($fids as $fid) {
632
        webform_file_process_rename($node, $submission, $node->webform['components'][$cid], $fid);
633
      }
634
    }
635
  }
636
}
637

    
638

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

    
654
  if ($file) {
655
    // Get the destination uri.
656
    $destination_dir = $component['extra']['scheme'] . '://webform/' . drupal_strtolower(webform_replace_tokens($component['extra']['directory'], $node));
657
    $destination_dir = file_stream_wrapper_uri_normalize($destination_dir);
658

    
659
    // Get the file extension.
660
    $info = pathinfo($file->uri);
661
    $extension = $info['extension'];
662

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

    
673
      // Compare the uri and Rename the file name.
674
      if ($file->uri != $destination) {
675
        file_move($file, $destination, FILE_EXISTS_RENAME);
676
      }
677
    }
678
  }
679
}