Projet

Général

Profil

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

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

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
  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
 */
393
function theme_webform_managed_file($variables) {
394
  $element = $variables['element'];
395

    
396
  $attributes = array();
397

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

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

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

    
416

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

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

    
448
  return $element;
449
}
450

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
637

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

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

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

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

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