Projet

Général

Profil

Paste
Télécharger (40,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / file_entity / file_entity.pages.inc @ d1c64ea8

1
<?php
2

    
3
/**
4
 * @file
5
 * Supports file operations including View, Edit, and Delete.
6
 */
7

    
8
/**
9
 * Menu callback; view a single file entity.
10
 */
11
function file_entity_view_page($file) {
12
  drupal_set_title($file->filename);
13

    
14
  $uri = entity_uri('file', $file);
15
  // Set the file path as the canonical URL to prevent duplicate content.
16
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
17
  // Set the non-aliased path as a default shortlink.
18
  drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
19

    
20
  return file_view($file, 'full');
21
}
22

    
23
/**
24
 * Menu callback; download a single file entity.
25
 */
26
function file_entity_download_page($file) {
27
  // Ensure there is a valid token to download this file.
28
  if (!variable_get('file_entity_allow_insecure_download', FALSE)) {
29
    if (!isset($_GET['token']) || $_GET['token'] !== file_entity_get_download_token($file)) {
30
      return MENU_ACCESS_DENIED;
31
    }
32
  }
33

    
34
  // If the file does not exist it can cause problems with file_transfer().
35
  if (!is_file($file->uri)) {
36
    return MENU_NOT_FOUND;
37
  }
38
  // @todo Remove this once drupal_basename is fixed for PHP versions greater
39
  //  than '5.3.29'.
40
  $basename_function = version_compare(PHP_VERSION,'5.3.29','>') ? 'basename' : 'drupal_basename';
41
  $headers = array(
42
    'Content-Type' => mime_header_encode($file->filemime),
43
    'Content-Disposition' => 'attachment; filename="' . mime_header_encode($basename_function($file->uri)) . '"',
44
    'Content-Length' => $file->filesize,
45
    'Content-Transfer-Encoding' => 'binary',
46
    'Pragma' => 'no-cache',
47
    'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
48
    'Expires' => '0',
49
  );
50

    
51
  // Let other modules alter the download headers.
52
  drupal_alter('file_download_headers', $headers, $file);
53

    
54
  // Let other modules know the file is being downloaded.
55
  module_invoke_all('file_transfer', $file->uri, $headers);
56

    
57
  if (file_entity_file_is_local($file)) {
58
    // For local files, transfer the file and do not reveal the actual URL.
59
    file_transfer($file->uri, $headers);
60
  }
61
  else {
62
    // For remote files, just redirect the user to that file's actual URL.
63
    $headers['Location'] = file_create_url($file->uri);
64
    foreach ($headers as $name => $value) {
65
      drupal_add_http_header($name, $value);
66
    }
67
    drupal_send_headers();
68
    drupal_exit();
69
  }
70
}
71

    
72
/**
73
 * Form callback for adding a file via an upload form.
74
 *
75
 * This is a multi step form which has 1-3 pages:
76
 * - Upload file
77
 * - Choose filetype
78
 *   If there is only one candidate (based on mimetype) we will skip this step.
79
 * - Edit fields
80
 *   Skip this step if there are no fields on this entity type.
81
 */
82
function file_entity_add_upload($form, &$form_state, $options = array()) {
83
  if (!is_array($options)) {
84
    $options = array($options);
85
  }
86
  $step = (isset($form_state['step']) && in_array($form_state['step'], array(1, 2, 3, 4))) ? $form_state['step'] : 1;
87
  $form['#step'] = $step;
88
  $form['#options'] = $options + array(
89
    'types' => array(),
90
    'enabledPlugins' => array(),
91
    'schemes' => array(),
92
    'max_filesize' => '',
93
    'uri_scheme' => file_default_scheme(),
94
    'plugins' => ''
95
  );
96

    
97
  switch ($step) {
98
    case 1:
99
      return file_entity_add_upload_step_upload($form, $form_state, $options);
100

    
101
    case 2:
102
      return file_entity_add_upload_step_filetype($form, $form_state, $options);
103

    
104
    case 3:
105
      return file_entity_add_upload_step_scheme($form, $form_state, $options);
106

    
107
    case 4:
108
      return file_entity_add_upload_step_fields($form, $form_state, $options);
109

    
110
  }
111
}
112

    
113
/**
114
 * Generate form fields for the first step in the add file wizard.
115
 */
116
function file_entity_add_upload_step_upload($form, &$form_state, array $options = array()) {
117
  $form['upload'] = array(
118
    '#type' => 'managed_file',
119
    '#title' => t('Upload a new file'),
120
    '#upload_location' => file_entity_upload_destination_uri($options),
121
    '#upload_validators' => file_entity_get_upload_validators($options),
122
    '#progress_indicator' => 'bar',
123
    '#required' => TRUE,
124
    '#pre_render' => array('file_managed_file_pre_render', 'file_entity_upload_validators_pre_render'),
125
    '#default_value' => isset($form_state['storage']['upload']) ? $form_state['storage']['upload'] : NULL,
126
  );
127

    
128
  $form['actions'] = array('#type' => 'actions');
129
  $form['actions']['next'] = array(
130
    '#type' => 'submit',
131
    '#value' => t('Next'),
132
  );
133

    
134
  form_load_include($form_state, 'inc', 'file_entity', 'file_entity.pages');
135

    
136
  return $form;
137
}
138

    
139
/**
140
 * Generate form fields for the second step in the add file wizard.
141
 */
142
function file_entity_add_upload_step_filetype($form, &$form_state, array $options = array()) {
143
  $file = file_load($form_state['storage']['upload']);
144
  $selected_files = $form['#options']['types'];
145

    
146
  $form['type'] = array(
147
    '#type' => 'radios',
148
    '#title' => t('File type'),
149
    '#options' => file_entity_get_filetype_candidates($file, $selected_files),
150
    '#default_value' => isset($form_state['storage']['type']) ? $form_state['storage']['type'] : NULL,
151
    '#required' => TRUE,
152
  );
153

    
154
  $form['actions'] = array('#type' => 'actions');
155
  $form['actions']['previous'] = array(
156
    '#type' => 'submit',
157
    '#value' => t('Previous'),
158
    '#limit_validation_errors' => array(),
159
    '#submit' => array('file_entity_add_upload_submit'),
160
  );
161
  $form['actions']['next'] = array(
162
    '#type' => 'submit',
163
    '#value' => t('Next'),
164
  );
165

    
166
  return $form;
167
}
168

    
169
/**
170
 * Generate form fields for the third step in the add file wizard.
171
 */
172
function file_entity_add_upload_step_scheme($form, &$form_state, array $options = array()) {
173
  $file = file_load($form_state['storage']['upload']);
174

    
175
  $schemes = array();
176
  foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $info) {
177
    $schemes[$scheme] = check_plain($info['description']);
178
  }
179

    
180
  // Remove any schemes not found in the instance settings.
181
  if (!empty($options['schemes'])) {
182
    $schemes = array_intersect_key($schemes, array_flip($options['schemes']));
183
  }
184

    
185
  // Determine which scheme to use as the default value.
186
  if (isset($form_state['storage']['scheme'])) {
187
    $fallback_scheme = $form_state['storage']['scheme'];
188
  }
189
  elseif (!empty($options['uri_scheme'])) {
190
    $fallback_scheme = $options['uri_scheme'];
191
  }
192
  else {
193
    $fallback_scheme = file_default_scheme();
194
  }
195

    
196
  $form['scheme'] = array(
197
    '#type' => 'radios',
198
    '#title' => t('Destination'),
199
    '#options' => $schemes,
200
    '#default_value' => $fallback_scheme,
201
    '#required' => TRUE,
202
  );
203

    
204
  $form['actions'] = array('#type' => 'actions');
205
  $form['actions']['previous'] = array(
206
    '#type' => 'submit',
207
    '#value' => t('Previous'),
208
    '#limit_validation_errors' => array(),
209
    '#submit' => array('file_entity_add_upload_submit'),
210
  );
211
  $form['actions']['next'] = array(
212
    '#type' => 'submit',
213
    '#value' => t('Next'),
214
  );
215

    
216
  return $form;
217
}
218

    
219
/**
220
 * Generate form fields for the fourth step in the add file wizard.
221
 */
222
function file_entity_add_upload_step_fields($form, &$form_state, array $options = array()) {
223
  // Load the file and overwrite the filetype set on the previous screen.
224
  $file = file_load($form_state['storage']['upload']);
225
  $file->type = $form_state['storage']['type'];
226

    
227
  // Let users modify the filename here.
228
  $form['filename'] = array(
229
    '#type' => 'textfield',
230
    '#title' => t('Name'),
231
    '#default_value' => $file->filename,
232
    '#required' => TRUE,
233
    '#maxlength' => 255,
234
    '#weight' => -10,
235
  );
236

    
237
  // Add fields.
238
  field_attach_form('file', $file, $form, $form_state);
239

    
240
  $form['actions'] = array('#type' => 'actions');
241
  $form['actions']['previous'] = array(
242
    '#type' => 'submit',
243
    '#value' => t('Previous'),
244
    '#limit_validation_errors' => array(),
245
    '#submit' => array('file_entity_add_upload_submit'),
246
  );
247
  $form['actions']['submit'] = array(
248
    '#type' => 'submit',
249
    '#value' => t('Save'),
250
  );
251

    
252
  return $form;
253
}
254

    
255
/**
256
 * Page callback to show file usage information.
257
 */
258
function file_entity_usage_page($file) {
259
  $rows = array();
260
  $occured_entities = array();
261

    
262
  // Determine all of the locations where a file is used, then loop through the
263
  // occurrences and filter out any duplicates.
264
  foreach (file_usage_list($file) as $module => $type) {
265
    foreach ($type as $entity_type => $entity_ids) {
266
      // There are cases where the actual entity doesn't exist.
267
      // We have to handle this.
268
      $entity_info = entity_get_info($entity_type);
269
      $entities = empty($entity_info) ? NULL : entity_load($entity_type, array_keys($entity_ids));
270

    
271
      foreach ($entity_ids as $entity_id => $count) {
272
        // If this entity has already been listed in the table, just add any
273
        // additional usage to the total count column in the table row and
274
        // continue on to the next iteration of the loop.
275
        if (isset($occured_entities[$entity_type][$entity_id])) {
276
          $rows[$occured_entities[$entity_type][$entity_id]][2] += $count;
277
          continue;
278
        }
279

    
280
        // Retrieve the label and the URI of the entity.
281
        $label = empty($entities[$entity_id]) ? $module : entity_label($entity_type, $entities[$entity_id]);
282
        $entity_uri = empty($entities[$entity_id]) ? NULL : entity_uri($entity_type, $entities[$entity_id]);
283

    
284
        // Link the label to the URI when possible.
285
        if (!empty($entity_uri['path'])) {
286
          $entity_label = l($label, $entity_uri['path']);
287
        }
288
        else {
289
          $entity_label = check_plain($label);
290
        }
291

    
292
        $rows[] = array($entity_label, $entity_type, $count);
293

    
294
        // Record the occurrence of the entity to ensure that it isn't listed in
295
        // the table again.
296
        $occured_entities[$entity_type][$entity_id] = count($rows) - 1;
297
      }
298
    }
299
  }
300

    
301
  $header = array(t('Entity'), t('Entity type'), t('Use count'));
302
  $build['usage_table'] = array(
303
    '#theme' => 'table',
304
    '#header' => $header,
305
    '#rows' => $rows,
306
    '#caption' => t('This table lists all of the places where @filename is used.', array('@filename' => $file->filename)),
307
    '#empty' => t('This file is not currently used.'),
308
  );
309

    
310
  return $build;
311
}
312

    
313
/**
314
 * Get the candidate filetypes for a given file.
315
 *
316
 * Only filetypes for which the user has access to create entities are returned.
317
 *
318
 * @param array $file
319
 *   An upload file array from form_state.
320
 *
321
 * @return array
322
 *   An array of file type bundles that support the file's mime type.
323
 */
324
function file_entity_get_filetype_candidates($file, $selected_files = array()) {
325
  $types = module_invoke_all('file_type', $file);
326
  drupal_alter('file_type', $types, $file);
327

    
328
  // If no file types are selected in field instance settings, allow all
329
  // available types.
330
  if (!empty($selected_files)) {
331
    // Limit file type candidates to field allowed types.
332
    $types = array_intersect($types, $selected_files);
333
  }
334

    
335
  $candidates = array();
336
  foreach ($types as $type) {
337
    $file->type = $type;
338
    if (file_entity_access('create', $file)) {
339
      $candidates[$type] = file_entity_type_get_name($file);
340
    }
341
  }
342
  return $candidates;
343
}
344

    
345
/**
346
 * Submit handler for the add file form.
347
 */
348
function file_entity_add_upload_submit($form, &$form_state) {
349
  $form_state['storage'] = isset($form_state['storage']) ? $form_state['storage'] : array();
350
  $form_state['storage'] = array_merge($form_state['storage'], $form_state['values']);
351

    
352
  // Field selected allowed types.
353
  $selected_files = $form['#options']['types'];
354

    
355
  // This var is set to TRUE when we are ready to save the file.
356
  $save = FALSE;
357
  $trigger = $form_state['triggering_element']['#id'];
358

    
359
  $steps_to_check = array(2, 3);
360
  if ($trigger == 'edit-previous') {
361
    // If the previous button was hit,
362
    // the step checking order should be reversed 3, 2.
363
    $steps_to_check = array_reverse($steps_to_check);
364
  }
365

    
366
  foreach ($steps_to_check as $step) {
367
    // Check if we can skip step 2 and 3.
368
    if (($form['#step'] == $step - 1 && $trigger == 'edit-next') || ($form['#step'] == $step + 1 && $trigger == 'edit-previous')) {
369
      $file = file_load($form_state['storage']['upload']);
370
      if ($step == 2) {
371
        // Check if we can skip step 2.
372
        $candidates = file_entity_get_filetype_candidates($file, $selected_files);
373
        if (count($candidates) == 1) {
374
          $candidates_keys = array_keys($candidates);
375
          // There is only one possible filetype for this file.
376
          // Skip the second page.
377
          $form['#step'] += ($trigger == 'edit-previous') ? -1 : 1;
378
          $form_state['storage']['type'] = reset($candidates_keys);
379
        }
380
        elseif (!$candidates || variable_get('file_entity_file_upload_wizard_skip_file_type', FALSE)) {
381
          // Do not assign the file a file type.
382
          $form['#step'] += ($trigger == 'edit-previous') ? -1 : 1;
383
          $form_state['storage']['type'] = FILE_TYPE_NONE;
384
        }
385
      }
386
      else {
387
        // Check if we can skip step 3.
388
        $options = $form['#options'];
389
        $schemes = file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE);
390

    
391
        // Remove any schemes not found in the instance settings.
392
        if (!empty($options['schemes'])) {
393
          $schemes = array_intersect_key($schemes, $options['schemes']);
394
        }
395

    
396
        if (!file_entity_file_is_writeable($file)) {
397
          // The file is read-only (remote) and must use its provided scheme.
398
          $form['#step'] += ($trigger == 'edit-previous') ? -1 : 1;
399
          $form_state['storage']['scheme'] = file_uri_scheme($file->uri);
400
        }
401
        elseif (count($schemes) == 1) {
402
          // There is only one possible stream wrapper for this file.
403
          // Skip the third page.
404
          $form['#step'] += ($trigger == 'edit-previous') ? -1 : 1;
405
          $form_state['storage']['scheme'] = key($schemes);
406
        }
407
        elseif (variable_get('file_entity_file_upload_wizard_skip_scheme', FALSE)) {
408
          $form['#step'] += ($trigger == 'edit-previous') ? -1 : 1;
409

    
410
          // Fallback to the URI scheme specified in the field settings
411
          // otherwise use the default file scheme.
412
          if (!empty($options['uri_scheme'])) {
413
            $form_state['storage']['scheme'] = $options['uri_scheme'];
414
          }
415
          else {
416
            $form_state['storage']['scheme'] = file_default_scheme();
417
          }
418
        }
419
      }
420
    }
421
  }
422

    
423
  // We have the filetype, check if we can skip step 4.
424
  if (($form['#step'] == 3 && $trigger == 'edit-next')) {
425
    $file = file_load($form_state['storage']['upload']);
426
    $form_state['file'] = $file;
427
    if (!field_info_instances('file', $form_state['storage']['type'])) {
428
      // This filetype doesn't have fields, save the file.
429
      $save = TRUE;
430
    }
431
    elseif (variable_get('file_entity_file_upload_wizard_skip_fields', FALSE)) {
432
      // Save the file with blanks fields.
433
      $save = TRUE;
434
    }
435
  }
436

    
437
  // Form id's can vary depending on how many other forms are displayed, so we
438
  // need to do string comparissons. e.g edit-submit--2.
439
  if (strpos($trigger, 'edit-next') !== FALSE) {
440
    $form_state['step'] = $form['#step'] + 1;
441
  }
442
  elseif (strpos($trigger, 'edit-previous') !== FALSE) {
443
    $form_state['step'] = $form['#step'] - 1;
444
  }
445
  elseif (strpos($trigger, 'edit-submit') !== FALSE) {
446
    $save = TRUE;
447
  }
448

    
449
  if ($save) {
450
    $file = file_load($form_state['storage']['upload']);
451
    if ($file) {
452
      if (file_uri_scheme($file->uri) != $form_state['storage']['scheme']) {
453
        $file_destination = $form_state['storage']['scheme'] . '://' . file_uri_target($file->uri);
454
        $file_destination = file_stream_wrapper_uri_normalize($file_destination);
455
        if ($moved_file = file_move($file, $file_destination, FILE_EXISTS_RENAME)) {
456
          // Only re-assign the file object if file_move() did not fail.
457
          $file = $moved_file;
458
        }
459
      }
460
      $file->type = $form_state['storage']['type'];
461
      $file->display = TRUE;
462

    
463
      // Change the file from temporary to permanent.
464
      $file->status = FILE_STATUS_PERMANENT;
465

    
466
      // Save the form fields.
467
      // Keep in mind that the values for the Field API fields must be in
468
      // $form_state['values'] and not in ['storage']. This is true as long as
469
      // the fields are on the last page of the multi step form.
470
      entity_form_submit_build_entity('file', $file, $form, $form_state);
471

    
472
      file_save($file);
473
      $form_state['file'] = $file;
474
      drupal_set_message(t('@type %name was uploaded.', array('@type' => file_entity_type_get_name($file), '%name' => $file->filename)));
475
    }
476
    else {
477
      drupal_set_message(t('An error occurred and no file was uploaded.'), 'error');
478
      return;
479
    }
480

    
481
    // Figure out destination.
482
    if (user_access('administer files')) {
483
      $path = 'admin/content/file';
484
    }
485
    else {
486
      $path = 'file/' . $file->fid;
487
    }
488
    $form_state['redirect'] = $path;
489
  }
490
  else {
491
    $form_state['rebuild'] = TRUE;
492
  }
493

    
494
  // Clear the page and block caches.
495
  cache_clear_all();
496
}
497

    
498
/**
499
 * Determines the upload location for the file add upload form.
500
 *
501
 * @param array $params
502
 *   An array of parameters from the media browser.
503
 * @param array $data
504
 *   (optional) An array of token objects to pass to token_replace().
505
 *
506
 * @return string
507
 *   A file directory URI with tokens replaced.
508
 *
509
 * @see token_replace()
510
 */
511
function file_entity_upload_destination_uri(array $params, array $data = array()) {
512
  $params += array(
513
    'uri_scheme' => file_default_scheme(),
514
    'file_directory' => variable_get('file_entity_default_file_directory', ''),
515
  );
516

    
517
  $destination = trim($params['file_directory'], '/');
518

    
519
  // Replace tokens.
520
  $destination = token_replace($destination, $data);
521

    
522
  return $params['uri_scheme'] . '://' . $destination;
523
}
524

    
525
/**
526
 * Form for uploading multiple files.
527
 */
528
function file_entity_add_upload_multiple($form, &$form_state, $params = array()) {
529
  $form = file_entity_add_upload($form, $form_state, $params);
530
  unset($form['upload']['#title']);
531
  // The validators will be set from plupload anyway. This isn't pretty,
532
  // but don't allow it to show up twice.
533
  unset($form['upload']['#description']);
534

    
535
  $form['upload']['#type'] = 'plupload';
536

    
537
  // Ensure that we call the plupload_element_pre_render function.
538
  // If it isn't called, it doesn't set the JS settings that transfers the
539
  // list of allowed file extensions to the PLUpload widget.
540
  // We override the 'file_entity_upload_validators_pre_render' setting if it
541
  // exists, because both pre-render hooks adds the upload-help with list of
542
  // allowed file extensions.
543
  $index = array_search('file_entity_upload_validators_pre_render', $form['upload']['#pre_render']);
544
  if ($index !== FALSE) {
545
    $form['upload']['#pre_render'][$index] = 'plupload_element_pre_render';
546
  }
547
  else {
548
    $form['upload']['#pre_render'][] = 'plupload_element_pre_render';
549
  }
550

    
551
  $form['submit']['#value'] = t('Start upload');
552
  return $form;
553
}
554

    
555
/**
556
 * Submit handler for the multiple upload form.
557
 */
558
function file_entity_add_upload_multiple_submit($form, &$form_state) {
559
  $upload_location = !empty($form['upload']['#upload_location']) ?
560
    $form['upload']['#upload_location'] . '/' :
561
    variable_get('file_default_scheme', 'public') . '://';
562

    
563
  // Ensure writable destination directory for the files.
564
  file_prepare_directory($upload_location, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
565

    
566
  // We can't use file_save_upload() because of
567
  // http://www.jacobsingh.name/content/tight-coupling-no-not.
568
  foreach ($form_state['values']['upload'] as $uploaded_file) {
569
    if ($uploaded_file['status'] == 'done') {
570
      $source = $uploaded_file['tmppath'];
571
      $destination = file_stream_wrapper_uri_normalize($upload_location . $uploaded_file['name']);
572
      // Rename it to its original name, and put it in its final home.
573
      // Note - not using file_move here because if we call file_get_mime
574
      // (in file_uri_to_object) while it has a .tmp extension, it horks.
575
      $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
576

    
577
      $file = file_uri_to_object($destination);
578
      $file->status = FILE_STATUS_PERMANENT;
579
      file_save($file);
580

    
581
      $form_state['files'][$file->fid] = $file;
582
    }
583
    else {
584
      // @todo: move this to element validate or something.
585
      form_set_error('pud', t('The specified file %name could not be uploaded.', array('%name' => $uploaded_file['name'])));
586
    }
587
  }
588

    
589
  // Redirect to the file edit page.
590
  if (file_entity_access('update', $file) && module_exists('media_bulk_upload')) {
591
    $destination = array();
592
    if (isset($_GET['destination'])) {
593
      $destination = drupal_get_destination();
594
      unset($_GET['destination']);
595
    }
596
    elseif (user_access('administer files')) {
597
      $destination = array('destination' => 'admin/content/file');
598
    }
599
    $form_state['redirect'] = array('admin/content/file/edit-multiple/' . implode(' ', array_keys($form_state['files'])), array('query' => $destination));
600
  }
601
  else {
602
    $form_state['redirect'] = user_access('administer files') ? 'admin/content/file' : '<front>';
603
  }
604

    
605
  // Clear the page and block caches.
606
  cache_clear_all();
607
}
608

    
609
/**
610
 * Page callback: Form constructor for the file edit form.
611
 *
612
 * Path: file/%file/edit
613
 *
614
 * @param object $file
615
 *   A file object from file_load().
616
 *
617
 * @see file_entity_menu()
618
 *
619
 * @todo Rename this form to file_edit_form to ease into core.
620
 */
621
function file_entity_edit($form, &$form_state, $file) {
622
  drupal_set_title(t('<em>Edit @type</em> @title', array('@type' => $file->type, '@title' => $file->filename)), PASS_THROUGH);
623

    
624
  $form_state['file'] = $file;
625

    
626
  $form['#attributes']['class'][] = 'file-form';
627
  if (!empty($file->type)) {
628
    $form['#attributes']['class'][] = 'file-' . $file->type . '-form';
629
  }
630

    
631
  // Basic file information.
632
  // These elements are just values so they are not even sent to the client.
633
  foreach (array('fid', 'type', 'uid', 'timestamp') as $key) {
634
    $form[$key] = array(
635
      '#type' => 'value',
636
      '#value' => isset($file->$key) ? $file->$key : NULL,
637
    );
638
  }
639

    
640
  $form['filename'] = array(
641
    '#type' => 'textfield',
642
    '#title' => t('Name'),
643
    '#default_value' => $file->filename,
644
    '#required' => TRUE,
645
    '#maxlength' => 255,
646
    '#weight' => -10,
647
  );
648

    
649
  // Add a 'replace this file' upload field if the file is writeable.
650
  if (file_entity_file_is_writeable($file)) {
651
    // Set up replacement file validation.
652
    $replacement_options = array();
653

    
654
    // The replacement file must have an extension valid for the original type.
655
    $file_extensions = array();
656
    $file_type_name = isset($file->type) ? $file->type : file_get_type($file);
657
    if ($file_type_name && ($file_type = file_type_load($file_type_name))) {
658
      $file_extensions = file_type_get_valid_extensions($file_type);
659
    }
660

    
661
    // Set allowed file extensions.
662
    if (!empty($file_extensions)) {
663
      // Set to type based file extensions.
664
      $replacement_options['file_extensions'] = implode(' ', $file_extensions);
665
    }
666
    else {
667
      // Fallback to the extension of the current file.
668
      $replacement_options['file_extensions'] = pathinfo($file->uri, PATHINFO_EXTENSION);
669
    }
670

    
671
    $form['replace_upload'] = array(
672
      '#type' => 'file',
673
      '#title' => t('Replace file'),
674
      '#description' => t('This file will replace the existing file. This action cannot be undone.'),
675
      '#upload_validators' => file_entity_get_upload_validators($replacement_options),
676
      '#pre_render' => array('file_entity_upload_validators_pre_render'),
677
    );
678
  }
679

    
680
  $form['preview'] = file_view_file($file, 'preview');
681

    
682
  $form['additional_settings'] = array(
683
    '#type' => 'vertical_tabs',
684
    '#weight' => 99,
685
  );
686

    
687
  // File destination information for administrators.
688
  $form['destination'] = array(
689
    '#type' => 'fieldset',
690
    '#access' => user_access('administer files') && file_entity_file_is_writeable($file),
691
    '#title' => t('Destination'),
692
    '#collapsible' => TRUE,
693
    '#collapsed' => TRUE,
694
    '#group' => 'additional_settings',
695
    '#attributes' => array(
696
      'class' => array('file-form-destination'),
697
    ),
698
    '#attached' => array(
699
      'js' => array(
700
        drupal_get_path('module', 'file_entity') . '/file_entity.js',
701
      ),
702
    ),
703
  );
704

    
705
  $options = array();
706
  foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $info) {
707
    $options[$scheme] = check_plain($info['name']);
708
  }
709

    
710
  $form['destination']['scheme'] = array(
711
    '#type' => 'radios',
712
    '#title' => t('Destination'),
713
    '#options' => $options,
714
    '#default_value' => file_uri_scheme($file->uri),
715
  );
716

    
717
  // File user information for administrators.
718
  $form['user'] = array(
719
    '#type' => 'fieldset',
720
    '#access' => user_access('administer files'),
721
    '#title' => t('User information'),
722
    '#collapsible' => TRUE,
723
    '#collapsed' => TRUE,
724
    '#group' => 'additional_settings',
725
    '#attributes' => array(
726
      'class' => array('file-form-user'),
727
    ),
728
    '#attached' => array(
729
      'js' => array(
730
        drupal_get_path('module', 'file_entity') . '/file_entity.js',
731
        array(
732
          'type' => 'setting',
733
          'data' => array('anonymous' => variable_get('anonymous', t('Anonymous'))),
734
        ),
735
      ),
736
    ),
737
    '#weight' => 90,
738
  );
739
  $form['user']['name'] = array(
740
    '#type' => 'textfield',
741
    '#title' => t('Associated with'),
742
    '#maxlength' => 60,
743
    '#autocomplete_path' => 'user/autocomplete',
744
    '#default_value' => !empty($file->uid) ? user_load($file->uid)->name : '',
745
    '#weight' => -1,
746
    '#description' => t('Leave blank for %anonymous.', array('%anonymous' => variable_get('anonymous', t('Anonymous')))),
747
  );
748

    
749
  // Add the buttons.
750
  $form['actions'] = array('#type' => 'actions');
751
  $form['actions']['submit'] = array(
752
    '#type' => 'submit',
753
    '#value' => t('Save'),
754
    '#weight' => 5,
755
    '#submit' => array('file_entity_edit_submit'),
756
    '#validate' => array('file_entity_edit_validate'),
757
  );
758
  $form['actions']['delete'] = array(
759
    '#type' => 'submit',
760
    '#value' => t('Delete'),
761
    '#weight' => 10,
762
    '#submit' => array('file_entity_edit_delete_submit'),
763
    '#access' => file_entity_access('delete', $file),
764
  );
765

    
766
  // Build the URL for the cancel button taking into account that there might be
767
  // a "destination" that includes query string variables.
768
  $parameters = drupal_get_query_parameters();
769
  $destination = isset($parameters['destination']) ? $parameters['destination'] : 'file/' . $file->fid;
770
  $url = drupal_parse_url($destination);
771

    
772
  $form['actions']['cancel'] = array(
773
    '#type' => 'link',
774
    '#title' => t('Cancel'),
775
    '#href' => $url['path'],
776
    '#options' => array('query' => $url['query']),
777
    '#weight' => 15,
778
  );
779

    
780
  $langcode = function_exists('entity_language') ? entity_language('file', $file) : NULL;
781
  field_attach_form('file', $file, $form, $form_state, $langcode);
782

    
783
  return $form;
784
}
785

    
786
/**
787
 * Form validation handler for file_entity_edit().
788
 */
789
function file_entity_edit_validate($form, &$form_state) {
790
  $file = (object) $form_state['values'];
791

    
792
  // Validate the "associated user" field.
793
  if (!empty($file->name) && !($account = user_load_by_name($file->name))) {
794
    // The use of empty() is mandatory in the context of usernames
795
    // as the empty string denotes the anonymous user. In case we
796
    // are dealing with an anonymous user we set the user ID to 0.
797
    form_set_error('name', t('The username %name does not exist.', array('%name' => $file->name)));
798
  }
799

    
800
  // Handle the replacement file if uploaded.
801
  if (isset($form_state['values']['replace_upload'])) {
802
    // Save the file as a temporary file.
803
    $file = file_save_upload('replace_upload', $form['replace_upload']['#upload_validators']);
804
    if (!empty($file)) {
805
      // Put the temporary file in form_values so we can save it on submit.
806
      $form_state['values']['replace_upload'] = $file;
807
    }
808
    elseif ($file === FALSE) {
809
      // File uploaded failed.
810
      form_set_error('replace_upload', t('The replacement file could not be uploaded.'));
811
    }
812
  }
813

    
814
  // Run entity form validation.
815
  entity_form_field_validate('file', $form, $form_state);
816
}
817

    
818
/**
819
 * Form submission handler for the 'Save' button for file_entity_edit().
820
 */
821
function file_entity_edit_submit($form, &$form_state) {
822
  $file = $form_state['file'];
823
  $orphaned_uri = '';
824

    
825
  // Check if a replacement file has been uploaded.
826
  if (!empty($form_state['values']['replace_upload'])) {
827
    $replacement = $form_state['values']['replace_upload'];
828
    // Move file from temp to permanent home.
829
    if (pathinfo($replacement->uri, PATHINFO_EXTENSION) == pathinfo($file->uri, PATHINFO_EXTENSION)) {
830
      if ($new_file_uri = file_unmanaged_copy($replacement->uri, $file->uri, FILE_EXISTS_REPLACE)) {
831
        // Remove temporary file.
832
        file_delete($replacement);
833
      }
834
    } else {
835
      $destination_uri = rtrim($file->uri, drupal_basename($file->uri)) . drupal_basename($replacement->uri);
836
      $replace_mode = $destination_uri == $file->uri ? FILE_EXISTS_REPLACE : FILE_EXISTS_RENAME;
837
      if ($new_file_uri = file_unmanaged_copy($replacement->uri, $destination_uri, $replace_mode)) {
838
        // @todo Add watchdog() about replaced file here?
839

    
840
        // Remove temporary file.
841
        file_delete($replacement);
842

    
843
        // Update if the uri target has changed.
844
        if ($new_file_uri != $file->uri) {
845
          // Store the original file uri to delete if save is successful.
846
          $orphaned_uri = $file->uri;
847

    
848
          // Update file entity uri.
849
          $file->uri = $new_file_uri;
850
        }
851
      }
852
    }
853
  }
854

    
855
  // Run entity form submit handling and save the file.
856
  entity_form_submit_build_entity('file', $file, $form, $form_state);
857

    
858
  // A user might assign the associated user by entering a user name in the file
859
  // edit form, which we then need to translate to a user ID.
860
  if (isset($file->name)) {
861
    // The use of isset() is mandatory in the context of user IDs, because
862
    // user ID 0 denotes the anonymous user.
863
    if ($user = user_load_by_name($file->name)) {
864
      $file->uid = $user->uid;
865
    }
866
    else {
867
      // Anonymous user.
868
      $file->uid = 0;
869
    }
870
  }
871
  elseif ($file->uid) {
872
    $user = user_load($file->uid);
873
    $file->name = $user->name;
874
  }
875

    
876
  if (file_uri_scheme($file->uri) != $form_state['values']['scheme']) {
877
    $file_destination = $form_state['values']['scheme'] . '://' . file_uri_target($file->uri);
878
    $file_destination = file_stream_wrapper_uri_normalize($file_destination);
879
    $file_destination_dirname = drupal_dirname($file_destination);
880
    // Create the directory in case it doesn't exist.
881
    file_prepare_directory($file_destination_dirname, FILE_CREATE_DIRECTORY);
882
    if ($moved_file = file_move($file, $file_destination, FILE_EXISTS_RENAME)) {
883
      // Only re-assign the file object if file_move() did not fail.
884
      $file = $moved_file;
885
    }
886
  }
887

    
888
  file_save($file);
889

    
890
  $args = array(
891
    '@type' => file_entity_type_get_name($file),
892
    '%title' => entity_label('file', $file),
893
  );
894
  watchdog('file', '@type: updated %title.', $args);
895
  drupal_set_message(t('@type %title has been updated.', $args));
896

    
897
  // Clean up orphaned file.
898
  if (!empty($orphaned_uri)) {
899
    file_unmanaged_delete($orphaned_uri);
900

    
901
    $args['@orphaned'] = file_uri_target($orphaned_uri);
902
    watchdog('file', '@type: deleted orphaned file @orphaned for %title.', $args);
903
    drupal_set_message(t('The replaced @type @orphaned has been deleted.', $args));
904
  }
905

    
906
  $form_state['redirect'] = 'file/' . $file->fid;
907

    
908
  // Clear the page and block caches.
909
  cache_clear_all();
910
}
911

    
912
/**
913
 * Form submission handler for the 'Delete' button for file_entity_edit().
914
 */
915
function file_entity_edit_delete_submit($form, &$form_state) {
916
  $fid = $form_state['values']['fid'];
917
  $destination = array();
918
  if (isset($_GET['destination'])) {
919
    $destination = drupal_get_destination();
920
    unset($_GET['destination']);
921
  }
922
  $form_state['redirect'] = array('file/' . $fid . '/delete', array('query' => $destination));
923

    
924
  // Clear the page and block caches.
925
  cache_clear_all();
926
}
927

    
928
/**
929
 * Page callback: Form constructor for the file deletion confirmation form.
930
 *
931
 * Path: file/%file/delete
932
 *
933
 * @param object $file
934
 *   A file object from file_load().
935
 *
936
 * @see file_entity_menu()
937
 */
938
function file_entity_delete_form($form, &$form_state, $file) {
939
  $form_state['file'] = $file;
940

    
941
  $form['fid'] = array(
942
    '#type' => 'value',
943
    '#value' => $file->fid,
944
  );
945

    
946
  $description = t('This action cannot be undone.');
947
  if ($references = file_usage_list($file)) {
948
    $description .= ' ' . t('This file is currently in use and may cause problems if deleted.');
949
  }
950

    
951
  return confirm_form($form,
952
    t('Are you sure you want to delete the file %title?', array(
953
      '%title' => entity_label('file', $file),
954
    )),
955
    'file/' . $file->fid,
956
    $description,
957
    t('Delete')
958
  );
959
}
960

    
961
/**
962
 * Form submission handler for file_entity_delete_form().
963
 */
964
function file_entity_delete_form_submit($form, &$form_state) {
965
  if ($form_state['values']['confirm'] && $file = file_load($form_state['values']['fid'])) {
966
    // Use file_delete_multiple() rather than file_delete() since we want to
967
    // avoid unwanted validation and usage checking.
968
    file_delete_multiple(array($file->fid));
969

    
970
    $args = array(
971
      '@type' => file_entity_type_get_name($file),
972
      '%title' => entity_label('file', $file),
973
    );
974
    watchdog('file', '@type: deleted %title.', $args);
975
    drupal_set_message(t('@type %title has been deleted.', $args));
976
  }
977

    
978
  $form_state['redirect'] = '<front>';
979

    
980
  // Clear the page and block caches.
981
  cache_clear_all();
982
}
983

    
984
/**
985
 * Form constructor for file deletion confirmation form.
986
 *
987
 * @param array $files
988
 *   An array of file objects.
989
 */
990
function file_entity_multiple_delete_form($form, &$form_state, array $files) {
991
  $form['files'] = array(
992
    '#prefix' => '<ul>',
993
    '#suffix' => '</ul>',
994
    '#tree' => TRUE,
995
  );
996

    
997
  $files_have_usage = FALSE;
998
  foreach ($files as $fid => $file) {
999
    $title = entity_label('file', $file);
1000
    $usage = file_usage_list($file);
1001
    if (!empty($usage)) {
1002
      $files_have_usage = TRUE;
1003
      $title = t('@title (in use)', array('@title' => $title));
1004
    }
1005
    else {
1006
      $title = check_plain($title);
1007
    }
1008
    $form['files'][$fid] = array(
1009
      '#type' => 'hidden',
1010
      '#value' => $fid,
1011
      '#prefix' => '<li>',
1012
      '#suffix' => $title . "</li>\n",
1013
    );
1014
  }
1015

    
1016
  $form['operation'] = array(
1017
    '#type' => 'hidden',
1018
    '#value' => 'delete',
1019
  );
1020

    
1021
  $description = t('This action cannot be undone.');
1022
  if ($files_have_usage) {
1023
    $description .= ' ' . t('Some of the files are currently in use and may cause problems if deleted.');
1024
  }
1025

    
1026
  return confirm_form(
1027
    $form,
1028
    format_plural(count($files), 'Are you sure you want to delete this file?', 'Are you sure you want to delete these files?'),
1029
    'admin/content/file',
1030
    $description,
1031
    t('Delete')
1032
  );
1033
}
1034

    
1035
/**
1036
 * Form submission handler for file_entity_multiple_delete_form().
1037
 */
1038
function file_entity_multiple_delete_form_submit($form, &$form_state) {
1039
  if ($form_state['values']['confirm'] && $fids = array_keys($form_state['values']['files'])) {
1040
    file_delete_multiple($fids);
1041
    $count = count($fids);
1042
    watchdog('file', 'Deleted @count files.', array('@count' => $count));
1043
    drupal_set_message(format_plural($count, 'Deleted one file.', 'Deleted @count files.'));
1044
  }
1045
  $form_state['redirect'] = 'admin/content/file';
1046

    
1047
  // Clear the page and block caches.
1048
  cache_clear_all();
1049
}
1050

    
1051
/**
1052
 * Page callback for the file edit form.
1053
 *
1054
 * @deprecated
1055
 *   Use drupal_get_form('file_entity_edit')
1056
 */
1057
function file_entity_page_edit($file) {
1058
  return drupal_get_form('file_entity_edit', $file);
1059
}
1060

    
1061
/**
1062
 * Page callback for the file deletion confirmation form.
1063
 *
1064
 * @deprecated
1065
 *   Use drupal_get_form('file_entity_delete_form')
1066
 */
1067
function file_entity_page_delete($file) {
1068
  return drupal_get_form('file_entity_delete_form');
1069
}
1070

    
1071
/**
1072
 * Retrieves the upload validators for a file.
1073
 *
1074
 * @param array $options
1075
 *   (optional) An array of options for file validation.
1076
 *
1077
 * @return array
1078
 *   An array suitable for passing to file_save_upload() or for a managed_file
1079
 *   or upload element's '#upload_validators' property.
1080
 */
1081
function file_entity_get_upload_validators(array $options = array()) {
1082
  // Set up file upload validators.
1083
  $validators = array();
1084

    
1085
  // Validate file extensions. If there are no file extensions in $params and
1086
  // there are no Media defaults, there is no file extension validation.
1087
  if (!empty($options['file_extensions'])) {
1088
    $validators['file_validate_extensions'] = array($options['file_extensions']);
1089
  }
1090
  else {
1091
    $validators['file_validate_extensions'] = array(variable_get('file_entity_default_allowed_extensions', 'jpg jpeg gif png txt doc docx xls xlsx pdf ppt pptx pps ppsx odt ods odp mp3 mov mp4 m4a m4v mpeg avi ogg oga ogv weba webp webm'));
1092
  }
1093

    
1094
  // Cap the upload size according to the system or user defined limit.
1095
  $max_filesize = parse_size(file_upload_max_size());
1096
  $file_entity_max_filesize = parse_size(variable_get('file_entity_max_filesize', ''));
1097

    
1098
  // If the user defined a size limit, use the smaller of the two.
1099
  if (!empty($file_entity_max_filesize)) {
1100
    $max_filesize = min($max_filesize, $file_entity_max_filesize);
1101
  }
1102

    
1103
  if (!empty($options['max_filesize']) && $options['max_filesize'] < $max_filesize) {
1104
    $max_filesize = parse_size($options['max_filesize']);
1105
  }
1106

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

    
1110
  // Add image validators.
1111
  $options += array('min_resolution' => 0, 'max_resolution' => 0);
1112
  if ($options['min_resolution'] || $options['max_resolution']) {
1113
    $validators['file_validate_image_resolution'] = array($options['max_resolution'], $options['min_resolution']);
1114
  }
1115

    
1116
  // Add other custom upload validators from options.
1117
  if (!empty($options['upload_validators'])) {
1118
    $validators += $options['upload_validators'];
1119
  }
1120

    
1121
  return $validators;
1122
}
1123

    
1124
function file_entity_upload_archive_form($form, &$form_state) {
1125
  $options = array(
1126
    'file_extensions' => archiver_get_extensions(),
1127
  );
1128

    
1129
  $form['upload'] = array(
1130
    '#type' => 'managed_file',
1131
    '#title' => t('Upload an archive file'),
1132
    '#upload_location' => NULL, // Upload to the temporary directory.
1133
    '#upload_validators' => file_entity_get_upload_validators($options),
1134
    '#progress_indicator' => 'bar',
1135
    '#required' => TRUE,
1136
    '#pre_render' => array('file_managed_file_pre_render', 'file_entity_upload_validators_pre_render'),
1137
  );
1138

    
1139
  $form['pattern'] = array(
1140
    '#type' => 'textfield',
1141
    '#title' => t('Pattern'),
1142
    '#description' => t('Only files matching this pattern will be imported. For example, to import all jpg and gif files, the pattern would be <em>*.jpg|*.gif</em>. Use <em>.*</em> to extract all files in the archive.'),
1143
    '#default_value' => '.*',
1144
    '#required' => TRUE,
1145
  );
1146

    
1147
  $form['actions'] = array('#type' => 'actions');
1148
  $form['actions']['submit'] = array(
1149
    '#type' => 'submit',
1150
    '#value' => t('Submit'),
1151
  );
1152

    
1153
  form_load_include($form_state, 'inc', 'file_entity', 'file_entity.pages');
1154

    
1155
  return $form;
1156
}
1157

    
1158
/**
1159
 * Upload a file.
1160
 */
1161
function file_entity_upload_archive_form_submit($form, &$form_state) {
1162
  $form_state['files'] = array();
1163

    
1164
  if ($archive = file_load($form_state['values']['upload'])) {
1165
    if ($archiver = archiver_get_archiver($archive->uri)) {
1166
      $files = $archiver->listContents();
1167

    
1168
      $extract_dir = file_default_scheme() . '://' . pathinfo($archive->filename, PATHINFO_FILENAME);
1169
      $extract_dir = file_destination($extract_dir, FILE_EXISTS_RENAME);
1170
      if (!file_prepare_directory($extract_dir, FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY)) {
1171
        throw new Exception(t('Unable to prepar, e directory %dir for extraction.', array('%dir' => $extract_dir)));
1172
      }
1173

    
1174
      $archiver->extract($extract_dir);
1175
      $pattern = '/' . $form_state['values']['pattern'] . '/';
1176
      if ($files = file_scan_directory($extract_dir, $pattern)) {
1177
        foreach ($files as $file) {
1178
          $file->status = FILE_STATUS_PERMANENT;
1179
          $file->uid = $archive->uid;
1180
          file_save($file);
1181
          $form_state['files'][$file->fid] = $file;
1182
        }
1183
      }
1184
      drupal_set_message(t('Extracted %file and added @count new files.', array('%file' => $archive->filename, '@count' => count($files))));
1185
    }
1186
    else {
1187
      throw new Exception(t('Cannot extract %file, not a valid archive.', array('%file' => $archive->uri)));
1188
    }
1189
  }
1190

    
1191
  // Redirect to the file edit page.
1192
  if (file_entity_access('edit') && module_exists('multiform')) {
1193
    $destination = array('destination' => 'admin/content/file');
1194
    if (isset($_GET['destination'])) {
1195
      $destination = drupal_get_destination();
1196
      unset($_GET['destination']);
1197
    }
1198
    $form_state['redirect'] = array('admin/content/file/edit-multiple/' . implode(' ', array_keys($form_state['files'])), array('query' => $destination));
1199
  }
1200
  else {
1201
    $form_state['redirect'] = 'admin/content/file';
1202
  }
1203
}