Projet

Général

Profil

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

root / htmltest / modules / file / file.module @ 85ad3d82

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) = 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 = array();
288
  $commands[] = ajax_command_replace(NULL, $output, $settings);
289
  return array('#type' => 'ajax', '#commands' => $commands);
290
}
291

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

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

    
320
  drupal_json_output($progress);
321
}
322

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

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

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

    
354
/**
355
 * Process function to expand the managed_file element type.
356
 *
357
 * Expands the file type to include Upload and Remove buttons, as well as
358
 * support for a default value.
359
 */
360
function file_managed_file_process($element, &$form_state, $form) {
361
  $fid = isset($element['#value']['fid']) ? $element['#value']['fid'] : 0;
362

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

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

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

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

    
406
  $element['fid'] = array(
407
    '#type' => 'hidden',
408
    '#value' => $fid,
409
  );
410

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

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

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

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

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

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

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

    
474
  return $element;
475
}
476

    
477
/**
478
 * The #value_callback for a managed_file type element.
479
 */
480
function file_managed_file_value(&$element, $input = FALSE, $form_state = NULL) {
481
  $fid = 0;
482

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

    
489
  if ($element['#extended'] && isset($form_state_fid['fid'])) {
490
    $fid = $form_state_fid['fid'];
491
  }
492
  elseif (is_numeric($form_state_fid)) {
493
    $fid = $form_state_fid;
494
  }
495

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

    
500
    // Uploads take priority over all other values.
501
    if ($file = file_managed_file_save_upload($element)) {
502
      $fid = $file->fid;
503
    }
504
    else {
505
      // Check for #filefield_value_callback values.
506
      // Because FAPI does not allow multiple #value_callback values like it
507
      // does for #element_validate and #process, this fills the missing
508
      // functionality to allow File fields to be extended through FAPI.
509
      if (isset($element['#file_value_callbacks'])) {
510
        foreach ($element['#file_value_callbacks'] as $callback) {
511
          $callback($element, $input, $form_state);
512
        }
513
      }
514
      // Load file if the FID has changed to confirm it exists.
515
      if (isset($input['fid']) && $file = file_load($input['fid'])) {
516
        $fid = $file->fid;
517
      }
518
    }
519
  }
520

    
521
  // If there is no input, set the default value.
522
  else {
523
    if ($element['#extended']) {
524
      $default_fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
525
      $return = isset($element['#default_value']) ? $element['#default_value'] : array('fid' => 0);
526
    }
527
    else {
528
      $default_fid = isset($element['#default_value']) ? $element['#default_value'] : 0;
529
      $return = array('fid' => 0);
530
    }
531

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

    
538
  $return['fid'] = $fid;
539

    
540
  return $return;
541
}
542

    
543
/**
544
 * An #element_validate callback for the managed_file element.
545
 */
546
function file_managed_file_validate(&$element, &$form_state) {
547
  // If referencing an existing file, only allow if there are existing
548
  // references. This prevents unmanaged files from being deleted if this
549
  // item were to be deleted.
550
  $clicked_button = end($form_state['triggering_element']['#parents']);
551
  if ($clicked_button != 'remove_button' && !empty($element['fid']['#value'])) {
552
    if ($file = file_load($element['fid']['#value'])) {
553
      if ($file->status == FILE_STATUS_PERMANENT) {
554
        $references = file_usage_list($file);
555
        if (empty($references)) {
556
          form_error($element, t('The file used in the !name field may not be referenced.', array('!name' => $element['#title'])));
557
        }
558
      }
559
    }
560
    else {
561
      form_error($element, t('The file referenced by the !name field does not exist.', array('!name' => $element['#title'])));
562
    }
563
  }
564

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

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

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

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

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

    
619
/**
620
 * Saves any files that have been uploaded into a managed_file element.
621
 *
622
 * @param $element
623
 *   The FAPI element whose values are being saved.
624
 *
625
 * @return
626
 *   The file object representing the file that was saved, or FALSE if no file
627
 *   was saved.
628
 */
629
function file_managed_file_save_upload($element) {
630
  $upload_name = implode('_', $element['#parents']);
631
  if (empty($_FILES['files']['name'][$upload_name])) {
632
    return FALSE;
633
  }
634

    
635
  $destination = isset($element['#upload_location']) ? $element['#upload_location'] : NULL;
636
  if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
637
    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']));
638
    form_set_error($upload_name, t('The file could not be uploaded.'));
639
    return FALSE;
640
  }
641

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

    
648
  return $file;
649
}
650

    
651
/**
652
 * Returns HTML for a managed file element.
653
 *
654
 * @param $variables
655
 *   An associative array containing:
656
 *   - element: A render element representing the file.
657
 *
658
 * @ingroup themeable
659
 */
660
function theme_file_managed_file($variables) {
661
  $element = $variables['element'];
662

    
663
  $attributes = array();
664
  if (isset($element['#id'])) {
665
    $attributes['id'] = $element['#id'];
666
  }
667
  if (!empty($element['#attributes']['class'])) {
668
    $attributes['class'] = (array) $element['#attributes']['class'];
669
  }
670
  $attributes['class'][] = 'form-managed-file';
671

    
672
  // This wrapper is required to apply JS behaviors and CSS styling.
673
  $output = '';
674
  $output .= '<div' . drupal_attributes($attributes) . '>';
675
  $output .= drupal_render_children($element);
676
  $output .= '</div>';
677
  return $output;
678
}
679

    
680
/**
681
 * #pre_render callback to hide display of the upload or remove controls.
682
 *
683
 * Upload controls are hidden when a file is already uploaded. Remove controls
684
 * are hidden when there is no file attached. Controls are hidden here instead
685
 * of in file_managed_file_process(), because #access for these buttons depends
686
 * on the managed_file element's #value. See the documentation of form_builder()
687
 * for more detailed information about the relationship between #process,
688
 * #value, and #access.
689
 *
690
 * Because #access is set here, it affects display only and does not prevent
691
 * JavaScript or other untrusted code from submitting the form as though access
692
 * were enabled. The form processing functions for these elements should not
693
 * assume that the buttons can't be "clicked" just because they are not
694
 * displayed.
695
 *
696
 * @see file_managed_file_process()
697
 * @see form_builder()
698
 */
699
function file_managed_file_pre_render($element) {
700
  // If we already have a file, we don't want to show the upload controls.
701
  if (!empty($element['#value']['fid'])) {
702
    $element['upload']['#access'] = FALSE;
703
    $element['upload_button']['#access'] = FALSE;
704
  }
705
  // If we don't already have a file, there is nothing to remove.
706
  else {
707
    $element['remove_button']['#access'] = FALSE;
708
  }
709
  return $element;
710
}
711

    
712
/**
713
 * Returns HTML for a link to a file.
714
 *
715
 * @param $variables
716
 *   An associative array containing:
717
 *   - file: A file object to which the link will be created.
718
 *   - icon_directory: (optional) A path to a directory of icons to be used for
719
 *     files. Defaults to the value of the "file_icon_directory" variable.
720
 *
721
 * @ingroup themeable
722
 */
723
function theme_file_link($variables) {
724
  $file = $variables['file'];
725
  $icon_directory = $variables['icon_directory'];
726

    
727
  $url = file_create_url($file->uri);
728
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));
729

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

    
738
  // Use the description as the link text if available.
739
  if (empty($file->description)) {
740
    $link_text = $file->filename;
741
  }
742
  else {
743
    $link_text = $file->description;
744
    $options['attributes']['title'] = check_plain($file->filename);
745
  }
746

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

    
750
/**
751
 * Returns HTML for an image with an appropriate icon for the given file.
752
 *
753
 * @param $variables
754
 *   An associative array containing:
755
 *   - file: A file object for which to make an icon.
756
 *   - icon_directory: (optional) A path to a directory of icons to be used for
757
 *     files. Defaults to the value of the "file_icon_directory" variable.
758
 *
759
 * @ingroup themeable
760
 */
761
function theme_file_icon($variables) {
762
  $file = $variables['file'];
763
  $icon_directory = $variables['icon_directory'];
764

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

    
770
/**
771
 * Creates a URL to the icon for a file object.
772
 *
773
 * @param $file
774
 *   A file object.
775
 * @param $icon_directory
776
 *   (optional) A path to a directory of icons to be used for files. Defaults to
777
 *   the value of the "file_icon_directory" variable.
778
 *
779
 * @return
780
 *   A URL string to the icon, or FALSE if an appropriate icon cannot be found.
781
 */
782
function file_icon_url($file, $icon_directory = NULL) {
783
  if ($icon_path = file_icon_path($file, $icon_directory)) {
784
    return base_path() . $icon_path;
785
  }
786
  return FALSE;
787
}
788

    
789
/**
790
 * Creates a path to the icon for a file object.
791
 *
792
 * @param $file
793
 *   A file object.
794
 * @param $icon_directory
795
 *   (optional) A path to a directory of icons to be used for files. Defaults to
796
 *   the value of the "file_icon_directory" variable.
797
 *
798
 * @return
799
 *   A string to the icon as a local path, or FALSE if an appropriate icon could
800
 *   not be found.
801
 */
802
function file_icon_path($file, $icon_directory = NULL) {
803
  // Use the default set of icons if none specified.
804
  if (!isset($icon_directory)) {
805
    $icon_directory = variable_get('file_icon_directory', drupal_get_path('module', 'file') . '/icons');
806
  }
807

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

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

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

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

    
838
  // No icon can be found.
839
  return FALSE;
840
}
841

    
842
/**
843
 * Determines the generic icon MIME package based on a file's MIME type.
844
 *
845
 * @param $file
846
 *   A file object.
847
 *
848
 * @return
849
 *   The generic icon MIME package expected for this file.
850
 */
851
function file_icon_map($file) {
852
  switch ($file->filemime) {
853
    // Word document types.
854
    case 'application/msword':
855
    case 'application/vnd.ms-word.document.macroEnabled.12':
856
    case 'application/vnd.oasis.opendocument.text':
857
    case 'application/vnd.oasis.opendocument.text-template':
858
    case 'application/vnd.oasis.opendocument.text-master':
859
    case 'application/vnd.oasis.opendocument.text-web':
860
    case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
861
    case 'application/vnd.stardivision.writer':
862
    case 'application/vnd.sun.xml.writer':
863
    case 'application/vnd.sun.xml.writer.template':
864
    case 'application/vnd.sun.xml.writer.global':
865
    case 'application/vnd.wordperfect':
866
    case 'application/x-abiword':
867
    case 'application/x-applix-word':
868
    case 'application/x-kword':
869
    case 'application/x-kword-crypt':
870
      return 'x-office-document';
871

    
872
    // Spreadsheet document types.
873
    case 'application/vnd.ms-excel':
874
    case 'application/vnd.ms-excel.sheet.macroEnabled.12':
875
    case 'application/vnd.oasis.opendocument.spreadsheet':
876
    case 'application/vnd.oasis.opendocument.spreadsheet-template':
877
    case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
878
    case 'application/vnd.stardivision.calc':
879
    case 'application/vnd.sun.xml.calc':
880
    case 'application/vnd.sun.xml.calc.template':
881
    case 'application/vnd.lotus-1-2-3':
882
    case 'application/x-applix-spreadsheet':
883
    case 'application/x-gnumeric':
884
    case 'application/x-kspread':
885
    case 'application/x-kspread-crypt':
886
      return 'x-office-spreadsheet';
887

    
888
    // Presentation document types.
889
    case 'application/vnd.ms-powerpoint':
890
    case 'application/vnd.ms-powerpoint.presentation.macroEnabled.12':
891
    case 'application/vnd.oasis.opendocument.presentation':
892
    case 'application/vnd.oasis.opendocument.presentation-template':
893
    case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
894
    case 'application/vnd.stardivision.impress':
895
    case 'application/vnd.sun.xml.impress':
896
    case 'application/vnd.sun.xml.impress.template':
897
    case 'application/x-kpresenter':
898
      return 'x-office-presentation';
899

    
900
    // Compressed archive types.
901
    case 'application/zip':
902
    case 'application/x-zip':
903
    case 'application/stuffit':
904
    case 'application/x-stuffit':
905
    case 'application/x-7z-compressed':
906
    case 'application/x-ace':
907
    case 'application/x-arj':
908
    case 'application/x-bzip':
909
    case 'application/x-bzip-compressed-tar':
910
    case 'application/x-compress':
911
    case 'application/x-compressed-tar':
912
    case 'application/x-cpio-compressed':
913
    case 'application/x-deb':
914
    case 'application/x-gzip':
915
    case 'application/x-java-archive':
916
    case 'application/x-lha':
917
    case 'application/x-lhz':
918
    case 'application/x-lzop':
919
    case 'application/x-rar':
920
    case 'application/x-rpm':
921
    case 'application/x-tzo':
922
    case 'application/x-tar':
923
    case 'application/x-tarz':
924
    case 'application/x-tgz':
925
      return 'package-x-generic';
926

    
927
    // Script file types.
928
    case 'application/ecmascript':
929
    case 'application/javascript':
930
    case 'application/mathematica':
931
    case 'application/vnd.mozilla.xul+xml':
932
    case 'application/x-asp':
933
    case 'application/x-awk':
934
    case 'application/x-cgi':
935
    case 'application/x-csh':
936
    case 'application/x-m4':
937
    case 'application/x-perl':
938
    case 'application/x-php':
939
    case 'application/x-ruby':
940
    case 'application/x-shellscript':
941
    case 'text/vnd.wap.wmlscript':
942
    case 'text/x-emacs-lisp':
943
    case 'text/x-haskell':
944
    case 'text/x-literate-haskell':
945
    case 'text/x-lua':
946
    case 'text/x-makefile':
947
    case 'text/x-matlab':
948
    case 'text/x-python':
949
    case 'text/x-sql':
950
    case 'text/x-tcl':
951
      return 'text-x-script';
952

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

    
957
    // Executable types.
958
    case 'application/x-macbinary':
959
    case 'application/x-ms-dos-executable':
960
    case 'application/x-pef-executable':
961
      return 'application-x-executable';
962

    
963
    default:
964
      return FALSE;
965
  }
966
}
967

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

    
974
/**
975
 * Retrieves a list of references to a file.
976
 *
977
 * @param $file
978
 *   A file object.
979
 * @param $field
980
 *   (optional) A field array to be used for this check. If given, limits the
981
 *   reference check to the given field.
982
 * @param $age
983
 *   (optional) A constant that specifies which references to count. Use
984
 *   FIELD_LOAD_REVISION to retrieve all references within all revisions or
985
 *   FIELD_LOAD_CURRENT to retrieve references only in the current revisions.
986
 * @param $field_type
987
 *   (optional) The name of a field type. If given, limits the reference check
988
 *   to fields of the given type.
989
 *
990
 * @return
991
 *   An integer value.
992
 */
993
function file_get_file_references($file, $field = NULL, $age = FIELD_LOAD_REVISION, $field_type = 'file') {
994
  $references = drupal_static(__FUNCTION__, array());
995
  $fields = isset($field) ? array($field['field_name'] => $field) : field_info_fields();
996

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

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

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