Projet

Général

Profil

Paste
Télécharger (34,8 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / file / file.field.inc @ b4adf10d

1
<?php
2

    
3
/**
4
 * @file
5
 * Field module functionality for the File module.
6
 */
7

    
8
/**
9
 * Implements hook_field_info().
10
 */
11
function file_field_info() {
12
  return array(
13
    'file' => array(
14
      'label' => t('File'),
15
      'description' => t('This field stores the ID of a file as an integer value.'),
16
      'settings' => array(
17
        'display_field' => 0,
18
        'display_default' => 0,
19
        'uri_scheme' => variable_get('file_default_scheme', 'public'),
20
      ),
21
      'instance_settings' => array(
22
        'file_extensions' => 'txt',
23
        'file_directory' => '',
24
        'max_filesize' => '',
25
        'description_field' => 0,
26
      ),
27
      'default_widget' => 'file_generic',
28
      'default_formatter' => 'file_default',
29
    ),
30
  );
31
}
32

    
33
/**
34
 * Implements hook_field_settings_form().
35
 */
36
function file_field_settings_form($field, $instance, $has_data) {
37
  $defaults = field_info_field_settings($field['type']);
38
  $settings = array_merge($defaults, $field['settings']);
39

    
40
  $form['#attached']['js'][] = drupal_get_path('module', 'file') . '/file.js';
41

    
42
  $form['display_field'] = array(
43
    '#type' => 'checkbox',
44
    '#title' => t('Enable <em>Display</em> field'),
45
    '#default_value' => $settings['display_field'],
46
    '#description' => t('The display option allows users to choose if a file should be shown when viewing the content.'),
47
  );
48
  $form['display_default'] = array(
49
    '#type' => 'checkbox',
50
    '#title' => t('Files displayed by default'),
51
    '#default_value' => $settings['display_default'],
52
    '#description' => t('This setting only has an effect if the display option is enabled.'),
53
  );
54

    
55
  $scheme_options = array();
56
  foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $stream_wrapper) {
57
    $scheme_options[$scheme] = $stream_wrapper['name'];
58
  }
59
  $form['uri_scheme'] = array(
60
    '#type' => 'radios',
61
    '#title' => t('Upload destination'),
62
    '#options' => $scheme_options,
63
    '#default_value' => $settings['uri_scheme'],
64
    '#description' => t('Select where the final files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
65
    '#disabled' => $has_data,
66
  );
67

    
68
  return $form;
69
}
70

    
71
/**
72
 * Implements hook_field_instance_settings_form().
73
 */
74
function file_field_instance_settings_form($field, $instance) {
75
  $settings = $instance['settings'];
76

    
77
  $form['file_directory'] = array(
78
    '#type' => 'textfield',
79
    '#title' => t('File directory'),
80
    '#default_value' => $settings['file_directory'],
81
    '#description' => t('Optional subdirectory within the upload destination where files will be stored. Do not include preceding or trailing slashes.'),
82
    '#element_validate' => array('_file_generic_settings_file_directory_validate'),
83
    '#weight' => 3,
84
  );
85

    
86
  // Make the extension list a little more human-friendly by comma-separation.
87
  $extensions = str_replace(' ', ', ', $settings['file_extensions']);
88
  $form['file_extensions'] = array(
89
    '#type' => 'textfield',
90
    '#title' => t('Allowed file extensions'),
91
    '#default_value' => $extensions,
92
    '#description' => t('Separate extensions with a space or comma and do not include the leading dot.'),
93
    '#element_validate' => array('_file_generic_settings_extensions'),
94
    '#weight' => 1,
95
    '#maxlength' => 256,
96
    // By making this field required, we prevent a potential security issue
97
    // that would allow files of any type to be uploaded.
98
    '#required' => TRUE,
99
  );
100

    
101
  $form['max_filesize'] = array(
102
    '#type' => 'textfield',
103
    '#title' => t('Maximum upload size'),
104
    '#default_value' => $settings['max_filesize'],
105
    '#description' => t('Enter a value like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes) in order to restrict the allowed file size. If left empty the file sizes will be limited only by PHP\'s maximum post and file upload sizes (current limit <strong>%limit</strong>).', array('%limit' => format_size(file_upload_max_size()))),
106
    '#size' => 10,
107
    '#element_validate' => array('_file_generic_settings_max_filesize'),
108
    '#weight' => 5,
109
  );
110

    
111
  $form['description_field'] = array(
112
    '#type' => 'checkbox',
113
    '#title' => t('Enable <em>Description</em> field'),
114
    '#default_value' => isset($settings['description_field']) ? $settings['description_field'] : '',
115
    '#description' => t('The description field allows users to enter a description about the uploaded file.'),
116
    '#parents' => array('instance', 'settings', 'description_field'),
117
    '#weight' => 11,
118
  );
119

    
120
  return $form;
121
}
122

    
123
/**
124
 * Element validate callback for the maximum upload size field.
125
 *
126
 * Ensure a size that can be parsed by parse_size() has been entered.
127
 */
128
function _file_generic_settings_max_filesize($element, &$form_state) {
129
  if (!empty($element['#value']) && !is_numeric(parse_size($element['#value']))) {
130
    form_error($element, t('The "!name" option must contain a valid value. You may either leave the text field empty or enter a string like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes).', array('!name' => t($element['title']))));
131
  }
132
}
133

    
134
/**
135
 * Element validate callback for the allowed file extensions field.
136
 *
137
 * This doubles as a convenience clean-up function and a validation routine.
138
 * Commas are allowed by the end-user, but ultimately the value will be stored
139
 * as a space-separated list for compatibility with file_validate_extensions().
140
 */
141
function _file_generic_settings_extensions($element, &$form_state) {
142
  if (!empty($element['#value'])) {
143
    $extensions = preg_replace('/([, ]+\.?)/', ' ', trim(strtolower($element['#value'])));
144
    $extensions = array_filter(explode(' ', $extensions));
145
    $extensions = implode(' ', array_unique($extensions));
146
    if (!preg_match('/^([a-z0-9]+([.][a-z0-9])* ?)+$/', $extensions)) {
147
      form_error($element, t('The list of allowed extensions is not valid, be sure to exclude leading dots and to separate extensions with a comma or space.'));
148
    }
149
    else {
150
      form_set_value($element, $extensions, $form_state);
151
    }
152
  }
153
}
154

    
155
/**
156
 * Element validate callback for the file destination field.
157
 *
158
 * Remove slashes from the beginning and end of the destination value and ensure
159
 * that the file directory path is not included at the beginning of the value.
160
 */
161
function _file_generic_settings_file_directory_validate($element, &$form_state) {
162
  // Strip slashes from the beginning and end of $widget['file_directory'].
163
  $value = trim($element['#value'], '\\/');
164
  form_set_value($element, $value, $form_state);
165
}
166

    
167
/**
168
 * Implements hook_field_load().
169
 */
170
function file_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
171

    
172
  $fids = array();
173
  foreach ($entities as $id => $entity) {
174
    // Load the files from the files table.
175
    foreach ($items[$id] as $delta => $item) {
176
      if (!empty($item['fid'])) {
177
        $fids[] = $item['fid'];
178
      }
179
    }
180
  }
181
  $files = file_load_multiple($fids);
182

    
183
  foreach ($entities as $id => $entity) {
184
    foreach ($items[$id] as $delta => $item) {
185
      // If the file does not exist, mark the entire item as empty.
186
      if (empty($item['fid']) || !isset($files[$item['fid']])) {
187
        $items[$id][$delta] = NULL;
188
      }
189
      else {
190
        $items[$id][$delta] = array_merge((array) $files[$item['fid']], $item);
191
      }
192
    }
193
  }
194
}
195

    
196
/**
197
 * Implements hook_field_prepare_view().
198
 */
199
function file_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
200
  // Remove files specified to not be displayed.
201
  foreach ($entities as $id => $entity) {
202
    foreach ($items[$id] as $delta => $item) {
203
      if (!file_field_displayed($item, $field)) {
204
        unset($items[$id][$delta]);
205
      }
206
    }
207
    // Ensure consecutive deltas.
208
    $items[$id] = array_values($items[$id]);
209
  }
210
}
211

    
212
/**
213
 * Implements hook_field_presave().
214
 */
215
function file_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
216
  // Make sure that each file which will be saved with this object has a
217
  // permanent status, so that it will not be removed when temporary files are
218
  // cleaned up.
219
  foreach ($items as $delta => $item) {
220
    if (empty($item['fid'])) {
221
      unset($items[$delta]);
222
      continue;
223
    }
224
    $file = file_load($item['fid']);
225
    if (empty($file)) {
226
      unset($items[$delta]);
227
      continue;
228
    }
229
    if (!$file->status) {
230
      $file->status = FILE_STATUS_PERMANENT;
231
      file_save($file);
232
    }
233
  }
234
}
235

    
236
/**
237
 * Implements hook_field_insert().
238
 */
239
function file_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
240
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
241

    
242
  // Add a new usage of each uploaded file.
243
  foreach ($items as $item) {
244
    $file = (object) $item;
245
    file_usage_add($file, 'file', $entity_type, $id);
246
  }
247
}
248

    
249
/**
250
 * Implements hook_field_update().
251
 *
252
 * Checks for files that have been removed from the object.
253
 */
254
function file_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
255
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
256

    
257
  // On new revisions, all files are considered to be a new usage and no
258
  // deletion of previous file usages are necessary.
259
  if (!empty($entity->revision)) {
260
    foreach ($items as $item) {
261
      $file = (object) $item;
262
      file_usage_add($file, 'file', $entity_type, $id);
263
    }
264
    return;
265
  }
266

    
267
  // Build a display of the current FIDs.
268
  $current_fids = array();
269
  foreach ($items as $item) {
270
    $current_fids[] = $item['fid'];
271
  }
272

    
273
  // Compare the original field values with the ones that are being saved. Use
274
  // $entity->original to check this when possible, but if it isn't available,
275
  // create a bare-bones entity and load its previous values instead.
276
  if (isset($entity->original)) {
277
    $original = $entity->original;
278
  }
279
  else {
280
    $original = entity_create_stub_entity($entity_type, array($id, $vid, $bundle));
281
    field_attach_load($entity_type, array($id => $original), FIELD_LOAD_CURRENT, array('field_id' => $field['id']));
282
  }
283
  $original_fids = array();
284
  if (!empty($original->{$field['field_name']}[$langcode])) {
285
    foreach ($original->{$field['field_name']}[$langcode] as $original_item) {
286
      $original_fids[] = $original_item['fid'];
287
      if (isset($original_item['fid']) && !in_array($original_item['fid'], $current_fids)) {
288
        // Decrement the file usage count by 1 and delete the file if possible.
289
        file_field_delete_file($original_item, $field, $entity_type, $id);
290
      }
291
    }
292
  }
293

    
294
  // Add new usage entries for newly added files.
295
  foreach ($items as $item) {
296
    if (!in_array($item['fid'], $original_fids)) {
297
      $file = (object) $item;
298
      file_usage_add($file, 'file', $entity_type, $id);
299
    }
300
  }
301
}
302

    
303
/**
304
 * Implements hook_field_delete().
305
 */
306
function file_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
307
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
308

    
309
  // Delete all file usages within this entity.
310
  foreach ($items as $delta => $item) {
311
    file_field_delete_file($item, $field, $entity_type, $id, 0);
312
  }
313
}
314

    
315
/**
316
 * Implements hook_field_delete_revision().
317
 */
318
function file_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, &$items) {
319
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
320
  foreach ($items as $delta => $item) {
321
    // Decrement the file usage count by 1 and delete the file if possible.
322
    if (file_field_delete_file($item, $field, $entity_type, $id)) {
323
      $items[$delta] = NULL;
324
    }
325
  }
326
}
327

    
328
/**
329
 * Decrements the usage count for a file and attempts to delete it.
330
 *
331
 * This function only has an effect if the file being deleted is used only by
332
 * File module.
333
 *
334
 * @param $item
335
 *   The field item that contains a file array.
336
 * @param $field
337
 *   The field structure for the operation.
338
 * @param $entity_type
339
 *   The type of $entity.
340
 * @param $id
341
 *   The entity ID which contains the file being deleted.
342
 * @param $count
343
 *   (optional) The number of references to decrement from the object
344
 *   containing the file. Defaults to 1.
345
 *
346
 * @return
347
 *   Boolean TRUE if the file was deleted, or an array of remaining references
348
 *   if the file is still in use by other modules. Boolean FALSE if an error
349
 *   was encountered.
350
 */
351
function file_field_delete_file($item, $field, $entity_type, $id, $count = 1) {
352
  // To prevent the file field from deleting files it doesn't know about, check
353
  // the file reference count. Temporary files can be deleted because they
354
  // are not yet associated with any content at all.
355
  $file = (object) $item;
356
  $file_usage = file_usage_list($file);
357
  if ($file->status == 0 || !empty($file_usage['file'])) {
358
    file_usage_delete($file, 'file', $entity_type, $id, $count);
359
    return file_delete($file);
360
  }
361

    
362
  // Even if the file is not deleted, return TRUE to indicate the file field
363
  // record can be removed from the field database tables.
364
  return TRUE;
365
}
366

    
367
/**
368
 * Implements hook_field_is_empty().
369
 */
370
function file_field_is_empty($item, $field) {
371
  return empty($item['fid']);
372
}
373

    
374
/**
375
 * Determines whether a file should be displayed when outputting field content.
376
 *
377
 * @param $item
378
 *   A field item array.
379
 * @param $field
380
 *   A field array.
381
 *
382
 * @return
383
 *   Boolean TRUE if the file will be displayed, FALSE if the file is hidden.
384
 */
385
function file_field_displayed($item, $field) {
386
  if (!empty($field['settings']['display_field'])) {
387
    return (bool) $item['display'];
388
  }
389
  return TRUE;
390
}
391

    
392
/**
393
 * Implements hook_field_formatter_info().
394
 */
395
function file_field_formatter_info() {
396
  return array(
397
    'file_default' => array(
398
      'label' => t('Generic file'),
399
      'field types' => array('file'),
400
    ),
401
    'file_table' => array(
402
      'label' => t('Table of files'),
403
      'field types' => array('file'),
404
    ),
405
    'file_url_plain' => array(
406
      'label' => t('URL to file'),
407
      'field types' => array('file'),
408
    ),
409
  );
410
}
411

    
412
/**
413
 * Implements hook_field_widget_info().
414
 */
415
function file_field_widget_info() {
416
  return array(
417
    'file_generic' => array(
418
      'label' => t('File'),
419
      'field types' => array('file'),
420
      'settings' => array(
421
        'progress_indicator' => 'throbber',
422
      ),
423
      'behaviors' => array(
424
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
425
        'default value' => FIELD_BEHAVIOR_NONE,
426
      ),
427
    ),
428
  );
429
}
430

    
431
/**
432
 * Implements hook_field_widget_settings_form().
433
 */
434
function file_field_widget_settings_form($field, $instance) {
435
  $widget = $instance['widget'];
436
  $settings = $widget['settings'];
437

    
438
  $form['progress_indicator'] = array(
439
    '#type' => 'radios',
440
    '#title' => t('Progress indicator'),
441
    '#options' => array(
442
      'throbber' => t('Throbber'),
443
      'bar' => t('Bar with progress meter'),
444
    ),
445
    '#default_value' => $settings['progress_indicator'],
446
    '#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.'),
447
    '#weight' => 16,
448
    '#access' => file_progress_implementation(),
449
  );
450

    
451
  return $form;
452
}
453

    
454
/**
455
 * Implements hook_field_widget_form().
456
 */
457
function file_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
458

    
459
  $defaults = array(
460
    'fid' => 0,
461
    'display' => !empty($field['settings']['display_default']),
462
    'description' => '',
463
  );
464

    
465
  // Load the items for form rebuilds from the field state as they might not be
466
  // in $form_state['values'] because of validation limitations. Also, they are
467
  // only passed in as $items when editing existing entities.
468
  $field_state = field_form_get_state($element['#field_parents'], $field['field_name'], $langcode, $form_state);
469
  if (isset($field_state['items'])) {
470
    $items = $field_state['items'];
471
  }
472

    
473
  // Essentially we use the managed_file type, extended with some enhancements.
474
  $element_info = element_info('managed_file');
475
  $element += array(
476
    '#type' => 'managed_file',
477
    '#upload_location' => file_field_widget_uri($field, $instance),
478
    '#upload_validators' => file_field_widget_upload_validators($field, $instance),
479
    '#value_callback' => 'file_field_widget_value',
480
    '#process' => array_merge($element_info['#process'], array('file_field_widget_process')),
481
    '#progress_indicator' => $instance['widget']['settings']['progress_indicator'],
482
    // Allows this field to return an array instead of a single value.
483
    '#extended' => TRUE,
484
  );
485

    
486
  if ($field['cardinality'] == 1) {
487
    // Set the default value.
488
    $element['#default_value'] = !empty($items) ? $items[0] : $defaults;
489
    // If there's only one field, return it as delta 0.
490
    if (empty($element['#default_value']['fid'])) {
491
      $element['#description'] = theme('file_upload_help', array('description' => $element['#description'], 'upload_validators' => $element['#upload_validators']));
492
    }
493
    $elements = array($element);
494
  }
495
  else {
496
    // If there are multiple values, add an element for each existing one.
497
    foreach ($items as $item) {
498
      $elements[$delta] = $element;
499
      $elements[$delta]['#default_value'] = $item;
500
      $elements[$delta]['#weight'] = $delta;
501
      $delta++;
502
    }
503
    // And then add one more empty row for new uploads except when this is a
504
    // programmed form as it is not necessary.
505
    if (($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta < $field['cardinality']) && empty($form_state['programmed'])) {
506
      $elements[$delta] = $element;
507
      $elements[$delta]['#default_value'] = $defaults;
508
      $elements[$delta]['#weight'] = $delta;
509
      $elements[$delta]['#required'] = ($element['#required'] && $delta == 0);
510
    }
511
    // The group of elements all-together need some extra functionality
512
    // after building up the full list (like draggable table rows).
513
    $elements['#file_upload_delta'] = $delta;
514
    $elements['#theme'] = 'file_widget_multiple';
515
    $elements['#theme_wrappers'] = array('fieldset');
516
    $elements['#process'] = array('file_field_widget_process_multiple');
517
    $elements['#title'] = $element['#title'];
518
    $elements['#description'] = $element['#description'];
519
    $elements['#field_name'] = $element['#field_name'];
520
    $elements['#language'] = $element['#language'];
521
    $elements['#display_field'] = $field['settings']['display_field'];
522

    
523
    // Add some properties that will eventually be added to the file upload
524
    // field. These are added here so that they may be referenced easily through
525
    // a hook_form_alter().
526
    $elements['#file_upload_title'] = t('Add a new file');
527
    $elements['#file_upload_description'] = theme('file_upload_help', array('description' => '', 'upload_validators' => $elements[0]['#upload_validators']));
528
  }
529

    
530
  return $elements;
531
}
532

    
533
/**
534
 * Retrieves the upload validators for a file field.
535
 *
536
 * @param $field
537
 *   A field array.
538
 *
539
 * @return
540
 *   An array suitable for passing to file_save_upload() or the file field
541
 *   element's '#upload_validators' property.
542
 */
543
function file_field_widget_upload_validators($field, $instance) {
544
  // Cap the upload size according to the PHP limit.
545
  $max_filesize = parse_size(file_upload_max_size());
546
  if (!empty($instance['settings']['max_filesize']) && parse_size($instance['settings']['max_filesize']) < $max_filesize) {
547
    $max_filesize = parse_size($instance['settings']['max_filesize']);
548
  }
549

    
550
  $validators = array();
551

    
552
  // There is always a file size limit due to the PHP server limit.
553
  $validators['file_validate_size'] = array($max_filesize);
554

    
555
  // Add the extension check if necessary.
556
  if (!empty($instance['settings']['file_extensions'])) {
557
    $validators['file_validate_extensions'] = array($instance['settings']['file_extensions']);
558
  }
559

    
560
  return $validators;
561
}
562

    
563
/**
564
 * Determines the URI for a file field instance.
565
 *
566
 * @param $field
567
 *   A field array.
568
 * @param $instance
569
 *   A field instance array.
570
 * @param $data
571
 *   An array of token objects to pass to token_replace().
572
 *
573
 * @return
574
 *   A file directory URI with tokens replaced.
575
 *
576
 * @see token_replace()
577
 */
578
function file_field_widget_uri($field, $instance, $data = array()) {
579
  $destination = trim($instance['settings']['file_directory'], '/');
580

    
581
  // Replace tokens.
582
  $destination = token_replace($destination, $data);
583

    
584
  return $field['settings']['uri_scheme'] . '://' . $destination;
585
}
586

    
587
/**
588
 * The #value_callback for the file_generic field element.
589
 */
590
function file_field_widget_value($element, $input = FALSE, $form_state) {
591
  if ($input) {
592
    // Checkboxes lose their value when empty.
593
    // If the display field is present make sure its unchecked value is saved.
594
    $field = field_widget_field($element, $form_state);
595
    if (empty($input['display'])) {
596
      $input['display'] = $field['settings']['display_field'] ? 0 : 1;
597
    }
598
  }
599

    
600
  // We depend on the managed file element to handle uploads.
601
  $return = file_managed_file_value($element, $input, $form_state);
602

    
603
  // Ensure that all the required properties are returned even if empty.
604
  $return += array(
605
    'fid' => 0,
606
    'display' => 1,
607
    'description' => '',
608
  );
609

    
610
  return $return;
611
}
612

    
613
/**
614
 * An element #process callback for the file_generic field type.
615
 *
616
 * Expands the file_generic type to include the description and display fields.
617
 */
618
function file_field_widget_process($element, &$form_state, $form) {
619
  $item = $element['#value'];
620
  $item['fid'] = $element['fid']['#value'];
621

    
622
  $field = field_widget_field($element, $form_state);
623
  $instance = field_widget_instance($element, $form_state);
624
  $settings = $instance['widget']['settings'];
625

    
626
  $element['#theme'] = 'file_widget';
627

    
628
  // Add the display field if enabled.
629
  if (!empty($field['settings']['display_field']) && $item['fid']) {
630
    $element['display'] = array(
631
      '#type' => empty($item['fid']) ? 'hidden' : 'checkbox',
632
      '#title' => t('Include file in display'),
633
      '#value' => isset($item['display']) ? $item['display'] : $field['settings']['display_default'],
634
      '#attributes' => array('class' => array('file-display')),
635
    );
636
  }
637
  else {
638
    $element['display'] = array(
639
      '#type' => 'hidden',
640
      '#value' => '1',
641
    );
642
  }
643

    
644
  // Add the description field if enabled.
645
  if (!empty($instance['settings']['description_field']) && $item['fid']) {
646
    $element['description'] = array(
647
      '#type' => variable_get('file_description_type', 'textfield'),
648
      '#title' => t('Description'),
649
      '#value' => isset($item['description']) ? $item['description'] : '',
650
      '#maxlength' => variable_get('file_description_length', 128),
651
      '#description' => t('The description may be used as the label of the link to the file.'),
652
    );
653
  }
654

    
655
  // Adjust the Ajax settings so that on upload and remove of any individual
656
  // file, the entire group of file fields is updated together.
657
  if ($field['cardinality'] != 1) {
658
    $parents = array_slice($element['#array_parents'], 0, -1);
659
    $new_path = 'file/ajax/' . implode('/', $parents) . '/' . $form['form_build_id']['#value'];
660
    $field_element = drupal_array_get_nested_value($form, $parents);
661
    $new_wrapper = $field_element['#id'] . '-ajax-wrapper';
662
    foreach (element_children($element) as $key) {
663
      if (isset($element[$key]['#ajax'])) {
664
        $element[$key]['#ajax']['path'] = $new_path;
665
        $element[$key]['#ajax']['wrapper'] = $new_wrapper;
666
      }
667
    }
668
    unset($element['#prefix'], $element['#suffix']);
669
  }
670

    
671
  // Add another submit handler to the upload and remove buttons, to implement
672
  // functionality needed by the field widget. This submit handler, along with
673
  // the rebuild logic in file_field_widget_form() requires the entire field,
674
  // not just the individual item, to be valid.
675
  foreach (array('upload_button', 'remove_button') as $key) {
676
    $element[$key]['#submit'][] = 'file_field_widget_submit';
677
    $element[$key]['#limit_validation_errors'] = array(array_slice($element['#parents'], 0, -1));
678
  }
679

    
680
  return $element;
681
}
682

    
683
/**
684
 * An element #process callback for a group of file_generic fields.
685
 *
686
 * Adds the weight field to each row so it can be ordered and adds a new Ajax
687
 * wrapper around the entire group so it can be replaced all at once.
688
 */
689
function file_field_widget_process_multiple($element, &$form_state, $form) {
690
  $element_children = element_children($element, TRUE);
691
  $count = count($element_children);
692

    
693
  foreach ($element_children as $delta => $key) {
694
    if ($key != $element['#file_upload_delta']) {
695
      $description = _file_field_get_description_from_element($element[$key]);
696
      $element[$key]['_weight'] = array(
697
        '#type' => 'weight',
698
        '#title' => $description ? t('Weight for @title', array('@title' => $description)) : t('Weight for new file'),
699
        '#title_display' => 'invisible',
700
        '#delta' => $count,
701
        '#default_value' => $delta,
702
      );
703
    }
704
    else {
705
      // The title needs to be assigned to the upload field so that validation
706
      // errors include the correct widget label.
707
      $element[$key]['#title'] = $element['#title'];
708
      $element[$key]['_weight'] = array(
709
        '#type' => 'hidden',
710
        '#default_value' => $delta,
711
      );
712
    }
713
  }
714

    
715
  // Add a new wrapper around all the elements for Ajax replacement.
716
  $element['#prefix'] = '<div id="' . $element['#id'] . '-ajax-wrapper">';
717
  $element['#suffix'] = '</div>';
718

    
719
  return $element;
720
}
721

    
722
/**
723
 * Retrieves the file description from a field field element.
724
 *
725
 * This helper function is used by file_field_widget_process_multiple().
726
 *
727
 * @param $element
728
 *   The element being processed.
729
 *
730
 * @return
731
 *   A description of the file suitable for use in the administrative interface.
732
 */
733
function _file_field_get_description_from_element($element) {
734
  // Use the actual file description, if it's available.
735
  if (!empty($element['#default_value']['description'])) {
736
    return $element['#default_value']['description'];
737
  }
738
  // Otherwise, fall back to the filename.
739
  if (!empty($element['#default_value']['filename'])) {
740
    return $element['#default_value']['filename'];
741
  }
742
  // This is probably a newly uploaded file; no description is available.
743
  return FALSE;
744
}
745

    
746
/**
747
 * Form submission handler for upload/remove button of file_field_widget_form().
748
 *
749
 * This runs in addition to and after file_managed_file_submit().
750
 *
751
 * @see file_managed_file_submit()
752
 * @see file_field_widget_form()
753
 * @see file_field_widget_process()
754
 */
755
function file_field_widget_submit($form, &$form_state) {
756
  // During the form rebuild, file_field_widget_form() will create field item
757
  // widget elements using re-indexed deltas, so clear out $form_state['input']
758
  // to avoid a mismatch between old and new deltas. The rebuilt elements will
759
  // have #default_value set appropriately for the current state of the field,
760
  // so nothing is lost in doing this.
761
  $parents = array_slice($form_state['triggering_element']['#parents'], 0, -2);
762
  drupal_array_set_nested_value($form_state['input'], $parents, NULL);
763

    
764
  $button = $form_state['triggering_element'];
765

    
766
  // Go one level up in the form, to the widgets container.
767
  $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
768
  $field_name = $element['#field_name'];
769
  $langcode = $element['#language'];
770
  $parents = $element['#field_parents'];
771

    
772
  $submitted_values = drupal_array_get_nested_value($form_state['values'], array_slice($button['#parents'], 0, -2));
773
  foreach ($submitted_values as $delta => $submitted_value) {
774
    if (!$submitted_value['fid']) {
775
      unset($submitted_values[$delta]);
776
    }
777
  }
778

    
779
  // Re-index deltas after removing empty items.
780
  $submitted_values = array_values($submitted_values);
781

    
782
  // Update form_state values.
783
  drupal_array_set_nested_value($form_state['values'], array_slice($button['#parents'], 0, -2), $submitted_values);
784

    
785
  // Update items.
786
  $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
787
  $field_state['items'] = $submitted_values;
788
  field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);
789
}
790

    
791
/**
792
 * Returns HTML for an individual file upload widget.
793
 *
794
 * @param $variables
795
 *   An associative array containing:
796
 *   - element: A render element representing the widget.
797
 *
798
 * @ingroup themeable
799
 */
800
function theme_file_widget($variables) {
801
  $element = $variables['element'];
802
  $output = '';
803

    
804
  // The "form-managed-file" class is required for proper Ajax functionality.
805
  $output .= '<div class="file-widget form-managed-file clearfix">';
806
  if ($element['fid']['#value'] != 0) {
807
    // Add the file size after the file name.
808
    $element['filename']['#markup'] .= ' <span class="file-size">(' . format_size($element['#file']->filesize) . ')</span> ';
809
  }
810
  $output .= drupal_render_children($element);
811
  $output .= '</div>';
812

    
813
  return $output;
814
}
815

    
816
/**
817
 * Returns HTML for a group of file upload widgets.
818
 *
819
 * @param $variables
820
 *   An associative array containing:
821
 *   - element: A render element representing the widgets.
822
 *
823
 * @ingroup themeable
824
 */
825
function theme_file_widget_multiple($variables) {
826
  $element = $variables['element'];
827

    
828
  // Special ID and classes for draggable tables.
829
  $weight_class = $element['#id'] . '-weight';
830
  $table_id = $element['#id'] . '-table';
831

    
832
  // Build up a table of applicable fields.
833
  $headers = array();
834
  $headers[] = t('File information');
835
  if ($element['#display_field']) {
836
    $headers[] = array(
837
      'data' => t('Display'),
838
      'class' => array('checkbox'),
839
    );
840
  }
841
  $headers[] = t('Weight');
842
  $headers[] = t('Operations');
843

    
844
  // Get our list of widgets in order (needed when the form comes back after
845
  // preview or failed validation).
846
  $widgets = array();
847
  foreach (element_children($element) as $key) {
848
    $widgets[] = &$element[$key];
849
  }
850
  usort($widgets, '_field_sort_items_value_helper');
851

    
852
  $rows = array();
853
  foreach ($widgets as $key => &$widget) {
854
    // Save the uploading row for last.
855
    if ($widget['#file'] == FALSE) {
856
      $widget['#title'] = $element['#file_upload_title'];
857
      $widget['#description'] = $element['#file_upload_description'];
858
      continue;
859
    }
860

    
861
    // Delay rendering of the buttons, so that they can be rendered later in the
862
    // "operations" column.
863
    $operations_elements = array();
864
    foreach (element_children($widget) as $sub_key) {
865
      if (isset($widget[$sub_key]['#type']) && $widget[$sub_key]['#type'] == 'submit') {
866
        hide($widget[$sub_key]);
867
        $operations_elements[] = &$widget[$sub_key];
868
      }
869
    }
870

    
871
    // Delay rendering of the "Display" option and the weight selector, so that
872
    // each can be rendered later in its own column.
873
    if ($element['#display_field']) {
874
      hide($widget['display']);
875
    }
876
    hide($widget['_weight']);
877

    
878
    // Render everything else together in a column, without the normal wrappers.
879
    $widget['#theme_wrappers'] = array();
880
    $information = drupal_render($widget);
881

    
882
    // Render the previously hidden elements, using render() instead of
883
    // drupal_render(), to undo the earlier hide().
884
    $operations = '';
885
    foreach ($operations_elements as $operation_element) {
886
      $operations .= render($operation_element);
887
    }
888
    $display = '';
889
    if ($element['#display_field']) {
890
      unset($widget['display']['#title']);
891
      $display = array(
892
        'data' => render($widget['display']),
893
        'class' => array('checkbox'),
894
      );
895
    }
896
    $widget['_weight']['#attributes']['class'] = array($weight_class);
897
    $weight = render($widget['_weight']);
898

    
899
    // Arrange the row with all of the rendered columns.
900
    $row = array();
901
    $row[] = $information;
902
    if ($element['#display_field']) {
903
      $row[] = $display;
904
    }
905
    $row[] = $weight;
906
    $row[] = $operations;
907
    $rows[] = array(
908
      'data' => $row,
909
      'class' => isset($widget['#attributes']['class']) ? array_merge($widget['#attributes']['class'], array('draggable')) : array('draggable'),
910
    );
911
  }
912

    
913
  drupal_add_tabledrag($table_id, 'order', 'sibling', $weight_class);
914

    
915
  $output = '';
916
  $output = empty($rows) ? '' : theme('table', array('header' => $headers, 'rows' => $rows, 'attributes' => array('id' => $table_id)));
917
  $output .= drupal_render_children($element);
918
  return $output;
919
}
920

    
921

    
922
/**
923
 * Returns HTML for help text based on file upload validators.
924
 *
925
 * @param $variables
926
 *   An associative array containing:
927
 *   - description: The normal description for this field, specified by the
928
 *     user.
929
 *   - upload_validators: An array of upload validators as used in
930
 *     $element['#upload_validators'].
931
 *
932
 * @ingroup themeable
933
 */
934
function theme_file_upload_help($variables) {
935
  $description = $variables['description'];
936
  $upload_validators = $variables['upload_validators'];
937

    
938
  $descriptions = array();
939

    
940
  if (strlen($description)) {
941
    $descriptions[] = $description;
942
  }
943
  if (isset($upload_validators['file_validate_size'])) {
944
    $descriptions[] = t('Files must be less than !size.', array('!size' => '<strong>' . format_size($upload_validators['file_validate_size'][0]) . '</strong>'));
945
  }
946
  if (isset($upload_validators['file_validate_extensions'])) {
947
    $descriptions[] = t('Allowed file types: !extensions.', array('!extensions' => '<strong>' . check_plain($upload_validators['file_validate_extensions'][0]) . '</strong>'));
948
  }
949
  if (isset($upload_validators['file_validate_image_resolution'])) {
950
    $max = $upload_validators['file_validate_image_resolution'][0];
951
    $min = $upload_validators['file_validate_image_resolution'][1];
952
    if ($min && $max && $min == $max) {
953
      $descriptions[] = t('Images must be exactly !size pixels.', array('!size' => '<strong>' . $max . '</strong>'));
954
    }
955
    elseif ($min && $max) {
956
      $descriptions[] = t('Images must be between !min and !max pixels.', array('!min' => '<strong>' . $min . '</strong>', '!max' => '<strong>' . $max . '</strong>'));
957
    }
958
    elseif ($min) {
959
      $descriptions[] = t('Images must be larger than !min pixels.', array('!min' => '<strong>' . $min . '</strong>'));
960
    }
961
    elseif ($max) {
962
      $descriptions[] = t('Images must be smaller than !max pixels.', array('!max' => '<strong>' . $max . '</strong>'));
963
    }
964
  }
965

    
966
  return implode('<br />', $descriptions);
967
}
968

    
969
/**
970
 * Implements hook_field_formatter_view().
971
 */
972
function file_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
973
  $element = array();
974

    
975
  switch ($display['type']) {
976
    case 'file_default':
977
      foreach ($items as $delta => $item) {
978
        $element[$delta] = array(
979
          '#theme' => 'file_link',
980
          '#file' => (object) $item,
981
        );
982
      }
983
      break;
984

    
985
    case 'file_url_plain':
986
      foreach ($items as $delta => $item) {
987
        $element[$delta] = array('#markup' => empty($item['uri']) ? '' : file_create_url($item['uri']));
988
      }
989
      break;
990

    
991
    case 'file_table':
992
      if (!empty($items)) {
993
        // Display all values in a single element..
994
        $element[0] = array(
995
          '#theme' => 'file_formatter_table',
996
          '#items' => $items,
997
        );
998
      }
999
      break;
1000
  }
1001

    
1002
  return $element;
1003
}
1004

    
1005
/**
1006
 * Returns HTML for a file attachments table.
1007
 *
1008
 * @param $variables
1009
 *   An associative array containing:
1010
 *   - items: An array of file attachments.
1011
 *
1012
 * @ingroup themeable
1013
 */
1014
function theme_file_formatter_table($variables) {
1015
  $header = array(t('Attachment'), t('Size'));
1016
  $rows = array();
1017
  foreach ($variables['items'] as $delta => $item) {
1018
    $rows[] = array(
1019
      theme('file_link', array('file' => (object) $item)),
1020
      format_size($item['filesize']),
1021
    );
1022
  }
1023

    
1024
  return empty($rows) ? '' : theme('table', array('header' => $header, 'rows' => $rows));
1025
}