Project

General

Profile

Paste
Download (41.7 KB) Statistics
| Branch: | Revision:

root / drupal7 / modules / file / file.module @ 175ce36f

1
<?php
2

    
3
/**
4
 * @file
5
 * Defines a "managed_file" Form API field and a "file" field for Field module.
6
 */
7

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

    
11
/**
12
 * Implements hook_help().
13
 */
14
function file_help($path, $arg) {
15
  switch ($path) {
16
    case 'admin/help#file':
17
      $output = '';
18
      $output .= '<h3>' . t('About') . '</h3>';
19
      $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>';
20
      $output .= '<h3>' . t('Uses') . '</h3>';
21
      $output .= '<dl>';
22
      $output .= '<dt>' . t('Attaching files to content') . '</dt>';
23
      $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>';
24
      $output .= '<dt>' . t('Managing attachment display') . '</dt>';
25
      $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>';
26
      $output .= '<dt>' . t('Managing file locations') . '</dt>';
27
      $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>';
28
      $output .= '</dl>';
29
      return $output;
30
  }
31
}
32

    
33
/**
34
 * Implements hook_menu().
35
 */
36
function file_menu() {
37
  $items = array();
38

    
39
  $items['file/ajax'] = array(
40
    'page callback' => 'file_ajax_upload',
41
    'delivery callback' => 'ajax_deliver',
42
    'access arguments' => array('access content'),
43
    'theme callback' => 'ajax_base_page_theme',
44
    'type' => MENU_CALLBACK,
45
  );
46
  $items['file/progress'] = array(
47
    'page callback' => 'file_ajax_progress',
48
    'access arguments' => array('access content'),
49
    'theme callback' => 'ajax_base_page_theme',
50
    'type' => MENU_CALLBACK,
51
  );
52

    
53
  return $items;
54
}
55

    
56
/**
57
 * Implements hook_element_info().
58
 *
59
 * The managed file element may be used anywhere in Drupal.
60
 */
61
function file_element_info() {
62
  $file_path = drupal_get_path('module', 'file');
63
  $types['managed_file'] = array(
64
    '#input' => TRUE,
65
    '#process' => array('file_managed_file_process'),
66
    '#value_callback' => 'file_managed_file_value',
67
    '#element_validate' => array('file_managed_file_validate'),
68
    '#pre_render' => array('file_managed_file_pre_render'),
69
    '#theme' => 'file_managed_file',
70
    '#theme_wrappers' => array('form_element'),
71
    '#progress_indicator' => 'throbber',
72
    '#progress_message' => NULL,
73
    '#upload_validators' => array(),
74
    '#upload_location' => NULL,
75
    '#size' => 22,
76
    '#extended' => FALSE,
77
    '#attached' => array(
78
      'css' => array($file_path . '/file.css'),
79
      'js' => array($file_path . '/file.js'),
80
    ),
81
  );
82
  return $types;
83
}
84

    
85
/**
86
 * Implements hook_theme().
87
 */
88
function file_theme() {
89
  return array(
90
    // file.module.
91
    'file_link' => array(
92
      'variables' => array('file' => NULL, 'icon_directory' => NULL),
93
    ),
94
    'file_icon' => array(
95
      'variables' => array('file' => NULL, 'icon_directory' => NULL, 'alt' => ''),
96
    ),
97
    'file_managed_file' => array(
98
      'render element' => 'element',
99
    ),
100

    
101
    // file.field.inc.
102
    'file_widget' => array(
103
      'render element' => 'element',
104
    ),
105
    'file_widget_multiple' => array(
106
      'render element' => 'element',
107
    ),
108
    'file_formatter_table' => array(
109
      'variables' => array('items' => NULL),
110
    ),
111
    'file_upload_help' => array(
112
      'variables' => array('description' => NULL, 'upload_validators' => NULL),
113
    ),
114
  );
115
}
116

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

    
126
  // Get the file record based on the URI. If not in the database just return.
127
  $files = file_load_multiple(array(), array('uri' => $uri));
128
  if (count($files)) {
129
    foreach ($files as $item) {
130
      // Since some database servers sometimes use a case-insensitive comparison
131
      // by default, double check that the filename is an exact match.
132
      if ($item->uri === $uri) {
133
        $file = $item;
134
        break;
135
      }
136
    }
137
  }
138
  if (!isset($file)) {
139
    return;
140
  }
141

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

    
145
  // Stop processing if there are no references in order to avoid returning
146
  // headers for files controlled by other modules. Make an exception for
147
  // temporary files where the host entity has not yet been saved (for example,
148
  // an image preview on a node/add form) in which case, allow download by the
149
  // file's owner. For anonymous file owners, only the browser session that
150
  // uploaded the file should be granted access.
151
  if (empty($references) && ($file->status == FILE_STATUS_PERMANENT || $file->uid != $user->uid || (!$user->uid && empty($_SESSION['anonymous_allowed_file_ids'][$file->fid])))) {
152
      return;
153
  }
154

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

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

    
177
          // Find the field item with the matching URI.
178
          foreach ($field_items as $item) {
179
            if ($item['uri'] == $uri) {
180
              $field_item = $item;
181
              break;
182
            }
183
          }
184
        }
185

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

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

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

    
210
        if (in_array(FALSE, $grants)) {
211
          // If an implementation returns FALSE, access to this entity is denied
212
          // but the file could belong to another entity to which the user might
213
          // have access. Continue with these.
214
          $denied = TRUE;
215
        }
216
      }
217
    }
218
  }
219

    
220
  // Access specifically denied.
221
  if ($denied) {
222
    return -1;
223
  }
224

    
225
  // Access is granted.
226
  $headers = file_get_content_headers($file);
227
  return $headers;
228
}
229

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

    
242
  // Sanitize form parents before using them.
243
  $form_parents = array_filter($form_parents, 'element_child');
244

    
245
  if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {
246
    // Invalid request.
247
    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');
248
    $commands = array();
249
    $commands[] = ajax_command_replace(NULL, theme('status_messages'));
250
    return array('#type' => 'ajax', '#commands' => $commands);
251
  }
252

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

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

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

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

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

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

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

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

    
296
/**
297
 * Menu callback for upload progress.
298
 *
299
 * @param $key
300
 *   The unique key for this upload process.
301
 */
302
function file_ajax_progress($key) {
303
  $progress = array(
304
    'message' => t('Starting upload...'),
305
    'percentage' => -1,
306
  );
307

    
308
  $implementation = file_progress_implementation();
309
  if ($implementation == 'uploadprogress') {
310
    $status = uploadprogress_get_info($key);
311
    if (isset($status['bytes_uploaded']) && !empty($status['bytes_total'])) {
312
      $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['bytes_uploaded']), '@total' => format_size($status['bytes_total'])));
313
      $progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']);
314
    }
315
  }
316
  elseif ($implementation == 'apc') {
317
    $status = apc_fetch('upload_' . $key);
318
    if (isset($status['current']) && !empty($status['total'])) {
319
      $progress['message'] = t('Uploading... (@current of @total)', array('@current' => format_size($status['current']), '@total' => format_size($status['total'])));
320
      $progress['percentage'] = round(100 * $status['current'] / $status['total']);
321
    }
322
  }
323

    
324
  drupal_json_output($progress);
325
}
326

    
327
/**
328
 * Determines the preferred upload progress implementation.
329
 *
330
 * @return
331
 *   A string indicating which upload progress system is available. Either "apc"
332
 *   or "uploadprogress". If neither are available, returns FALSE.
333
 */
334
function file_progress_implementation() {
335
  static $implementation;
336
  if (!isset($implementation)) {
337
    $implementation = FALSE;
338

    
339
    // We prefer the PECL extension uploadprogress because it supports multiple
340
    // simultaneous uploads. APC only supports one at a time.
341
    if (extension_loaded('uploadprogress')) {
342
      $implementation = 'uploadprogress';
343
    }
344
    elseif (extension_loaded('apc') && ini_get('apc.rfc1867')) {
345
      $implementation = 'apc';
346
    }
347
  }
348
  return $implementation;
349
}
350

    
351
/**
352
 * Implements hook_file_delete().
353
 */
354
function file_file_delete($file) {
355
  // TODO: Remove references to a file that is in-use.
356
}
357

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

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

    
376
  $ajax_settings = array(
377
    'path' => 'file/ajax/' . implode('/', $element['#array_parents']) . '/' . $form['form_build_id']['#value'],
378
    'wrapper' => $original_id . '-ajax-wrapper',
379
    'effect' => 'fade',
380
    'progress' => array(
381
      'type' => $element['#progress_indicator'],
382
      'message' => $element['#progress_message'],
383
    ),
384
  );
385

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

    
398
  // Force the progress indicator for the remove button to be either 'none' or
399
  // 'throbber', even if the upload button is using something else.
400
  $ajax_settings['progress']['type'] = ($element['#progress_indicator'] == 'none') ? 'none' : 'throbber';
401
  $ajax_settings['progress']['message'] = NULL;
402
  $ajax_settings['effect'] = 'none';
403
  $element['remove_button'] = array(
404
    '#name' => implode('_', $element['#parents']) . '_remove_button',
405
    '#type' => 'submit',
406
    '#value' => t('Remove'),
407
    '#validate' => array(),
408
    '#submit' => array('file_managed_file_submit'),
409
    '#limit_validation_errors' => array($element['#parents']),
410
    '#ajax' => $ajax_settings,
411
    '#weight' => -5,
412
  );
413

    
414
  $element['fid'] = array(
415
    '#type' => 'hidden',
416
    '#value' => $fid,
417
  );
418

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

    
423
    if ($implementation == 'uploadprogress') {
424
      $element['UPLOAD_IDENTIFIER'] = array(
425
        '#type' => 'hidden',
426
        '#value' => $upload_progress_key,
427
        '#attributes' => array('class' => array('file-progress')),
428
        // Uploadprogress extension requires this field to be at the top of the
429
        // form.
430
        '#weight' => -20,
431
      );
432
    }
433
    elseif ($implementation == 'apc') {
434
      $element['APC_UPLOAD_PROGRESS'] = array(
435
        '#type' => 'hidden',
436
        '#value' => $upload_progress_key,
437
        '#attributes' => array('class' => array('file-progress')),
438
        // Uploadprogress extension requires this field to be at the top of the
439
        // form.
440
        '#weight' => -20,
441
      );
442
    }
443

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

    
448
  // The file upload field itself.
449
  $element['upload'] = array(
450
    '#name' => 'files[' . implode('_', $element['#parents']) . ']',
451
    '#type' => 'file',
452
    '#title' => t('Choose a file'),
453
    '#title_display' => 'invisible',
454
    '#size' => $element['#size'],
455
    '#theme_wrappers' => array(),
456
    '#weight' => -10,
457
  );
458

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

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

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

    
493
  return $element;
494
}
495

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

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

    
509
  if ($element['#extended'] && isset($form_state_fid['fid'])) {
510
    $fid = $form_state_fid['fid'];
511
  }
512
  elseif (is_numeric($form_state_fid)) {
513
    $fid = $form_state_fid;
514
  }
515

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

    
520
    // Uploads take priority over all other values.
521
    if ($file = file_managed_file_save_upload($element)) {
522
      $fid = $file->fid;
523
    }
524
    else {
525
      // Check for #filefield_value_callback values.
526
      // Because FAPI does not allow multiple #value_callback values like it
527
      // does for #element_validate and #process, this fills the missing
528
      // functionality to allow File fields to be extended through FAPI.
529
      if (isset($element['#file_value_callbacks'])) {
530
        foreach ($element['#file_value_callbacks'] as $callback) {
531
          $callback($element, $input, $form_state);
532
        }
533
      }
534
      // If a FID was submitted, load the file (and check access if it's not a
535
      // public file) to confirm it exists and that the current user has access
536
      // to it.
537
      if (isset($input['fid']) && ($file = file_load($input['fid']))) {
538
        // By default the public:// file scheme provided by Drupal core is the
539
        // only one that allows files to be publicly accessible to everyone, so
540
        // it is the only one for which the file access checks are bypassed.
541
        // Other modules which provide publicly accessible streams of their own
542
        // in hook_stream_wrappers() can add the corresponding scheme to the
543
        // 'file_public_schema' variable to bypass file access checks for those
544
        // as well. This should only be done for schemes that are completely
545
        // publicly accessible, with no download restrictions; for security
546
        // reasons all other schemes must go through the file_download_access()
547
        // check.
548
        if (!in_array(file_uri_scheme($file->uri), variable_get('file_public_schema', array('public'))) && !file_download_access($file->uri)) {
549
          $force_default = TRUE;
550
        }
551
        // Temporary files that belong to other users should never be allowed.
552
        elseif ($file->status != FILE_STATUS_PERMANENT) {
553
          if ($GLOBALS['user']->uid && $file->uid != $GLOBALS['user']->uid) {
554
            $force_default = TRUE;
555
          }
556
          // Since file ownership can't be determined for anonymous users, they
557
          // are not allowed to reuse temporary files at all. But they do need
558
          // to be able to reuse their own files from earlier submissions of
559
          // the same form, so to allow that, check for the token added by
560
          // file_managed_file_process().
561
          elseif (!$GLOBALS['user']->uid) {
562
            $token = drupal_array_get_nested_value($form_state['input'], array_merge($element['#parents'], array('fid_token')));
563
            if ($token !== drupal_hmac_base64('file-' . $file->fid, drupal_get_private_key() . drupal_get_hash_salt())) {
564
              $force_default = TRUE;
565
            }
566
          }
567
        }
568
        // If all checks pass, allow the file to be changed.
569
        if (!$force_default) {
570
          $fid = $file->fid;
571
        }
572
      }
573
    }
574
  }
575

    
576
  // If there is no input or if the default value was requested above, use the
577
  // default value.
578
  if ($input === FALSE || $force_default) {
579
    if ($element['#extended']) {
580
      $default_fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
581
      $return = isset($element['#default_value']) ? $element['#default_value'] : array('fid' => 0);
582
    }
583
    else {
584
      $default_fid = isset($element['#default_value']) ? $element['#default_value'] : 0;
585
      $return = array('fid' => 0);
586
    }
587

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

    
594
  $return['fid'] = $fid;
595

    
596
  return $return;
597
}
598

    
599
/**
600
 * An #element_validate callback for the managed_file element.
601
 */
602
function file_managed_file_validate(&$element, &$form_state) {
603
  // If referencing an existing file, only allow if there are existing
604
  // references. This prevents unmanaged files from being deleted if this
605
  // item were to be deleted.
606
  $clicked_button = end($form_state['triggering_element']['#parents']);
607
  if ($clicked_button != 'remove_button' && !empty($element['fid']['#value'])) {
608
    if ($file = file_load($element['fid']['#value'])) {
609
      if ($file->status == FILE_STATUS_PERMANENT) {
610
        $references = file_usage_list($file);
611
        if (empty($references)) {
612
          form_error($element, t('The file used in the !name field may not be referenced.', array('!name' => $element['#title'])));
613
        }
614
      }
615
    }
616
    else {
617
      form_error($element, t('The file referenced by the !name field does not exist.', array('!name' => $element['#title'])));
618
    }
619
  }
620

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

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

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

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

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

    
675
/**
676
 * Saves any files that have been uploaded into a managed_file element.
677
 *
678
 * @param $element
679
 *   The FAPI element whose values are being saved.
680
 *
681
 * @return
682
 *   The file object representing the file that was saved, or FALSE if no file
683
 *   was saved.
684
 */
685
function file_managed_file_save_upload($element) {
686
  $upload_name = implode('_', $element['#parents']);
687
  if (empty($_FILES['files']['name'][$upload_name])) {
688
    return FALSE;
689
  }
690

    
691
  $destination = isset($element['#upload_location']) ? $element['#upload_location'] : NULL;
692
  if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
693
    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']));
694
    form_set_error($upload_name, t('The file could not be uploaded.'));
695
    return FALSE;
696
  }
697

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

    
704
  return $file;
705
}
706

    
707
/**
708
 * Returns HTML for a managed file element.
709
 *
710
 * @param $variables
711
 *   An associative array containing:
712
 *   - element: A render element representing the file.
713
 *
714
 * @ingroup themeable
715
 */
716
function theme_file_managed_file($variables) {
717
  $element = $variables['element'];
718

    
719
  $attributes = array();
720
  if (isset($element['#id'])) {
721
    $attributes['id'] = $element['#id'];
722
  }
723
  if (!empty($element['#attributes']['class'])) {
724
    $attributes['class'] = (array) $element['#attributes']['class'];
725
  }
726
  $attributes['class'][] = 'form-managed-file';
727

    
728
  // This wrapper is required to apply JS behaviors and CSS styling.
729
  $output = '';
730
  $output .= '<div' . drupal_attributes($attributes) . '>';
731
  $output .= drupal_render_children($element);
732
  $output .= '</div>';
733
  return $output;
734
}
735

    
736
/**
737
 * #pre_render callback to hide display of the upload or remove controls.
738
 *
739
 * Upload controls are hidden when a file is already uploaded. Remove controls
740
 * are hidden when there is no file attached. Controls are hidden here instead
741
 * of in file_managed_file_process(), because #access for these buttons depends
742
 * on the managed_file element's #value. See the documentation of form_builder()
743
 * for more detailed information about the relationship between #process,
744
 * #value, and #access.
745
 *
746
 * Because #access is set here, it affects display only and does not prevent
747
 * JavaScript or other untrusted code from submitting the form as though access
748
 * were enabled. The form processing functions for these elements should not
749
 * assume that the buttons can't be "clicked" just because they are not
750
 * displayed.
751
 *
752
 * @see file_managed_file_process()
753
 * @see form_builder()
754
 */
755
function file_managed_file_pre_render($element) {
756
  // If we already have a file, we don't want to show the upload controls.
757
  if (!empty($element['#value']['fid'])) {
758
    $element['upload']['#access'] = FALSE;
759
    $element['upload_button']['#access'] = FALSE;
760
  }
761
  // If we don't already have a file, there is nothing to remove.
762
  else {
763
    $element['remove_button']['#access'] = FALSE;
764
  }
765
  return $element;
766
}
767

    
768
/**
769
 * Returns HTML for a link to a file.
770
 *
771
 * @param $variables
772
 *   An associative array containing:
773
 *   - file: A file object to which the link will be created.
774
 *   - icon_directory: (optional) A path to a directory of icons to be used for
775
 *     files. Defaults to the value of the "file_icon_directory" variable.
776
 *
777
 * @ingroup themeable
778
 */
779
function theme_file_link($variables) {
780
  $file = $variables['file'];
781
  $icon_directory = $variables['icon_directory'];
782

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

    
785
  // Human-readable names, for use as text-alternatives to icons.
786
  $mime_name = array(
787
    'application/msword' => t('Microsoft Office document icon'),
788
    'application/vnd.ms-excel' => t('Office spreadsheet icon'),
789
    'application/vnd.ms-powerpoint' => t('Office presentation icon'),
790
    'application/pdf' => t('PDF icon'),
791
    'video/quicktime' => t('Movie icon'),
792
    'audio/mpeg' => t('Audio icon'),
793
    'audio/wav' => t('Audio icon'),
794
    'image/jpeg' => t('Image icon'),
795
    'image/png' => t('Image icon'),
796
    'image/gif' => t('Image icon'),
797
    'application/zip' => t('Package icon'),
798
    'text/html' => t('HTML icon'),
799
    'text/plain' => t('Plain text icon'),
800
    'application/octet-stream' => t('Binary Data'),
801
  );
802

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

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

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

    
819
  // Use the description as the link text if available.
820
  if (empty($file->description)) {
821
    $link_text = $file->filename;
822
  }
823
  else {
824
    $link_text = $file->description;
825
    $options['attributes']['title'] = check_plain($file->filename);
826
  }
827

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

    
831
/**
832
 * Returns HTML for an image with an appropriate icon for the given file.
833
 *
834
 * @param $variables
835
 *   An associative array containing:
836
 *   - file: A file object for which to make an icon.
837
 *   - icon_directory: (optional) A path to a directory of icons to be used for
838
 *     files. Defaults to the value of the "file_icon_directory" variable.
839
 *   - alt: (optional) The alternative text to represent the icon in text-based
840
 *     browsers. Defaults to an empty string.
841
 *
842
 * @ingroup themeable
843
 */
844
function theme_file_icon($variables) {
845
  $file = $variables['file'];
846
  $alt = $variables['alt'];
847
  $icon_directory = $variables['icon_directory'];
848

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

    
854
/**
855
 * Creates a URL to the icon for a file object.
856
 *
857
 * @param $file
858
 *   A file object.
859
 * @param $icon_directory
860
 *   (optional) A path to a directory of icons to be used for files. Defaults to
861
 *   the value of the "file_icon_directory" variable.
862
 *
863
 * @return
864
 *   A URL string to the icon, or FALSE if an appropriate icon cannot be found.
865
 */
866
function file_icon_url($file, $icon_directory = NULL) {
867
  if ($icon_path = file_icon_path($file, $icon_directory)) {
868
    return base_path() . $icon_path;
869
  }
870
  return FALSE;
871
}
872

    
873
/**
874
 * Creates a path to the icon for a file object.
875
 *
876
 * @param $file
877
 *   A file object.
878
 * @param $icon_directory
879
 *   (optional) A path to a directory of icons to be used for files. Defaults to
880
 *   the value of the "file_icon_directory" variable.
881
 *
882
 * @return
883
 *   A string to the icon as a local path, or FALSE if an appropriate icon could
884
 *   not be found.
885
 */
886
function file_icon_path($file, $icon_directory = NULL) {
887
  // Use the default set of icons if none specified.
888
  if (!isset($icon_directory)) {
889
    $icon_directory = variable_get('file_icon_directory', drupal_get_path('module', 'file') . '/icons');
890
  }
891

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

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

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

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

    
922
  // No icon can be found.
923
  return FALSE;
924
}
925

    
926
/**
927
 * Determines the generic icon MIME package based on a file's MIME type.
928
 *
929
 * @param $file
930
 *   A file object.
931
 *
932
 * @return
933
 *   The generic icon MIME package expected for this file.
934
 */
935
function file_icon_map($file) {
936
  switch ($file->filemime) {
937
    // Word document types.
938
    case 'application/msword':
939
    case 'application/vnd.ms-word.document.macroEnabled.12':
940
    case 'application/vnd.oasis.opendocument.text':
941
    case 'application/vnd.oasis.opendocument.text-template':
942
    case 'application/vnd.oasis.opendocument.text-master':
943
    case 'application/vnd.oasis.opendocument.text-web':
944
    case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
945
    case 'application/vnd.stardivision.writer':
946
    case 'application/vnd.sun.xml.writer':
947
    case 'application/vnd.sun.xml.writer.template':
948
    case 'application/vnd.sun.xml.writer.global':
949
    case 'application/vnd.wordperfect':
950
    case 'application/x-abiword':
951
    case 'application/x-applix-word':
952
    case 'application/x-kword':
953
    case 'application/x-kword-crypt':
954
      return 'x-office-document';
955

    
956
    // Spreadsheet document types.
957
    case 'application/vnd.ms-excel':
958
    case 'application/vnd.ms-excel.sheet.macroEnabled.12':
959
    case 'application/vnd.oasis.opendocument.spreadsheet':
960
    case 'application/vnd.oasis.opendocument.spreadsheet-template':
961
    case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
962
    case 'application/vnd.stardivision.calc':
963
    case 'application/vnd.sun.xml.calc':
964
    case 'application/vnd.sun.xml.calc.template':
965
    case 'application/vnd.lotus-1-2-3':
966
    case 'application/x-applix-spreadsheet':
967
    case 'application/x-gnumeric':
968
    case 'application/x-kspread':
969
    case 'application/x-kspread-crypt':
970
      return 'x-office-spreadsheet';
971

    
972
    // Presentation document types.
973
    case 'application/vnd.ms-powerpoint':
974
    case 'application/vnd.ms-powerpoint.presentation.macroEnabled.12':
975
    case 'application/vnd.oasis.opendocument.presentation':
976
    case 'application/vnd.oasis.opendocument.presentation-template':
977
    case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
978
    case 'application/vnd.stardivision.impress':
979
    case 'application/vnd.sun.xml.impress':
980
    case 'application/vnd.sun.xml.impress.template':
981
    case 'application/x-kpresenter':
982
      return 'x-office-presentation';
983

    
984
    // Compressed archive types.
985
    case 'application/zip':
986
    case 'application/x-zip':
987
    case 'application/stuffit':
988
    case 'application/x-stuffit':
989
    case 'application/x-7z-compressed':
990
    case 'application/x-ace':
991
    case 'application/x-arj':
992
    case 'application/x-bzip':
993
    case 'application/x-bzip-compressed-tar':
994
    case 'application/x-compress':
995
    case 'application/x-compressed-tar':
996
    case 'application/x-cpio-compressed':
997
    case 'application/x-deb':
998
    case 'application/x-gzip':
999
    case 'application/x-java-archive':
1000
    case 'application/x-lha':
1001
    case 'application/x-lhz':
1002
    case 'application/x-lzop':
1003
    case 'application/x-rar':
1004
    case 'application/x-rpm':
1005
    case 'application/x-tzo':
1006
    case 'application/x-tar':
1007
    case 'application/x-tarz':
1008
    case 'application/x-tgz':
1009
      return 'package-x-generic';
1010

    
1011
    // Script file types.
1012
    case 'application/ecmascript':
1013
    case 'application/javascript':
1014
    case 'application/mathematica':
1015
    case 'application/vnd.mozilla.xul+xml':
1016
    case 'application/x-asp':
1017
    case 'application/x-awk':
1018
    case 'application/x-cgi':
1019
    case 'application/x-csh':
1020
    case 'application/x-m4':
1021
    case 'application/x-perl':
1022
    case 'application/x-php':
1023
    case 'application/x-ruby':
1024
    case 'application/x-shellscript':
1025
    case 'text/vnd.wap.wmlscript':
1026
    case 'text/x-emacs-lisp':
1027
    case 'text/x-haskell':
1028
    case 'text/x-literate-haskell':
1029
    case 'text/x-lua':
1030
    case 'text/x-makefile':
1031
    case 'text/x-matlab':
1032
    case 'text/x-python':
1033
    case 'text/x-sql':
1034
    case 'text/x-tcl':
1035
      return 'text-x-script';
1036

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

    
1041
    // Executable types.
1042
    case 'application/x-macbinary':
1043
    case 'application/x-ms-dos-executable':
1044
    case 'application/x-pef-executable':
1045
      return 'application-x-executable';
1046

    
1047
    default:
1048
      return FALSE;
1049
  }
1050
}
1051

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

    
1058
/**
1059
 * Retrieves a list of references to a file.
1060
 *
1061
 * @param $file
1062
 *   A file object.
1063
 * @param $field
1064
 *   (optional) A field array to be used for this check. If given, limits the
1065
 *   reference check to the given field.
1066
 * @param $age
1067
 *   (optional) A constant that specifies which references to count. Use
1068
 *   FIELD_LOAD_REVISION to retrieve all references within all revisions or
1069
 *   FIELD_LOAD_CURRENT to retrieve references only in the current revisions.
1070
 * @param $field_type
1071
 *   (optional) The name of a field type. If given, limits the reference check
1072
 *   to fields of the given type.
1073
 * @param $check_access
1074
 *   (optional) A boolean that specifies whether the permissions of the current
1075
 *   user should be checked when retrieving references. If FALSE, all
1076
 *   references to the file are returned. If TRUE, only references from
1077
 *   entities that the current user has access to are returned. Defaults to
1078
 *   TRUE for backwards compatibility reasons, but FALSE is recommended for
1079
 *   most situations.
1080
 *
1081
 * @return
1082
 *   An integer value.
1083
 */
1084
function file_get_file_references($file, $field = NULL, $age = FIELD_LOAD_REVISION, $field_type = 'file', $check_access = TRUE) {
1085
  $references = drupal_static(__FUNCTION__, array());
1086
  $fields = isset($field) ? array($field['field_name'] => $field) : field_info_fields();
1087

    
1088
  foreach ($fields as $field_name => $file_field) {
1089
    if ((empty($field_type) || $file_field['type'] == $field_type) && !isset($references[$field_name])) {
1090
      // Get each time this file is used within a field.
1091
      $query = new EntityFieldQuery();
1092
      $query
1093
        ->fieldCondition($file_field, 'fid', $file->fid)
1094
        ->age($age);
1095
      if (!$check_access) {
1096
        // Neutralize the 'entity_field_access' query tag added by
1097
        // field_sql_storage_field_storage_query().
1098
        $query->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
1099
      }
1100
      $references[$field_name] = $query->execute();
1101
    }
1102
  }
1103

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

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