Projet

Général

Profil

Paste
Télécharger (38,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / file / file.module @ 6ff32cea

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),
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);
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.
150
  if (empty($references) && ($file->status == FILE_STATUS_PERMANENT || $file->uid != $user->uid)) {
151
      return;
152
  }
153

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
283
  $output = theme('status_messages') . drupal_render($form);
284
  $js = drupal_add_js();
285
  $settings = call_user_func_array('array_merge_recursive', $js['settings']['data']);
286

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

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

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

    
319
  drupal_json_output($progress);
320
}
321

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

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

    
346
/**
347
 * Implements hook_file_delete().
348
 */
349
function file_file_delete($file) {
350
  // TODO: Remove references to a file that is in-use.
351
}
352

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

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

    
371
  $ajax_settings = array(
372
    'path' => 'file/ajax/' . implode('/', $element['#array_parents']) . '/' . $form['form_build_id']['#value'],
373
    'wrapper' => $original_id . '-ajax-wrapper',
374
    'effect' => 'fade',
375
    'progress' => array(
376
      'type' => $element['#progress_indicator'],
377
      'message' => $element['#progress_message'],
378
    ),
379
  );
380

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

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

    
409
  $element['fid'] = array(
410
    '#type' => 'hidden',
411
    '#value' => $fid,
412
  );
413

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

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

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

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

    
454
  if ($fid && $element['#file']) {
455
    $element['filename'] = array(
456
      '#type' => 'markup',
457
      '#markup' => theme('file_link', array('file' => $element['#file'])) . ' ',
458
      '#weight' => -10,
459
    );
460
  }
461

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

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

    
477
  return $element;
478
}
479

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

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

    
493
  if ($element['#extended'] && isset($form_state_fid['fid'])) {
494
    $fid = $form_state_fid['fid'];
495
  }
496
  elseif (is_numeric($form_state_fid)) {
497
    $fid = $form_state_fid;
498
  }
499

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

    
504
    // Uploads take priority over all other values.
505
    if ($file = file_managed_file_save_upload($element)) {
506
      $fid = $file->fid;
507
    }
508
    else {
509
      // Check for #filefield_value_callback values.
510
      // Because FAPI does not allow multiple #value_callback values like it
511
      // does for #element_validate and #process, this fills the missing
512
      // functionality to allow File fields to be extended through FAPI.
513
      if (isset($element['#file_value_callbacks'])) {
514
        foreach ($element['#file_value_callbacks'] as $callback) {
515
          $callback($element, $input, $form_state);
516
        }
517
      }
518
      // If a FID was submitted, load the file (and check access if it's not a
519
      // public file) to confirm it exists and that the current user has access
520
      // to it.
521
      if (isset($input['fid']) && ($file = file_load($input['fid']))) {
522
        // By default the public:// file scheme provided by Drupal core is the
523
        // only one that allows files to be publicly accessible to everyone, so
524
        // it is the only one for which the file access checks are bypassed.
525
        // Other modules which provide publicly accessible streams of their own
526
        // in hook_stream_wrappers() can add the corresponding scheme to the
527
        // 'file_public_schema' variable to bypass file access checks for those
528
        // as well. This should only be done for schemes that are completely
529
        // publicly accessible, with no download restrictions; for security
530
        // reasons all other schemes must go through the file_download_access()
531
        // check.
532
        if (in_array(file_uri_scheme($file->uri), variable_get('file_public_schema', array('public'))) || file_download_access($file->uri)) {
533
          $fid = $file->fid;
534
        }
535
        // If the current user doesn't have access, don't let the file be
536
        // changed.
537
        else {
538
          $force_default = TRUE;
539
        }
540
      }
541
    }
542
  }
543

    
544
  // If there is no input or if the default value was requested above, use the
545
  // default value.
546
  if ($input === FALSE || $force_default) {
547
    if ($element['#extended']) {
548
      $default_fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
549
      $return = isset($element['#default_value']) ? $element['#default_value'] : array('fid' => 0);
550
    }
551
    else {
552
      $default_fid = isset($element['#default_value']) ? $element['#default_value'] : 0;
553
      $return = array('fid' => 0);
554
    }
555

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

    
562
  $return['fid'] = $fid;
563

    
564
  return $return;
565
}
566

    
567
/**
568
 * An #element_validate callback for the managed_file element.
569
 */
570
function file_managed_file_validate(&$element, &$form_state) {
571
  // If referencing an existing file, only allow if there are existing
572
  // references. This prevents unmanaged files from being deleted if this
573
  // item were to be deleted.
574
  $clicked_button = end($form_state['triggering_element']['#parents']);
575
  if ($clicked_button != 'remove_button' && !empty($element['fid']['#value'])) {
576
    if ($file = file_load($element['fid']['#value'])) {
577
      if ($file->status == FILE_STATUS_PERMANENT) {
578
        $references = file_usage_list($file);
579
        if (empty($references)) {
580
          form_error($element, t('The file used in the !name field may not be referenced.', array('!name' => $element['#title'])));
581
        }
582
      }
583
    }
584
    else {
585
      form_error($element, t('The file referenced by the !name field does not exist.', array('!name' => $element['#title'])));
586
    }
587
  }
588

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

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

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

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

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

    
643
/**
644
 * Saves any files that have been uploaded into a managed_file element.
645
 *
646
 * @param $element
647
 *   The FAPI element whose values are being saved.
648
 *
649
 * @return
650
 *   The file object representing the file that was saved, or FALSE if no file
651
 *   was saved.
652
 */
653
function file_managed_file_save_upload($element) {
654
  $upload_name = implode('_', $element['#parents']);
655
  if (empty($_FILES['files']['name'][$upload_name])) {
656
    return FALSE;
657
  }
658

    
659
  $destination = isset($element['#upload_location']) ? $element['#upload_location'] : NULL;
660
  if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
661
    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']));
662
    form_set_error($upload_name, t('The file could not be uploaded.'));
663
    return FALSE;
664
  }
665

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

    
672
  return $file;
673
}
674

    
675
/**
676
 * Returns HTML for a managed file element.
677
 *
678
 * @param $variables
679
 *   An associative array containing:
680
 *   - element: A render element representing the file.
681
 *
682
 * @ingroup themeable
683
 */
684
function theme_file_managed_file($variables) {
685
  $element = $variables['element'];
686

    
687
  $attributes = array();
688
  if (isset($element['#id'])) {
689
    $attributes['id'] = $element['#id'];
690
  }
691
  if (!empty($element['#attributes']['class'])) {
692
    $attributes['class'] = (array) $element['#attributes']['class'];
693
  }
694
  $attributes['class'][] = 'form-managed-file';
695

    
696
  // This wrapper is required to apply JS behaviors and CSS styling.
697
  $output = '';
698
  $output .= '<div' . drupal_attributes($attributes) . '>';
699
  $output .= drupal_render_children($element);
700
  $output .= '</div>';
701
  return $output;
702
}
703

    
704
/**
705
 * #pre_render callback to hide display of the upload or remove controls.
706
 *
707
 * Upload controls are hidden when a file is already uploaded. Remove controls
708
 * are hidden when there is no file attached. Controls are hidden here instead
709
 * of in file_managed_file_process(), because #access for these buttons depends
710
 * on the managed_file element's #value. See the documentation of form_builder()
711
 * for more detailed information about the relationship between #process,
712
 * #value, and #access.
713
 *
714
 * Because #access is set here, it affects display only and does not prevent
715
 * JavaScript or other untrusted code from submitting the form as though access
716
 * were enabled. The form processing functions for these elements should not
717
 * assume that the buttons can't be "clicked" just because they are not
718
 * displayed.
719
 *
720
 * @see file_managed_file_process()
721
 * @see form_builder()
722
 */
723
function file_managed_file_pre_render($element) {
724
  // If we already have a file, we don't want to show the upload controls.
725
  if (!empty($element['#value']['fid'])) {
726
    $element['upload']['#access'] = FALSE;
727
    $element['upload_button']['#access'] = FALSE;
728
  }
729
  // If we don't already have a file, there is nothing to remove.
730
  else {
731
    $element['remove_button']['#access'] = FALSE;
732
  }
733
  return $element;
734
}
735

    
736
/**
737
 * Returns HTML for a link to a file.
738
 *
739
 * @param $variables
740
 *   An associative array containing:
741
 *   - file: A file object to which the link will be created.
742
 *   - icon_directory: (optional) A path to a directory of icons to be used for
743
 *     files. Defaults to the value of the "file_icon_directory" variable.
744
 *
745
 * @ingroup themeable
746
 */
747
function theme_file_link($variables) {
748
  $file = $variables['file'];
749
  $icon_directory = $variables['icon_directory'];
750

    
751
  $url = file_create_url($file->uri);
752
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));
753

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

    
762
  // Use the description as the link text if available.
763
  if (empty($file->description)) {
764
    $link_text = $file->filename;
765
  }
766
  else {
767
    $link_text = $file->description;
768
    $options['attributes']['title'] = check_plain($file->filename);
769
  }
770

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

    
774
/**
775
 * Returns HTML for an image with an appropriate icon for the given file.
776
 *
777
 * @param $variables
778
 *   An associative array containing:
779
 *   - file: A file object for which to make an icon.
780
 *   - icon_directory: (optional) A path to a directory of icons to be used for
781
 *     files. Defaults to the value of the "file_icon_directory" variable.
782
 *
783
 * @ingroup themeable
784
 */
785
function theme_file_icon($variables) {
786
  $file = $variables['file'];
787
  $icon_directory = $variables['icon_directory'];
788

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

    
794
/**
795
 * Creates a URL to the icon for a file object.
796
 *
797
 * @param $file
798
 *   A file object.
799
 * @param $icon_directory
800
 *   (optional) A path to a directory of icons to be used for files. Defaults to
801
 *   the value of the "file_icon_directory" variable.
802
 *
803
 * @return
804
 *   A URL string to the icon, or FALSE if an appropriate icon cannot be found.
805
 */
806
function file_icon_url($file, $icon_directory = NULL) {
807
  if ($icon_path = file_icon_path($file, $icon_directory)) {
808
    return base_path() . $icon_path;
809
  }
810
  return FALSE;
811
}
812

    
813
/**
814
 * Creates a path to the icon for a file object.
815
 *
816
 * @param $file
817
 *   A file object.
818
 * @param $icon_directory
819
 *   (optional) A path to a directory of icons to be used for files. Defaults to
820
 *   the value of the "file_icon_directory" variable.
821
 *
822
 * @return
823
 *   A string to the icon as a local path, or FALSE if an appropriate icon could
824
 *   not be found.
825
 */
826
function file_icon_path($file, $icon_directory = NULL) {
827
  // Use the default set of icons if none specified.
828
  if (!isset($icon_directory)) {
829
    $icon_directory = variable_get('file_icon_directory', drupal_get_path('module', 'file') . '/icons');
830
  }
831

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

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

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

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

    
862
  // No icon can be found.
863
  return FALSE;
864
}
865

    
866
/**
867
 * Determines the generic icon MIME package based on a file's MIME type.
868
 *
869
 * @param $file
870
 *   A file object.
871
 *
872
 * @return
873
 *   The generic icon MIME package expected for this file.
874
 */
875
function file_icon_map($file) {
876
  switch ($file->filemime) {
877
    // Word document types.
878
    case 'application/msword':
879
    case 'application/vnd.ms-word.document.macroEnabled.12':
880
    case 'application/vnd.oasis.opendocument.text':
881
    case 'application/vnd.oasis.opendocument.text-template':
882
    case 'application/vnd.oasis.opendocument.text-master':
883
    case 'application/vnd.oasis.opendocument.text-web':
884
    case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
885
    case 'application/vnd.stardivision.writer':
886
    case 'application/vnd.sun.xml.writer':
887
    case 'application/vnd.sun.xml.writer.template':
888
    case 'application/vnd.sun.xml.writer.global':
889
    case 'application/vnd.wordperfect':
890
    case 'application/x-abiword':
891
    case 'application/x-applix-word':
892
    case 'application/x-kword':
893
    case 'application/x-kword-crypt':
894
      return 'x-office-document';
895

    
896
    // Spreadsheet document types.
897
    case 'application/vnd.ms-excel':
898
    case 'application/vnd.ms-excel.sheet.macroEnabled.12':
899
    case 'application/vnd.oasis.opendocument.spreadsheet':
900
    case 'application/vnd.oasis.opendocument.spreadsheet-template':
901
    case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
902
    case 'application/vnd.stardivision.calc':
903
    case 'application/vnd.sun.xml.calc':
904
    case 'application/vnd.sun.xml.calc.template':
905
    case 'application/vnd.lotus-1-2-3':
906
    case 'application/x-applix-spreadsheet':
907
    case 'application/x-gnumeric':
908
    case 'application/x-kspread':
909
    case 'application/x-kspread-crypt':
910
      return 'x-office-spreadsheet';
911

    
912
    // Presentation document types.
913
    case 'application/vnd.ms-powerpoint':
914
    case 'application/vnd.ms-powerpoint.presentation.macroEnabled.12':
915
    case 'application/vnd.oasis.opendocument.presentation':
916
    case 'application/vnd.oasis.opendocument.presentation-template':
917
    case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
918
    case 'application/vnd.stardivision.impress':
919
    case 'application/vnd.sun.xml.impress':
920
    case 'application/vnd.sun.xml.impress.template':
921
    case 'application/x-kpresenter':
922
      return 'x-office-presentation';
923

    
924
    // Compressed archive types.
925
    case 'application/zip':
926
    case 'application/x-zip':
927
    case 'application/stuffit':
928
    case 'application/x-stuffit':
929
    case 'application/x-7z-compressed':
930
    case 'application/x-ace':
931
    case 'application/x-arj':
932
    case 'application/x-bzip':
933
    case 'application/x-bzip-compressed-tar':
934
    case 'application/x-compress':
935
    case 'application/x-compressed-tar':
936
    case 'application/x-cpio-compressed':
937
    case 'application/x-deb':
938
    case 'application/x-gzip':
939
    case 'application/x-java-archive':
940
    case 'application/x-lha':
941
    case 'application/x-lhz':
942
    case 'application/x-lzop':
943
    case 'application/x-rar':
944
    case 'application/x-rpm':
945
    case 'application/x-tzo':
946
    case 'application/x-tar':
947
    case 'application/x-tarz':
948
    case 'application/x-tgz':
949
      return 'package-x-generic';
950

    
951
    // Script file types.
952
    case 'application/ecmascript':
953
    case 'application/javascript':
954
    case 'application/mathematica':
955
    case 'application/vnd.mozilla.xul+xml':
956
    case 'application/x-asp':
957
    case 'application/x-awk':
958
    case 'application/x-cgi':
959
    case 'application/x-csh':
960
    case 'application/x-m4':
961
    case 'application/x-perl':
962
    case 'application/x-php':
963
    case 'application/x-ruby':
964
    case 'application/x-shellscript':
965
    case 'text/vnd.wap.wmlscript':
966
    case 'text/x-emacs-lisp':
967
    case 'text/x-haskell':
968
    case 'text/x-literate-haskell':
969
    case 'text/x-lua':
970
    case 'text/x-makefile':
971
    case 'text/x-matlab':
972
    case 'text/x-python':
973
    case 'text/x-sql':
974
    case 'text/x-tcl':
975
      return 'text-x-script';
976

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

    
981
    // Executable types.
982
    case 'application/x-macbinary':
983
    case 'application/x-ms-dos-executable':
984
    case 'application/x-pef-executable':
985
      return 'application-x-executable';
986

    
987
    default:
988
      return FALSE;
989
  }
990
}
991

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

    
998
/**
999
 * Retrieves a list of references to a file.
1000
 *
1001
 * @param $file
1002
 *   A file object.
1003
 * @param $field
1004
 *   (optional) A field array to be used for this check. If given, limits the
1005
 *   reference check to the given field.
1006
 * @param $age
1007
 *   (optional) A constant that specifies which references to count. Use
1008
 *   FIELD_LOAD_REVISION to retrieve all references within all revisions or
1009
 *   FIELD_LOAD_CURRENT to retrieve references only in the current revisions.
1010
 * @param $field_type
1011
 *   (optional) The name of a field type. If given, limits the reference check
1012
 *   to fields of the given type.
1013
 *
1014
 * @return
1015
 *   An integer value.
1016
 */
1017
function file_get_file_references($file, $field = NULL, $age = FIELD_LOAD_REVISION, $field_type = 'file') {
1018
  $references = drupal_static(__FUNCTION__, array());
1019
  $fields = isset($field) ? array($field['field_name'] => $field) : field_info_fields();
1020

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

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

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