Projet

Général

Profil

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

root / drupal7 / sites / all / modules / file_entity / file_entity.pages.inc @ 66c11afc

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 Why basename? Why not drupal_basename which was working up until recently.
39
  $headers = array(
40
    'Content-Type' => mime_header_encode($file->filemime),
41
    'Content-Disposition' => 'attachment; filename="' . mime_header_encode(basename($file->uri)) . '"',
42
    'Content-Length' => $file->filesize,
43
    'Content-Transfer-Encoding' => 'binary',
44
    'Pragma' => 'no-cache',
45
    'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
46
    'Expires' => '0',
47
  );
48

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

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

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

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

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

    
99
    case 2:
100
      return file_entity_add_upload_step_filetype($form, $form_state, $options);
101

    
102
    case 3:
103
      return file_entity_add_upload_step_scheme($form, $form_state, $options);
104

    
105
    case 4:
106
      return file_entity_add_upload_step_fields($form, $form_state, $options);
107

    
108
  }
109
}
110

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

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

    
132
  form_load_include($form_state, 'inc', 'file_entity', 'file_entity.pages');
133

    
134
  return $form;
135
}
136

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

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

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

    
164
  return $form;
165
}
166

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

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

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

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

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

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

    
214
  return $form;
215
}
216

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

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

    
235
  // Add fields.
236
  field_attach_form('file', $file, $form, $form_state);
237

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

    
250
  return $form;
251
}
252

    
253
/**
254
 * Page callback to show file usage information.
255
 */
256
function file_entity_usage_page($file) {
257
  drupal_set_title(t('<em>Usage of @type</em> @title', array('@type' => $file->type, '@title' => $file->filename)), PASS_THROUGH);
258

    
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
  $triggered_next = $trigger == 'edit-next' || (strpos($trigger, 'edit-next--') === 0);
359
  $triggered_previous = $trigger == 'edit-previous' || (strpos($trigger, 'edit-previous--') === 0);
360
  $step_delta = ($triggered_previous) ? -1 : 1;
361

    
362
  $steps_to_check = array(2, 3);
363
  if ($triggered_previous) {
364
    // If the previous button was hit,
365
    // the step checking order should be reversed 3, 2.
366
    $steps_to_check = array_reverse($steps_to_check);
367
  }
368

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

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

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

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

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

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

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

    
466
      // Change the file from temporary to permanent.
467
      $file->status = FILE_STATUS_PERMANENT;
468

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

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

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

    
497
  // Clear the page and block caches.
498
  cache_clear_all();
499
}
500

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

    
520
  $destination = trim($params['file_directory'], '/');
521

    
522
  // Replace tokens.
523
  $destination = token_replace($destination, $data);
524

    
525
  return $params['uri_scheme'] . '://' . $destination;
526
}
527

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

    
538
  $form['upload']['#type'] = 'plupload';
539

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

    
554
  $form['submit']['#value'] = t('Start upload');
555
  return $form;
556
}
557

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

    
566
  // Ensure writable destination directory for the files.
567
  file_prepare_directory($upload_location, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
568

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

    
580
      $file = file_uri_to_object($destination);
581
      $file->status = FILE_STATUS_PERMANENT;
582
      file_save($file);
583

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

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

    
608
  // Clear the page and block caches.
609
  cache_clear_all();
610
}
611

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

    
627
  $form_state['file'] = $file;
628

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

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

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

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

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

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

    
674
    $form['replace_upload'] = array(
675
      '#type' => 'file',
676
      '#title' => t('Replace file'),
677
      '#description' => t('This file will replace the existing file. This action cannot be undone.'),
678
      '#upload_validators' => file_entity_get_upload_validators($replacement_options),
679
      '#pre_render' => array('file_entity_upload_validators_pre_render'),
680
    );
681
    $form['replace_keep_original_filename'] = array(
682
      '#type' => 'checkbox',
683
      '#title' => t('Keep original filename'),
684
      '#default_value' => variable_get('file_entity_file_replace_options_keep_original_filename', FALSE),
685
      '#description' => t('Rename the newly uploaded file to the name of the original file. This action cannot be undone.'),
686
    );
687
  }
688

    
689
  $form['preview'] = file_view_file($file, 'preview');
690

    
691
  $form['additional_settings'] = array(
692
    '#type' => 'vertical_tabs',
693
    '#weight' => 99,
694
  );
695

    
696
  // File destination information for administrators.
697
  $form['destination'] = array(
698
    '#type' => 'fieldset',
699
    '#access' => user_access('administer files') && file_entity_file_is_writeable($file),
700
    '#title' => t('Destination'),
701
    '#collapsible' => TRUE,
702
    '#collapsed' => TRUE,
703
    '#group' => 'additional_settings',
704
    '#attributes' => array(
705
      'class' => array('file-form-destination'),
706
    ),
707
    '#attached' => array(
708
      'js' => array(
709
        drupal_get_path('module', 'file_entity') . '/file_entity.js',
710
      ),
711
    ),
712
  );
713

    
714
  $options = array();
715
  foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $info) {
716
    $options[$scheme] = check_plain($info['name']);
717
  }
718

    
719
  $form['destination']['scheme'] = array(
720
    '#type' => 'radios',
721
    '#title' => t('Destination'),
722
    '#options' => $options,
723
    '#default_value' => file_uri_scheme($file->uri),
724
  );
725

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

    
758
  // Add the buttons.
759
  $form['actions'] = array('#type' => 'actions');
760
  $form['actions']['submit'] = array(
761
    '#type' => 'submit',
762
    '#value' => t('Save'),
763
    '#weight' => 5,
764
    '#submit' => array('file_entity_edit_submit'),
765
    '#validate' => array('file_entity_edit_validate'),
766
  );
767
  $form['actions']['delete'] = array(
768
    '#type' => 'submit',
769
    '#value' => t('Delete'),
770
    '#weight' => 10,
771
    '#submit' => array('file_entity_edit_delete_submit'),
772
    '#access' => file_entity_access('delete', $file),
773
  );
774

    
775
  // Build the URL for the cancel button taking into account that there might be
776
  // a "destination" that includes query string variables.
777
  $parameters = drupal_get_query_parameters();
778
  $destination = isset($parameters['destination']) ? $parameters['destination'] : 'file/' . $file->fid;
779
  $url = drupal_parse_url($destination);
780

    
781
  $form['actions']['cancel'] = array(
782
    '#type' => 'link',
783
    '#title' => t('Cancel'),
784
    '#href' => $url['path'],
785
    '#options' => array('query' => $url['query']),
786
    '#weight' => 15,
787
  );
788

    
789
  $langcode = function_exists('entity_language') ? entity_language('file', $file) : NULL;
790
  field_attach_form('file', $file, $form, $form_state, $langcode);
791

    
792
  return $form;
793
}
794

    
795
/**
796
 * Form validation handler for file_entity_edit().
797
 */
798
function file_entity_edit_validate($form, &$form_state) {
799
  $file = (object) $form_state['values'];
800

    
801
  // Validate the "associated user" field.
802
  if (!empty($file->name) && !($account = user_load_by_name($file->name))) {
803
    // The use of empty() is mandatory in the context of usernames
804
    // as the empty string denotes the anonymous user. In case we
805
    // are dealing with an anonymous user we set the user ID to 0.
806
    form_set_error('name', t('The username %name does not exist.', array('%name' => $file->name)));
807
  }
808

    
809
  // Handle the replacement file if uploaded.
810
  if (isset($form_state['values']['replace_upload'])) {
811
    // Save the file as a temporary file.
812
    $file = file_save_upload('replace_upload', $form['replace_upload']['#upload_validators']);
813
    if (!empty($file)) {
814
      // Put the temporary file in form_values so we can save it on submit.
815
      $form_state['values']['replace_upload'] = $file;
816
    }
817
    elseif ($file === FALSE) {
818
      // File uploaded failed.
819
      form_set_error('replace_upload', t('The replacement file could not be uploaded.'));
820
    }
821
  }
822

    
823
  // Run entity form validation.
824
  entity_form_field_validate('file', $form, $form_state);
825
}
826

    
827
/**
828
 * Form submission handler for the 'Save' button for file_entity_edit().
829
 */
830
function file_entity_edit_submit($form, &$form_state) {
831
  $file = $form_state['file'];
832
  $orphaned_uri = '';
833

    
834
  // Check if a replacement file has been uploaded.
835
  if (!empty($form_state['values']['replace_upload'])) {
836
    $replacement = $form_state['values']['replace_upload'];
837
    // Move file from temp to permanent home.
838
    if (!empty($form_state['values']['replace_keep_original_filename'])
839
    && $form_state['values']['replace_keep_original_filename']) {
840
      $destination_uri = rtrim($file->uri, drupal_basename($file->uri)) . drupal_basename($file->uri);
841
    }
842
    else {
843
      $destination_uri = rtrim($file->uri, drupal_basename($file->uri)) . drupal_basename($replacement->uri);
844
    }
845
    $replace_mode = $destination_uri == $file->uri ? FILE_EXISTS_REPLACE : FILE_EXISTS_RENAME;
846
    if ($new_file_uri = file_unmanaged_copy($replacement->uri, $destination_uri, $replace_mode)) {
847
      // @todo Add watchdog() about replaced file here?
848

    
849
      // Remove temporary file.
850
      file_delete($replacement);
851

    
852
      // Update if the uri target has changed.
853
      if ($new_file_uri != $file->uri) {
854
        // Store the original file uri to delete if save is successful.
855
        $orphaned_uri = $file->uri;
856

    
857
        // Update file entity uri.
858
        $file->uri = $new_file_uri;
859
      }
860
    }
861
  }
862

    
863
  // Run entity form submit handling and save the file.
864
  entity_form_submit_build_entity('file', $file, $form, $form_state);
865

    
866
  // A user might assign the associated user by entering a user name in the file
867
  // edit form, which we then need to translate to a user ID.
868
  if (isset($file->name)) {
869
    // The use of isset() is mandatory in the context of user IDs, because
870
    // user ID 0 denotes the anonymous user.
871
    if ($user = user_load_by_name($file->name)) {
872
      $file->uid = $user->uid;
873
    }
874
    else {
875
      // Anonymous user.
876
      $file->uid = 0;
877
    }
878
  }
879
  elseif ($file->uid) {
880
    $user = user_load($file->uid);
881
    $file->name = $user->name;
882
  }
883

    
884
  if (file_uri_scheme($file->uri) != $form_state['values']['scheme']) {
885
    $file_destination = $form_state['values']['scheme'] . '://' . file_uri_target($file->uri);
886
    $file_destination = file_stream_wrapper_uri_normalize($file_destination);
887
    $file_destination_dirname = drupal_dirname($file_destination);
888
    // Create the directory in case it doesn't exist.
889
    file_prepare_directory($file_destination_dirname, FILE_CREATE_DIRECTORY);
890
    if ($moved_file = file_move($file, $file_destination, FILE_EXISTS_RENAME)) {
891
      // Only re-assign the file object if file_move() did not fail.
892
      $file = $moved_file;
893
    }
894
  }
895

    
896
  file_save($file);
897

    
898
  $args = array(
899
    '@type' => file_entity_type_get_name($file),
900
    '%title' => entity_label('file', $file),
901
  );
902
  watchdog('file', '@type: updated %title.', $args);
903
  drupal_set_message(t('@type %title has been updated.', $args));
904

    
905
  // Clean up orphaned file.
906
  if (!empty($orphaned_uri)) {
907
    file_unmanaged_delete($orphaned_uri);
908

    
909
    $args['@orphaned'] = file_uri_target($orphaned_uri);
910
    watchdog('file', '@type: deleted orphaned file @orphaned for %title.', $args);
911
    drupal_set_message(t('The replaced @type @orphaned has been deleted.', $args));
912
  }
913

    
914
  $form_state['redirect'] = 'file/' . $file->fid;
915

    
916
  // Clear the page and block caches.
917
  cache_clear_all();
918
}
919

    
920
/**
921
 * Form submission handler for the 'Delete' button for file_entity_edit().
922
 */
923
function file_entity_edit_delete_submit($form, &$form_state) {
924
  $fid = $form_state['values']['fid'];
925
  $destination = array();
926
  if (isset($_GET['destination'])) {
927
    $destination = drupal_get_destination();
928
    unset($_GET['destination']);
929
  }
930
  $form_state['redirect'] = array('file/' . $fid . '/delete', array('query' => $destination));
931

    
932
  // Clear the page and block caches.
933
  cache_clear_all();
934
}
935

    
936
/**
937
 * Page callback: Form constructor for the file deletion confirmation form.
938
 *
939
 * Path: file/%file/delete
940
 *
941
 * @param object $file
942
 *   A file object from file_load().
943
 *
944
 * @see file_entity_menu()
945
 */
946
function file_entity_delete_form($form, &$form_state, $file) {
947
  $form_state['file'] = $file;
948

    
949
  $form['fid'] = array(
950
    '#type' => 'value',
951
    '#value' => $file->fid,
952
  );
953

    
954
  $description = t('This action cannot be undone.');
955
  if ($references = file_usage_list($file)) {
956
    $description .= ' ' . t('This file is currently in use and may cause problems if deleted.');
957
  }
958

    
959
  return confirm_form($form,
960
    t('Are you sure you want to delete the file %title?', array(
961
      '%title' => entity_label('file', $file),
962
    )),
963
    'file/' . $file->fid,
964
    $description,
965
    t('Delete')
966
  );
967
}
968

    
969
/**
970
 * Form submission handler for file_entity_delete_form().
971
 */
972
function file_entity_delete_form_submit($form, &$form_state) {
973
  if ($form_state['values']['confirm'] && $file = file_load($form_state['values']['fid'])) {
974
    // Use file_delete_multiple() rather than file_delete() since we want to
975
    // avoid unwanted validation and usage checking.
976
    file_delete_multiple(array($file->fid));
977

    
978
    $args = array(
979
      '@type' => file_entity_type_get_name($file),
980
      '%title' => entity_label('file', $file),
981
    );
982
    watchdog('file', '@type: deleted %title.', $args);
983
    drupal_set_message(t('@type %title has been deleted.', $args));
984
  }
985

    
986
  $form_state['redirect'] = '<front>';
987

    
988
  // Clear the page and block caches.
989
  cache_clear_all();
990
}
991

    
992
/**
993
 * Form constructor for file deletion confirmation form.
994
 *
995
 * @param array $files
996
 *   An array of file objects.
997
 */
998
function file_entity_multiple_delete_form($form, &$form_state, array $files) {
999
  $form['files'] = array(
1000
    '#prefix' => '<ul>',
1001
    '#suffix' => '</ul>',
1002
    '#tree' => TRUE,
1003
  );
1004

    
1005
  $files_have_usage = FALSE;
1006
  foreach ($files as $fid => $file) {
1007
    $title = entity_label('file', $file);
1008
    $usage = file_usage_list($file);
1009
    if (!empty($usage)) {
1010
      $files_have_usage = TRUE;
1011
      $title = t('@title (in use)', array('@title' => $title));
1012
    }
1013
    else {
1014
      $title = check_plain($title);
1015
    }
1016
    $form['files'][$fid] = array(
1017
      '#type' => 'hidden',
1018
      '#value' => $fid,
1019
      '#prefix' => '<li>',
1020
      '#suffix' => $title . "</li>\n",
1021
    );
1022
  }
1023

    
1024
  $form['operation'] = array(
1025
    '#type' => 'hidden',
1026
    '#value' => 'delete',
1027
  );
1028

    
1029
  $description = t('This action cannot be undone.');
1030
  if ($files_have_usage) {
1031
    $description .= ' ' . t('Some of the files are currently in use and may cause problems if deleted.');
1032
  }
1033

    
1034
  return confirm_form(
1035
    $form,
1036
    format_plural(count($files), 'Are you sure you want to delete this file?', 'Are you sure you want to delete these files?'),
1037
    'admin/content/file',
1038
    $description,
1039
    t('Delete')
1040
  );
1041
}
1042

    
1043
/**
1044
 * Form submission handler for file_entity_multiple_delete_form().
1045
 */
1046
function file_entity_multiple_delete_form_submit($form, &$form_state) {
1047
  if ($form_state['values']['confirm'] && $fids = array_keys($form_state['values']['files'])) {
1048
    file_delete_multiple($fids);
1049
    $count = count($fids);
1050
    watchdog('file', 'Deleted @count files.', array('@count' => $count));
1051
    drupal_set_message(format_plural($count, 'Deleted one file.', 'Deleted @count files.'));
1052
  }
1053
  $form_state['redirect'] = 'admin/content/file';
1054

    
1055
  // Clear the page and block caches.
1056
  cache_clear_all();
1057
}
1058

    
1059
/**
1060
 * Page callback for the file edit form.
1061
 *
1062
 * @deprecated
1063
 *   Use drupal_get_form('file_entity_edit')
1064
 */
1065
function file_entity_page_edit($file) {
1066
  return drupal_get_form('file_entity_edit', $file);
1067
}
1068

    
1069
/**
1070
 * Page callback for the file deletion confirmation form.
1071
 *
1072
 * @deprecated
1073
 *   Use drupal_get_form('file_entity_delete_form')
1074
 */
1075
function file_entity_page_delete($file) {
1076
  return drupal_get_form('file_entity_delete_form');
1077
}
1078

    
1079
/**
1080
 * Retrieves the upload validators for a file.
1081
 *
1082
 * @param array $options
1083
 *   (optional) An array of options for file validation.
1084
 *
1085
 * @return array
1086
 *   An array suitable for passing to file_save_upload() or for a managed_file
1087
 *   or upload element's '#upload_validators' property.
1088
 */
1089
function file_entity_get_upload_validators(array $options = array()) {
1090
  // Set up file upload validators.
1091
  $validators = array();
1092

    
1093
  // Validate file extensions. If there are no file extensions in $params and
1094
  // there are no Media defaults, there is no file extension validation.
1095
  if (!empty($options['file_extensions'])) {
1096
    $validators['file_validate_extensions'] = array($options['file_extensions']);
1097
  }
1098
  else {
1099
    $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'));
1100
  }
1101

    
1102
  // Cap the upload size according to the system or user defined limit.
1103
  $max_filesize = parse_size(file_upload_max_size());
1104
  $file_entity_max_filesize = parse_size(variable_get('file_entity_max_filesize', ''));
1105

    
1106
  // If the user defined a size limit, use the smaller of the two.
1107
  if (!empty($file_entity_max_filesize)) {
1108
    $max_filesize = min($max_filesize, $file_entity_max_filesize);
1109
  }
1110

    
1111
  if (!empty($options['max_filesize']) && $options['max_filesize'] < $max_filesize) {
1112
    $max_filesize = parse_size($options['max_filesize']);
1113
  }
1114

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

    
1118
  // Add image validators.
1119
  $options += array('min_resolution' => 0, 'max_resolution' => 0);
1120
  if ($options['min_resolution'] || $options['max_resolution']) {
1121
    $validators['file_validate_image_resolution'] = array($options['max_resolution'], $options['min_resolution']);
1122
  }
1123

    
1124
  // Add other custom upload validators from options.
1125
  if (!empty($options['upload_validators'])) {
1126
    $validators += $options['upload_validators'];
1127
  }
1128

    
1129
  return $validators;
1130
}
1131

    
1132
function file_entity_upload_archive_form($form, &$form_state) {
1133
  $options = array(
1134
    'file_extensions' => archiver_get_extensions(),
1135
  );
1136

    
1137
  $form['upload'] = array(
1138
    '#type' => 'managed_file',
1139
    '#title' => t('Upload an archive file'),
1140
    '#upload_location' => NULL, // Upload to the temporary directory.
1141
    '#upload_validators' => file_entity_get_upload_validators($options),
1142
    '#progress_indicator' => 'bar',
1143
    '#required' => TRUE,
1144
    '#pre_render' => array('file_managed_file_pre_render', 'file_entity_upload_validators_pre_render'),
1145
  );
1146

    
1147
  $form['pattern'] = array(
1148
    '#type' => 'textfield',
1149
    '#title' => t('Pattern'),
1150
    '#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.'),
1151
    '#default_value' => '.*',
1152
    '#required' => TRUE,
1153
  );
1154

    
1155
  $form['actions'] = array('#type' => 'actions');
1156
  $form['actions']['submit'] = array(
1157
    '#type' => 'submit',
1158
    '#value' => t('Submit'),
1159
  );
1160

    
1161
  form_load_include($form_state, 'inc', 'file_entity', 'file_entity.pages');
1162

    
1163
  return $form;
1164
}
1165

    
1166
/**
1167
 * Upload a file.
1168
 */
1169
function file_entity_upload_archive_form_submit($form, &$form_state) {
1170
  $form_state['files'] = array();
1171

    
1172
  if ($archive = file_load($form_state['values']['upload'])) {
1173
    if ($archiver = archiver_get_archiver($archive->uri)) {
1174
      $files = $archiver->listContents();
1175

    
1176
      $extract_dir = file_default_scheme() . '://' . pathinfo($archive->filename, PATHINFO_FILENAME);
1177
      $extract_dir = file_destination($extract_dir, FILE_EXISTS_RENAME);
1178
      if (!file_prepare_directory($extract_dir, FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY)) {
1179
        throw new Exception(t('Unable to prepar, e directory %dir for extraction.', array('%dir' => $extract_dir)));
1180
      }
1181

    
1182
      $archiver->extract($extract_dir);
1183
      $pattern = '/' . $form_state['values']['pattern'] . '/';
1184
      if ($files = file_scan_directory($extract_dir, $pattern)) {
1185
        foreach ($files as $file) {
1186
          $file->status = FILE_STATUS_PERMANENT;
1187
          $file->uid = $archive->uid;
1188
          file_save($file);
1189
          $form_state['files'][$file->fid] = $file;
1190
        }
1191
      }
1192
      drupal_set_message(t('Extracted %file and added @count new files.', array('%file' => $archive->filename, '@count' => count($files))));
1193
    }
1194
    else {
1195
      throw new Exception(t('Cannot extract %file, not a valid archive.', array('%file' => $archive->uri)));
1196
    }
1197
  }
1198

    
1199
  // Redirect to the file edit page.
1200
  if (file_entity_access('edit') && module_exists('multiform')) {
1201
    $destination = array('destination' => 'admin/content/file');
1202
    if (isset($_GET['destination'])) {
1203
      $destination = drupal_get_destination();
1204
      unset($_GET['destination']);
1205
    }
1206
    $form_state['redirect'] = array('admin/content/file/edit-multiple/' . implode(' ', array_keys($form_state['files'])), array('query' => $destination));
1207
  }
1208
  else {
1209
    $form_state['redirect'] = 'admin/content/file';
1210
  }
1211
}