Projet

Général

Profil

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

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

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 filesize. 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 allow to upload files @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
  $row = array();
317
  $title = $element['addextensions']['#title'];
318
  $element['addextensions']['#title'] = NULL;
319
  $row[] = array('data' => $title, 'colspan' => 2);
320
  $row[] = drupal_render($element['addextensions']);
321
  $rows[] = $row;
322

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

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

    
333
  return drupal_render_children($element);
334
}
335

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

    
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);
347
  }
348

    
349
  $element = array(
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'])),
360
    ),
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'),
370
  );
371

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

    
376
  return $element;
377
}
378

    
379
/**
380
 * Returns HTML for a webform managed file element.
381
 *
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
384
 * with the same id.
385
 *
386
 * @param $variables
387
 *   An associative array containing:
388
 *   - element: A render element representing the file.
389
 *
390
 */
391
function theme_webform_managed_file($variables) {
392
  $element = $variables['element'];
393

    
394
  $attributes = array();
395

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

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

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

    
414

    
415
/**
416
 * Implements _webform_submit_component().
417
 */
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.
424
  if ($fid) {
425
    $_SESSION['webform_files'][$fid] = $fid;
426
  }
427
  return $fid;
428
}
429

    
430
/**
431
 * Pre-render callback to allow access to uploaded files.
432
 *
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.
437
 *
438
 * @see webform_file_download()
439
 */
440
function webform_file_allow_access($element) {
441
  if (!empty($element['#value']['fid'])) {
442
    $fid = $element['#value']['fid'];
443
    $_SESSION['webform_files'][$fid] = $fid;
444
  }
445

    
446
  return $element;
447
}
448

    
449
/**
450
 * Implements _webform_display_component().
451
 */
452
function _webform_display_file($component, $value, $format = 'html', $submission = array()) {
453
  $fid = isset($value[0]) ? $value[0] : NULL;
454
  return array(
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'),
463
  );
464
}
465

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

    
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)) : ' ';
475
}
476

    
477
/**
478
 * Implements _webform_delete_component().
479
 */
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');
484
    file_delete($file);
485
  }
486
}
487

    
488
/**
489
 * Implements _webform_attachments_component().
490
 */
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);
496
  return $files;
497
}
498
/**
499
 * Implements _webform_analysis_component().
500
 */
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']);
506

    
507
  if (count($sids)) {
508
    $query->condition('wsd.sid', $sids, 'IN');
509
  }
510

    
511
  if ($join) {
512
    $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
513
  }
514

    
515
  $nonblanks = 0;
516
  $sizetotal = 0;
517
  $submissions = 0;
518

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

    
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'));
532
  return array(
533
    'table_rows' => $rows,
534
    'other_data' => $other,
535
  );
536
}
537

    
538
/**
539
 * Implements _webform_table_component().
540
 */
541
function _webform_table_file($component, $value) {
542
  $output = '';
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)';
547
  }
548
  return $output;
549
}
550

    
551
/**
552
 * Implements _webform_csv_headers_component().
553
 */
554
function _webform_csv_headers_file($component, $export_options) {
555
  $header = array();
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)'));
560
  return $header;
561
}
562

    
563
/**
564
 * Implements _webform_csv_data_component().
565
 */
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));
569
}
570

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

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

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

    
601
/**
602
 * Given a submission with file_usage set, add or remove file usage entries.
603
 */
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) {
608
      $file->status = 1;
609
      file_save($file);
610
      file_usage_add($file, 'webform', 'submission', $submission->sid);
611
    }
612

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

    
621
/**
622
 * Rename any files which are eligible for renaming, if this submission is being
623
 * submitted for the first time.
624
 */
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);
630
      }
631
    }
632
  }
633
}
634

    
635

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

    
651
  if ($file) {
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);
655

    
656
    // Get the file extension.
657
    $info = pathinfo($file->uri);
658
    $extension = $info['extension'];
659

    
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";
669

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