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 @ cb17e347

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
      'attributes' => array(),
31
      'private' => FALSE,
32
      'analysis' => FALSE,
33
    ),
34
  );
35
}
36

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

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

    
65
    $form['validation']['size'] = array(
66
      '#type' => 'textfield',
67
      '#title' => t('Max upload size'),
68
      '#default_value' => $component['extra']['filtering']['size'],
69
      '#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()))),
70
      '#size' => 10,
71
      '#parents' => array('extra', 'filtering', 'size'),
72
      '#element_validate' => array('_webform_edit_file_size_validate'),
73
      '#weight' => 1,
74
    );
75

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

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

    
93
    $types = array('gif', 'jpg', 'png');
94
    $form['validation']['extensions']['types']['webimages'] = array(
95
      '#type' => 'checkboxes',
96
      '#title' => t('Web images'),
97
      '#options' => drupal_map_assoc($types),
98
      '#default_value' => array_intersect($current_types, $types),
99
    );
100

    
101
    $types = array('bmp', 'eps', 'tif', 'pict', 'psd');
102
    $form['validation']['extensions']['types']['desktopimages'] = array(
103
      '#type' => 'checkboxes',
104
      '#title' => t('Desktop images'),
105
      '#options' => drupal_map_assoc($types),
106
      '#default_value' => array_intersect($current_types, $types),
107
    );
108

    
109
    $types = array('txt', 'rtf', 'html', 'pdf', 'doc', 'docx', 'odt', 'ppt', 'pptx', 'odp', 'xls', 'xlsx', 'ods', 'xml');
110
    $form['validation']['extensions']['types']['documents'] = array(
111
      '#type' => 'checkboxes',
112
      '#title' => t('Documents'),
113
      '#options' => drupal_map_assoc($types),
114
      '#default_value' => array_intersect($current_types, $types),
115
    );
116

    
117
    $types = array('avi', 'mov', 'mp3', 'ogg', 'wav');
118
    $form['validation']['extensions']['types']['media'] = array(
119
      '#type' => 'checkboxes',
120
      '#title' => t('Media'),
121
      '#options' => drupal_map_assoc($types),
122
      '#default_value' => array_intersect($current_types, $types),
123
    );
124

    
125
    $types = array('bz2', 'dmg', 'gz', 'jar', 'rar', 'sit', 'tar', 'zip');
126
    $form['validation']['extensions']['types']['archives'] = array(
127
      '#type' => 'checkboxes',
128
      '#title' => t('Archives'),
129
      '#options' => drupal_map_assoc($types),
130
      '#default_value' => array_intersect($current_types, $types),
131
    );
132

    
133
    $form['validation']['extensions']['addextensions'] = array(
134
      '#type' => 'textfield',
135
      '#title' => t('Additional extensions'),
136
      '#default_value' => $component['extra']['filtering']['addextensions'],
137
      '#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.'),
138
      '#size' => 20,
139
      '#weight' => 3,
140
    );
141

    
142
    $scheme_options = array();
143
    foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $stream_wrapper) {
144
      $scheme_options[$scheme] = $stream_wrapper['name'];
145
    }
146
    $form['extra']['scheme'] = array(
147
      '#type' => 'radios',
148
      '#title' => t('Upload destination'),
149
      '#options' => $scheme_options,
150
      '#default_value' => $component['extra']['scheme'],
151
      '#description' => t('Private file storage has significantly more overhead than public files, but restricts file access to users who can view submissions.'),
152
      '#weight' => 4,
153
      '#access' => count($scheme_options) > 1,
154
    );
155
    $form['extra']['directory'] = array(
156
      '#type' => 'textfield',
157
      '#title' => t('Upload directory'),
158
      '#default_value' => $component['extra']['directory'],
159
      '#description' => t('You may optionally specify a sub-directory to store your files.') . ' ' . theme('webform_token_help'),
160
      '#weight' => 5,
161
      '#field_prefix' => 'webform/',
162
    );
163

    
164
    $form['extra']['rename'] = array(
165
      '#type' => 'textfield',
166
      '#title' => t('Rename files'),
167
      '#default_value' => $component['extra']['rename'],
168
      '#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'))),
169
      '#weight' => 6,
170
      '#element_validate' => array('_webform_edit_file_rename_validate'),
171
    );
172

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

    
187
    // TODO: Make managed_file respect the "size" parameter.
188
    /*
189
    $form['display']['width'] = array(
190
      '#type' => 'textfield',
191
      '#title' => t('Width'),
192
      '#default_value' => $component['extra']['width'],
193
      '#description' => t('Width of the file field.') . ' ' . t('Leaving blank will use the default size.'),
194
      '#size' => 5,
195
      '#maxlength' => 10,
196
      '#weight' => 4,
197
      '#parents' => array('extra', 'width')
198
    );
199
    */
200

    
201
    return $form;
202
}
203

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

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

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

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

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

    
256
  return $element;
257
}
258

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

    
280
  // Additional types.
281
  $additional_extensions = explode(',', $element['addextensions']['#value']);
282
  foreach ($additional_extensions as $extension) {
283
    $clean_extension = drupal_strtolower(trim($extension));
284
    if (!empty($clean_extension) && !in_array($clean_extension, $extensions)) {
285
      $extensions[] = $clean_extension;
286
    }
287
  }
288

    
289
  form_set_value($element['types'], $extensions, $form_state);
290
}
291

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

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

    
313
  // Add the row for additional types.
314
  $row = array();
315
  $title = $element['addextensions']['#title'];
316
  $element['addextensions']['#title'] = NULL;
317
  $row[] = array('data' => $title, 'colspan' => 2);
318
  $row[] = drupal_render($element['addextensions']);
319
  $rows[] = $row;
320

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

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

    
331
  return drupal_render_children($element);
332
}
333

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

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

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

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

    
374
  return $element;
375
}
376

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

    
392
  $attributes = array();
393

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

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

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

    
412

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

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

    
444
  return $element;
445
}
446

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

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

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

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

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

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

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

    
513
  $nonblanks = 0;
514
  $sizetotal = 0;
515
  $submissions = 0;
516

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

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

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

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

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

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

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

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

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

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

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

    
633

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

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

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

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

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