summaryrefslogtreecommitdiffstats
path: root/modules/file/file.module
blob: c8e17f858341f4fdf3b7b043cb1166665d03dc22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
<?php

/**
 * @file
 * Defines a "managed_file" Form API field and a "file" field for Field module.
 */

// Load all Field module hooks for File.
require_once DRUPAL_ROOT . '/modules/file/file.field.inc';

/**
 * Implements hook_help().
 */
function file_help($path, $arg) {
  switch ($path) {
    case 'admin/help#file':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The File module defines a <em>File</em> field type for the Field module, which lets you manage and validate uploaded files attached to content on your site (see the <a href="@field-help">Field module help page</a> for more information about fields). For more information, see the online handbook entry for <a href="@file">File module</a>.', array('@field-help' => url('admin/help/field'), '@file' => 'http://drupal.org/documentation/modules/file')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Attaching files to content') . '</dt>';
      $output .= '<dd>' . t('The File module allows users to attach files to content (e.g., PDF files, spreadsheets, etc.), when a <em>File</em> field is added to a given content type using the <a href="@fieldui-help">Field UI module</a>. You can add validation options to your File field, such as specifying a maximum file size and allowed file extensions.', array('@fieldui-help' => url('admin/help/field_ui'))) . '</dd>';
      $output .= '<dt>' . t('Managing attachment display') . '</dt>';
      $output .= '<dd>' . t('When you attach a file to content, you can specify whether it is <em>listed</em> or not. Listed files are displayed automatically in a section at the bottom of your content; non-listed files are available for embedding in your content, but are not included in the list at the bottom.') . '</dd>';
      $output .= '<dt>' . t('Managing file locations') . '</dt>';
      $output .= '<dd>' . t("When you create a File field, you can specify a directory where the files will be stored, which can be within either the <em>public</em> or <em>private</em> files directory. Files in the public directory can be accessed directly through the web server; when public files are listed, direct links to the files are used, and anyone who knows a file's URL can download the file. Files in the private directory are not accessible directly through the web server; when private files are listed, the links are Drupal path requests. This adds to server load and download time, since Drupal must start up and resolve the path for each file download request, but allows for access restrictions.") . '</dd>';
      $output .= '</dl>';
      return $output;
  }
}

/**
 * Implements hook_menu().
 */
function file_menu() {
  $items = array();

  $items['file/ajax'] = array(
    'page callback' => 'file_ajax_upload',
    'delivery callback' => 'ajax_deliver',
    'access arguments' => array('access content'),
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );
  $items['file/progress'] = array(
    'page callback' => 'file_ajax_progress',
    'access arguments' => array('access content'),
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Implements hook_element_info().
 *
 * The managed file element may be used anywhere in Drupal.
 */
function file_element_info() {
  $file_path = drupal_get_path('module', 'file');
  $types['managed_file'] = array(
    '#input' => TRUE,
    '#process' => array('file_managed_file_process'),
    '#value_callback' => 'file_managed_file_value',
    '#element_validate' => array('file_managed_file_validate'),
    '#pre_render' => array('file_managed_file_pre_render'),
    '#theme' => 'file_managed_file',
    '#theme_wrappers' => array('form_element'),
    '#progress_indicator' => 'throbber',
    '#progress_message' => NULL,
    '#upload_validators' => array(),
    '#upload_location' => NULL,
    '#size' => 22,
    '#extended' => FALSE,
    '#attached' => array(
      'css' => array($file_path . '/file.css'),
      'js' => array($file_path . '/file.js'),
    ),
  );
  return $types;
}

/**
 * Implements hook_theme().
 */
function file_theme() {
  return array(
    // file.module.
    'file_link' => array(
      'variables' => array('file' => NULL, 'icon_directory' => NULL),
    ),
    'file_icon' => array(
      'variables' => array('file' => NULL, 'icon_directory' => NULL, 'alt' => ''),
    ),
    'file_managed_file' => array(
      'render element' => 'element',
    ),

    // file.field.inc.
    'file_widget' => array(
      'render element' => 'element',
    ),
    'file_widget_multiple' => array(
      'render element' => 'element',
    ),
    'file_formatter_table' => array(
      'variables' => array('items' => NULL),
    ),
    'file_upload_help' => array(
      'variables' => array('description' => NULL, 'upload_validators' => NULL),
    ),
  );
}

/**
 * Implements hook_file_download().
 *
 * This function takes an extra parameter $field_type so that it may
 * be re-used by other File-like modules, such as Image.
 */
function file_file_download($uri, $field_type = 'file') {
  global $user;

  // Get the file record based on the URI. If not in the database just return.
  $files = file_load_multiple(array(), array('uri' => $uri));
  if (count($files)) {
    foreach ($files as $item) {
      // Since some database servers sometimes use a case-insensitive comparison
      // by default, double check that the filename is an exact match.
      if ($item->uri === $uri) {
        $file = $item;
        break;
      }
    }
  }
  if (!isset($file)) {
    return;
  }

  // Find out which (if any) fields of this type contain the file.
  $references = file_get_file_references($file, NULL, FIELD_LOAD_CURRENT, $field_type);

  // Stop processing if there are no references in order to avoid returning
  // headers for files controlled by other modules. Make an exception for
  // temporary files where the host entity has not yet been saved (for example,
  // an image preview on a node/add form) in which case, allow download by the
  // file's owner.
  if (empty($references) && ($file->status == FILE_STATUS_PERMANENT || $file->uid != $user->uid)) {
      return;
  }

  // Default to allow access.
  $denied = FALSE;
  // Loop through all references of this file. If a reference explicitly allows
  // access to the field to which this file belongs, no further checks are done
  // and download access is granted. If a reference denies access, eventually
  // existing additional references are checked. If all references were checked
  // and no reference denied access, access is granted as well. If at least one
  // reference denied access, access is denied.
  foreach ($references as $field_name => $field_references) {
    foreach ($field_references as $entity_type => $type_references) {
      foreach ($type_references as $id => $reference) {
        // Try to load $entity and $field.
        $entity = entity_load($entity_type, array($id));
        $entity = reset($entity);
        $field = field_info_field($field_name);

        // Load the field item that references the file.
        $field_item = NULL;
        if ($entity) {
          // Load all field items for that entity.
          $field_items = field_get_items($entity_type, $entity, $field_name);

          // Find the field item with the matching URI.
          foreach ($field_items as $item) {
            if ($item['uri'] == $uri) {
              $field_item = $item;
              break;
            }
          }
        }

        // Check that $entity, $field and $field_item were loaded successfully
        // and check if access to that field is not disallowed. If any of these
        // checks fail, stop checking access for this reference.
        if (empty($entity) || empty($field) || empty($field_item) || !field_access('view', $field, $entity_type, $entity)) {
          $denied = TRUE;
          break;
        }

        // Invoke hook and collect grants/denies for download access.
        // Default to FALSE and let entities overrule this ruling.
        $grants = array('system' => FALSE);
        foreach (module_implements('file_download_access') as $module) {
          $grants = array_merge($grants, array($module => module_invoke($module, 'file_download_access', $field_item, $entity_type, $entity)));
        }
        // Allow other modules to alter the returned grants/denies.
        drupal_alter('file_download_access', $grants, $field_item, $entity_type, $entity);

        if (in_array(TRUE, $grants)) {
          // If TRUE is returned, access is granted and no further checks are
          // necessary.
          $denied = FALSE;
          break 3;
        }

        if (in_array(FALSE, $grants)) {
          // If an implementation returns FALSE, access to this entity is denied
          // but the file could belong to another entity to which the user might
          // have access. Continue with these.
          $denied = TRUE;
        }
      }
    }
  }

  // Access specifically denied.
  if ($denied) {
    return -1;
  }

  // Access is granted.
  $headers = file_get_content_headers($file);
  return $headers;
}

/**
 * Menu callback; Shared Ajax callback for file uploads and deletions.
 *
 * This rebuilds the form element for a particular field item. As long as the
 * form processing is properly encapsulated in the widget element the form
 * should rebuild correctly using FAPI without the need for additional callbacks
 * or processing.
 */
function file_ajax_upload() {
  $form_parents = func_get_args();
  $form_build_id = (string) array_pop($form_parents);

  if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {
    // Invalid request.
    drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', array('@size' => format_size(file_upload_max_size()))), 'error');
    $commands = array();
    $commands[] = ajax_command_replace(NULL, theme('status_messages'));
    return array('#type' => 'ajax', '#commands' => $commands);
  }

  list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();

  if (!$form) {
    // Invalid form_build_id.
    drupal_set_message(t('An unrecoverable error occurred. Use of this form has expired. Try reloading the page and submitting again.'), 'error');
    $commands = array();
    $commands[] = ajax_command_replace(NULL, theme('status_messages'));
    return array('#type' => 'ajax', '#commands' => $commands);
  }

  // Get the current element and count the number of files.
  $current_element = $form;
  foreach ($form_parents as $parent) {
    $current_element = $current_element[$parent];
  }
  $current_file_count = isset($current_element['#file_upload_delta']) ? $current_element['#file_upload_delta'] : 0;

  // Process user input. $form and $form_state are modified in the process.
  drupal_process_form($form['#form_id'], $form, $form_state);

  // Retrieve the element to be rendered.
  foreach ($form_parents as $parent) {
    $form = $form[$parent];
  }

  // Add the special Ajax class if a new file was added.
  if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) {
    $form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content';
  }
  // Otherwise just add the new content class on a placeholder.
  else {
    $form['#suffix'] .= '<span class="ajax-new-content"></span>';
  }

  $form['#prefix'] .= theme('status_messages');
  $output = drupal_render($form);
  $js = drupal_add_js();
  $settings = drupal_array_merge_deep_array($js['settings']['data']);

  $commands[] = ajax_command_replace(NULL, $output, $settings);
  return array('#type' => 'ajax', '#commands' => $commands);
}

/**
 * Menu callback for upload progress.
 *
 * @param $key
 *   The unique key for this upload process.
 */
function file_ajax_progress($key) {
  $progress = array(
    'message' => t('Starting upload...'),
    'percentage' => -1,
  );

  $implementation = file_progress_implementation();
  if ($implementation == 'uploadprogress') {
    $status = uploadprogress_get_info($key);
    if (isset($status['bytes_uploaded']) && !empty($status['bytes_total'])) {
      $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['bytes_uploaded']), '@total' => format_size($status['bytes_total'])));
      $progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']);
    }
  }
  elseif ($implementation == 'apc') {
    $status = apc_fetch('upload_' . $key);
    if (isset($status['current']) && !empty($status['total'])) {
      $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['current']), '@total' => format_size($status['total'])));
      $progress['percentage'] = round(100 * $status['current'] / $status['total']);
    }
  }

  drupal_json_output($progress);
}

/**
 * Determines the preferred upload progress implementation.
 *
 * @return
 *   A string indicating which upload progress system is available. Either "apc"
 *   or "uploadprogress". If neither are available, returns FALSE.
 */
function file_progress_implementation() {
  static $implementation;
  if (!isset($implementation)) {
    $implementation = FALSE;

    // We prefer the PECL extension uploadprogress because it supports multiple
    // simultaneous uploads. APC only supports one at a time.
    if (extension_loaded('uploadprogress')) {
      $implementation = 'uploadprogress';
    }
    elseif (extension_loaded('apc') && ini_get('apc.rfc1867')) {
      $implementation = 'apc';
    }
  }
  return $implementation;
}

/**
 * Implements hook_file_delete().
 */
function file_file_delete($file) {
  // TODO: Remove references to a file that is in-use.
}

/**
 * Process function to expand the managed_file element type.
 *
 * Expands the file type to include Upload and Remove buttons, as well as
 * support for a default value.
 */
function file_managed_file_process($element, &$form_state, $form) {
  // Append the '-upload' to the #id so the field label's 'for' attribute
  // corresponds with the file element.
  $original_id = $element['#id'];
  $element['#id'] .= '-upload';
  $fid = isset($element['#value']['fid']) ? $element['#value']['fid'] : 0;

  // Set some default element properties.
  $element['#progress_indicator'] = empty($element['#progress_indicator']) ? 'none' : $element['#progress_indicator'];
  $element['#file'] = $fid ? file_load($fid) : FALSE;
  $element['#tree'] = TRUE;

  $ajax_settings = array(
    'path' => 'file/ajax/' . implode('/', $element['#array_parents']) . '/' . $form['form_build_id']['#value'],
    'wrapper' => $original_id . '-ajax-wrapper',
    'effect' => 'fade',
    'progress' => array(
      'type' => $element['#progress_indicator'],
      'message' => $element['#progress_message'],
    ),
  );

  // Set up the buttons first since we need to check if they were clicked.
  $element['upload_button'] = array(
    '#name' => implode('_', $element['#parents']) . '_upload_button',
    '#type' => 'submit',
    '#value' => t('Upload'),
    '#validate' => array(),
    '#submit' => array('file_managed_file_submit'),
    '#limit_validation_errors' => array($element['#parents']),
    '#ajax' => $ajax_settings,
    '#weight' => -5,
  );

  // Force the progress indicator for the remove button to be either 'none' or
  // 'throbber', even if the upload button is using something else.
  $ajax_settings['progress']['type'] = ($element['#progress_indicator'] == 'none') ? 'none' : 'throbber';
  $ajax_settings['progress']['message'] = NULL;
  $ajax_settings['effect'] = 'none';
  $element['remove_button'] = array(
    '#name' => implode('_', $element['#parents']) . '_remove_button',
    '#type' => 'submit',
    '#value' => t('Remove'),
    '#validate' => array(),
    '#submit' => array('file_managed_file_submit'),
    '#limit_validation_errors' => array($element['#parents']),
    '#ajax' => $ajax_settings,
    '#weight' => -5,
  );

  $element['fid'] = array(
    '#type' => 'hidden',
    '#value' => $fid,
  );

  // Add progress bar support to the upload if possible.
  if ($element['#progress_indicator'] == 'bar' && $implementation = file_progress_implementation()) {
    $upload_progress_key = mt_rand();

    if ($implementation == 'uploadprogress') {
      $element['UPLOAD_IDENTIFIER'] = array(
        '#type' => 'hidden',
        '#value' => $upload_progress_key,
        '#attributes' => array('class' => array('file-progress')),
        // Uploadprogress extension requires this field to be at the top of the
        // form.
        '#weight' => -20,
      );
    }
    elseif ($implementation == 'apc') {
      $element['APC_UPLOAD_PROGRESS'] = array(
        '#type' => 'hidden',
        '#value' => $upload_progress_key,
        '#attributes' => array('class' => array('file-progress')),
        // Uploadprogress extension requires this field to be at the top of the
        // form.
        '#weight' => -20,
      );
    }

    // Add the upload progress callback.
    $element['upload_button']['#ajax']['progress']['path'] = 'file/progress/' . $upload_progress_key;
  }

  // The file upload field itself.
  $element['upload'] = array(
    '#name' => 'files[' . implode('_', $element['#parents']) . ']',
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#title_display' => 'invisible',
    '#size' => $element['#size'],
    '#theme_wrappers' => array(),
    '#weight' => -10,
  );

  if ($fid && $element['#file']) {
    $element['filename'] = array(
      '#type' => 'markup',
      '#markup' => theme('file_link', array('file' => $element['#file'])) . ' ',
      '#weight' => -10,
    );
    // Anonymous users who have uploaded a temporary file need a
    // non-session-based token added so file_managed_file_value() can check
    // that they have permission to use this file on subsequent submissions of
    // the same form (for example, after an Ajax upload or form validation
    // error).
    if (!$GLOBALS['user']->uid && $element['#file']->status != FILE_STATUS_PERMANENT) {
      $element['fid_token'] = array(
        '#type' => 'hidden',
        '#value' => drupal_hmac_base64('file-' . $fid, drupal_get_private_key() . drupal_get_hash_salt()),
      );
    }
  }

  // Add the extension list to the page as JavaScript settings.
  if (isset($element['#upload_validators']['file_validate_extensions'][0])) {
    $extension_list = implode(',', array_filter(explode(' ', $element['#upload_validators']['file_validate_extensions'][0])));
    $element['upload']['#attached']['js'] = array(
      array(
        'type' => 'setting',
        'data' => array('file' => array('elements' => array('#' . $element['#id'] => $extension_list)))
      )
    );
  }

  // Prefix and suffix used for Ajax replacement.
  $element['#prefix'] = '<div id="' . $original_id . '-ajax-wrapper">';
  $element['#suffix'] = '</div>';

  return $element;
}

/**
 * The #value_callback for a managed_file type element.
 */
function file_managed_file_value(&$element, $input = FALSE, $form_state = NULL) {
  $fid = 0;
  $force_default = FALSE;

  // Find the current value of this field from the form state.
  $form_state_fid = $form_state['values'];
  foreach ($element['#parents'] as $parent) {
    $form_state_fid = isset($form_state_fid[$parent]) ? $form_state_fid[$parent] : 0;
  }

  if ($element['#extended'] && isset($form_state_fid['fid'])) {
    $fid = $form_state_fid['fid'];
  }
  elseif (is_numeric($form_state_fid)) {
    $fid = $form_state_fid;
  }

  // Process any input and save new uploads.
  if ($input !== FALSE) {
    $return = $input;

    // Uploads take priority over all other values.
    if ($file = file_managed_file_save_upload($element)) {
      $fid = $file->fid;
    }
    else {
      // Check for #filefield_value_callback values.
      // Because FAPI does not allow multiple #value_callback values like it
      // does for #element_validate and #process, this fills the missing
      // functionality to allow File fields to be extended through FAPI.
      if (isset($element['#file_value_callbacks'])) {
        foreach ($element['#file_value_callbacks'] as $callback) {
          $callback($element, $input, $form_state);
        }
      }
      // If a FID was submitted, load the file (and check access if it's not a
      // public file) to confirm it exists and that the current user has access
      // to it.
      if (isset($input['fid']) && ($file = file_load($input['fid']))) {
        // By default the public:// file scheme provided by Drupal core is the
        // only one that allows files to be publicly accessible to everyone, so
        // it is the only one for which the file access checks are bypassed.
        // Other modules which provide publicly accessible streams of their own
        // in hook_stream_wrappers() can add the corresponding scheme to the
        // 'file_public_schema' variable to bypass file access checks for those
        // as well. This should only be done for schemes that are completely
        // publicly accessible, with no download restrictions; for security
        // reasons all other schemes must go through the file_download_access()
        // check.
        if (!in_array(file_uri_scheme($file->uri), variable_get('file_public_schema', array('public'))) && !file_download_access($file->uri)) {
          $force_default = TRUE;
        }
        // Temporary files that belong to other users should never be allowed.
        elseif ($file->status != FILE_STATUS_PERMANENT) {
          if ($GLOBALS['user']->uid && $file->uid != $GLOBALS['user']->uid) {
            $force_default = TRUE;
          }
          // Since file ownership can't be determined for anonymous users, they
          // are not allowed to reuse temporary files at all. But they do need
          // to be able to reuse their own files from earlier submissions of
          // the same form, so to allow that, check for the token added by
          // file_managed_file_process().
          elseif (!$GLOBALS['user']->uid) {
            $token = drupal_array_get_nested_value($form_state['input'], array_merge($element['#parents'], array('fid_token')));
            if ($token !== drupal_hmac_base64('file-' . $file->fid, drupal_get_private_key() . drupal_get_hash_salt())) {
              $force_default = TRUE;
            }
          }
        }
        // If all checks pass, allow the file to be changed.
        if (!$force_default) {
          $fid = $file->fid;
        }
      }
    }
  }

  // If there is no input or if the default value was requested above, use the
  // default value.
  if ($input === FALSE || $force_default) {
    if ($element['#extended']) {
      $default_fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
      $return = isset($element['#default_value']) ? $element['#default_value'] : array('fid' => 0);
    }
    else {
      $default_fid = isset($element['#default_value']) ? $element['#default_value'] : 0;
      $return = array('fid' => 0);
    }

    // Confirm that the file exists when used as a default value.
    if ($default_fid && $file = file_load($default_fid)) {
      $fid = $file->fid;
    }
  }

  $return['fid'] = $fid;

  return $return;
}

/**
 * An #element_validate callback for the managed_file element.
 */
function file_managed_file_validate(&$element, &$form_state) {
  // If referencing an existing file, only allow if there are existing
  // references. This prevents unmanaged files from being deleted if this
  // item were to be deleted.
  $clicked_button = end($form_state['triggering_element']['#parents']);
  if ($clicked_button != 'remove_button' && !empty($element['fid']['#value'])) {
    if ($file = file_load($element['fid']['#value'])) {
      if ($file->status == FILE_STATUS_PERMANENT) {
        $references = file_usage_list($file);
        if (empty($references)) {
          form_error($element, t('The file used in the !name field may not be referenced.', array('!name' => $element['#title'])));
        }
      }
    }
    else {
      form_error($element, t('The file referenced by the !name field does not exist.', array('!name' => $element['#title'])));
    }
  }

  // Check required property based on the FID.
  if ($element['#required'] && empty($element['fid']['#value']) && !in_array($clicked_button, array('upload_button', 'remove_button'))) {
    form_error($element['upload'], t('!name field is required.', array('!name' => $element['#title'])));
  }

  // Consolidate the array value of this field to a single FID.
  if (!$element['#extended']) {
    form_set_value($element, $element['fid']['#value'], $form_state);
  }
}

/**
 * Form submission handler for upload / remove buttons of managed_file elements.
 *
 * @see file_managed_file_process()
 */
function file_managed_file_submit($form, &$form_state) {
  // Determine whether it was the upload or the remove button that was clicked,
  // and set $element to the managed_file element that contains that button.
  $parents = $form_state['triggering_element']['#array_parents'];
  $button_key = array_pop($parents);
  $element = drupal_array_get_nested_value($form, $parents);

  // No action is needed here for the upload button, because all file uploads on
  // the form are processed by file_managed_file_value() regardless of which
  // button was clicked. Action is needed here for the remove button, because we
  // only remove a file in response to its remove button being clicked.
  if ($button_key == 'remove_button') {
    // If it's a temporary file we can safely remove it immediately, otherwise
    // it's up to the implementing module to clean up files that are in use.
    if ($element['#file'] && $element['#file']->status == 0) {
      file_delete($element['#file']);
    }
    // Update both $form_state['values'] and $form_state['input'] to reflect
    // that the file has been removed, so that the form is rebuilt correctly.
    // $form_state['values'] must be updated in case additional submit handlers
    // run, and for form building functions that run during the rebuild, such as
    // when the managed_file element is part of a field widget.
    // $form_state['input'] must be updated so that file_managed_file_value()
    // has correct information during the rebuild.
    $values_element = $element['#extended'] ? $element['fid'] : $element;
    form_set_value($values_element, NULL, $form_state);
    drupal_array_set_nested_value($form_state['input'], $values_element['#parents'], NULL);
  }

  // Set the form to rebuild so that $form is correctly updated in response to
  // processing the file removal. Since this function did not change $form_state
  // if the upload button was clicked, a rebuild isn't necessary in that
  // situation and setting $form_state['redirect'] to FALSE would suffice.
  // However, we choose to always rebuild, to keep the form processing workflow
  // consistent between the two buttons.
  $form_state['rebuild'] = TRUE;
}

/**
 * Saves any files that have been uploaded into a managed_file element.
 *
 * @param $element
 *   The FAPI element whose values are being saved.
 *
 * @return
 *   The file object representing the file that was saved, or FALSE if no file
 *   was saved.
 */
function file_managed_file_save_upload($element) {
  $upload_name = implode('_', $element['#parents']);
  if (empty($_FILES['files']['name'][$upload_name])) {
    return FALSE;
  }

  $destination = isset($element['#upload_location']) ? $element['#upload_location'] : NULL;
  if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
    watchdog('file', 'The upload directory %directory for the file field !name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.', array('%directory' => $destination, '!name' => $element['#field_name']));
    form_set_error($upload_name, t('The file could not be uploaded.'));
    return FALSE;
  }

  if (!$file = file_save_upload($upload_name, $element['#upload_validators'], $destination)) {
    watchdog('file', 'The file upload failed. %upload', array('%upload' => $upload_name));
    form_set_error($upload_name, t('The file in the !name field was unable to be uploaded.', array('!name' => $element['#title'])));
    return FALSE;
  }

  return $file;
}

/**
 * Returns HTML for a managed file element.
 *
 * @param $variables
 *   An associative array containing:
 *   - element: A render element representing the file.
 *
 * @ingroup themeable
 */
function theme_file_managed_file($variables) {
  $element = $variables['element'];

  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] = (array) $element['#attributes']['class'];
  }
  $attributes['class'][] = 'form-managed-file';

  // This wrapper is required to apply JS behaviors and CSS styling.
  $output = '';
  $output .= '<div' . drupal_attributes($attributes) . '>';
  $output .= drupal_render_children($element);
  $output .= '</div>';
  return $output;
}

/**
 * #pre_render callback to hide display of the upload or remove controls.
 *
 * Upload controls are hidden when a file is already uploaded. Remove controls
 * are hidden when there is no file attached. Controls are hidden here instead
 * of in file_managed_file_process(), because #access for these buttons depends
 * on the managed_file element's #value. See the documentation of form_builder()
 * for more detailed information about the relationship between #process,
 * #value, and #access.
 *
 * Because #access is set here, it affects display only and does not prevent
 * JavaScript or other untrusted code from submitting the form as though access
 * were enabled. The form processing functions for these elements should not
 * assume that the buttons can't be "clicked" just because they are not
 * displayed.
 *
 * @see file_managed_file_process()
 * @see form_builder()
 */
function file_managed_file_pre_render($element) {
  // If we already have a file, we don't want to show the upload controls.
  if (!empty($element['#value']['fid'])) {
    $element['upload']['#access'] = FALSE;
    $element['upload_button']['#access'] = FALSE;
  }
  // If we don't already have a file, there is nothing to remove.
  else {
    $element['remove_button']['#access'] = FALSE;
  }
  return $element;
}

/**
 * Returns HTML for a link to a file.
 *
 * @param $variables
 *   An associative array containing:
 *   - file: A file object to which the link will be created.
 *   - icon_directory: (optional) A path to a directory of icons to be used for
 *     files. Defaults to the value of the "file_icon_directory" variable.
 *
 * @ingroup themeable
 */
function theme_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);

  // Human-readable names, for use as text-alternatives to icons.
  $mime_name = array(
    'application/msword' => t('Microsoft Office document icon'),
    'application/vnd.ms-excel' => t('Office spreadsheet icon'),
    'application/vnd.ms-powerpoint' => t('Office presentation icon'),
    'application/pdf' => t('PDF icon'),
    'video/quicktime' => t('Movie icon'),
    'audio/mpeg' => t('Audio icon'),
    'audio/wav' => t('Audio icon'),
    'image/jpeg' => t('Image icon'),
    'image/png' => t('Image icon'),
    'image/gif' => t('Image icon'),
    'application/zip' => t('Package icon'),
    'text/html' => t('HTML icon'),
    'text/plain' => t('Plain text icon'),
    'application/octet-stream' => t('Binary Data'),
  );

  $mimetype = file_get_mimetype($file->uri);

  $icon = theme('file_icon', array(
    'file' => $file,
    'icon_directory' => $icon_directory,
    'alt' => !empty($mime_name[$mimetype]) ? $mime_name[$mimetype] : t('File'),
  ));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span>';
}

/**
 * Returns HTML for an image with an appropriate icon for the given file.
 *
 * @param $variables
 *   An associative array containing:
 *   - file: A file object for which to make an icon.
 *   - icon_directory: (optional) A path to a directory of icons to be used for
 *     files. Defaults to the value of the "file_icon_directory" variable.
 *   - alt: (optional) The alternative text to represent the icon in text-based
 *     browsers. Defaults to an empty string.
 *
 * @ingroup themeable
 */
function theme_file_icon($variables) {
  $file = $variables['file'];
  $alt = $variables['alt'];
  $icon_directory = $variables['icon_directory'];

  $mime = check_plain($file->filemime);
  $icon_url = file_icon_url($file, $icon_directory);
  return '<img class="file-icon" alt="' . check_plain($alt) . '" title="' . $mime . '" src="' . $icon_url . '" />';
}

/**
 * Creates a URL to the icon for a file object.
 *
 * @param $file
 *   A file object.
 * @param $icon_directory
 *   (optional) A path to a directory of icons to be used for files. Defaults to
 *   the value of the "file_icon_directory" variable.
 *
 * @return
 *   A URL string to the icon, or FALSE if an appropriate icon cannot be found.
 */
function file_icon_url($file, $icon_directory = NULL) {
  if ($icon_path = file_icon_path($file, $icon_directory)) {
    return base_path() . $icon_path;
  }
  return FALSE;
}

/**
 * Creates a path to the icon for a file object.
 *
 * @param $file
 *   A file object.
 * @param $icon_directory
 *   (optional) A path to a directory of icons to be used for files. Defaults to
 *   the value of the "file_icon_directory" variable.
 *
 * @return
 *   A string to the icon as a local path, or FALSE if an appropriate icon could
 *   not be found.
 */
function file_icon_path($file, $icon_directory = NULL) {
  // Use the default set of icons if none specified.
  if (!isset($icon_directory)) {
    $icon_directory = variable_get('file_icon_directory', drupal_get_path('module', 'file') . '/icons');
  }

  // If there's an icon matching the exact mimetype, go for it.
  $dashed_mime = strtr($file->filemime, array('/' => '-'));
  $icon_path = $icon_directory . '/' . $dashed_mime . '.png';
  if (file_exists($icon_path)) {
    return $icon_path;
  }

  // For a few mimetypes, we can "manually" map to a generic icon.
  $generic_mime = (string) file_icon_map($file);
  $icon_path = $icon_directory . '/' . $generic_mime . '.png';
  if ($generic_mime && file_exists($icon_path)) {
    return $icon_path;
  }

  // Use generic icons for each category that provides such icons.
  foreach (array('audio', 'image', 'text', 'video') as $category) {
    if (strpos($file->filemime, $category . '/') === 0) {
      $icon_path = $icon_directory . '/' . $category . '-x-generic.png';
      if (file_exists($icon_path)) {
        return $icon_path;
      }
    }
  }

  // Try application-octet-stream as last fallback.
  $icon_path = $icon_directory . '/application-octet-stream.png';
  if (file_exists($icon_path)) {
    return $icon_path;
  }

  // No icon can be found.
  return FALSE;
}

/**
 * Determines the generic icon MIME package based on a file's MIME type.
 *
 * @param $file
 *   A file object.
 *
 * @return
 *   The generic icon MIME package expected for this file.
 */
function file_icon_map($file) {
  switch ($file->filemime) {
    // Word document types.
    case 'application/msword':
    case 'application/vnd.ms-word.document.macroEnabled.12':
    case 'application/vnd.oasis.opendocument.text':
    case 'application/vnd.oasis.opendocument.text-template':
    case 'application/vnd.oasis.opendocument.text-master':
    case 'application/vnd.oasis.opendocument.text-web':
    case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
    case 'application/vnd.stardivision.writer':
    case 'application/vnd.sun.xml.writer':
    case 'application/vnd.sun.xml.writer.template':
    case 'application/vnd.sun.xml.writer.global':
    case 'application/vnd.wordperfect':
    case 'application/x-abiword':
    case 'application/x-applix-word':
    case 'application/x-kword':
    case 'application/x-kword-crypt':
      return 'x-office-document';

    // Spreadsheet document types.
    case 'application/vnd.ms-excel':
    case 'application/vnd.ms-excel.sheet.macroEnabled.12':
    case 'application/vnd.oasis.opendocument.spreadsheet':
    case 'application/vnd.oasis.opendocument.spreadsheet-template':
    case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
    case 'application/vnd.stardivision.calc':
    case 'application/vnd.sun.xml.calc':
    case 'application/vnd.sun.xml.calc.template':
    case 'application/vnd.lotus-1-2-3':
    case 'application/x-applix-spreadsheet':
    case 'application/x-gnumeric':
    case 'application/x-kspread':
    case 'application/x-kspread-crypt':
      return 'x-office-spreadsheet';

    // Presentation document types.
    case 'application/vnd.ms-powerpoint':
    case 'application/vnd.ms-powerpoint.presentation.macroEnabled.12':
    case 'application/vnd.oasis.opendocument.presentation':
    case 'application/vnd.oasis.opendocument.presentation-template':
    case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
    case 'application/vnd.stardivision.impress':
    case 'application/vnd.sun.xml.impress':
    case 'application/vnd.sun.xml.impress.template':
    case 'application/x-kpresenter':
      return 'x-office-presentation';

    // Compressed archive types.
    case 'application/zip':
    case 'application/x-zip':
    case 'application/stuffit':
    case 'application/x-stuffit':
    case 'application/x-7z-compressed':
    case 'application/x-ace':
    case 'application/x-arj':
    case 'application/x-bzip':
    case 'application/x-bzip-compressed-tar':
    case 'application/x-compress':
    case 'application/x-compressed-tar':
    case 'application/x-cpio-compressed':
    case 'application/x-deb':
    case 'application/x-gzip':
    case 'application/x-java-archive':
    case 'application/x-lha':
    case 'application/x-lhz':
    case 'application/x-lzop':
    case 'application/x-rar':
    case 'application/x-rpm':
    case 'application/x-tzo':
    case 'application/x-tar':
    case 'application/x-tarz':
    case 'application/x-tgz':
      return 'package-x-generic';

    // Script file types.
    case 'application/ecmascript':
    case 'application/javascript':
    case 'application/mathematica':
    case 'application/vnd.mozilla.xul+xml':
    case 'application/x-asp':
    case 'application/x-awk':
    case 'application/x-cgi':
    case 'application/x-csh':
    case 'application/x-m4':
    case 'application/x-perl':
    case 'application/x-php':
    case 'application/x-ruby':
    case 'application/x-shellscript':
    case 'text/vnd.wap.wmlscript':
    case 'text/x-emacs-lisp':
    case 'text/x-haskell':
    case 'text/x-literate-haskell':
    case 'text/x-lua':
    case 'text/x-makefile':
    case 'text/x-matlab':
    case 'text/x-python':
    case 'text/x-sql':
    case 'text/x-tcl':
      return 'text-x-script';

    // HTML aliases.
    case 'application/xhtml+xml':
      return 'text-html';

    // Executable types.
    case 'application/x-macbinary':
    case 'application/x-ms-dos-executable':
    case 'application/x-pef-executable':
      return 'application-x-executable';

    default:
      return FALSE;
  }
}

/**
 * @defgroup file-module-api File module public API functions
 * @{
 * These functions may be used to determine if and where a file is in use.
 */

/**
 * Retrieves a list of references to a file.
 *
 * @param $file
 *   A file object.
 * @param $field
 *   (optional) A field array to be used for this check. If given, limits the
 *   reference check to the given field.
 * @param $age
 *   (optional) A constant that specifies which references to count. Use
 *   FIELD_LOAD_REVISION to retrieve all references within all revisions or
 *   FIELD_LOAD_CURRENT to retrieve references only in the current revisions.
 * @param $field_type
 *   (optional) The name of a field type. If given, limits the reference check
 *   to fields of the given type.
 *
 * @return
 *   An integer value.
 */
function file_get_file_references($file, $field = NULL, $age = FIELD_LOAD_REVISION, $field_type = 'file') {
  $references = drupal_static(__FUNCTION__, array());
  $fields = isset($field) ? array($field['field_name'] => $field) : field_info_fields();

  foreach ($fields as $field_name => $file_field) {
    if ((empty($field_type) || $file_field['type'] == $field_type) && !isset($references[$field_name])) {
      // Get each time this file is used within a field.
      $query = new EntityFieldQuery();
      $query
        ->fieldCondition($file_field, 'fid', $file->fid)
        ->age($age);
      $references[$field_name] = $query->execute();
    }
  }

  return isset($field) ? $references[$field['field_name']] : array_filter($references);
}

/**
 * @} End of "defgroup file-module-api".
 */