From ebe58478cd1478b23dbac1519a5ce625230f01f7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Claes=20Gyllensv=C3=A4rd?= <letharion@gmail.com>
Date: Sun, 29 Apr 2012 15:10:57 +0200
Subject: [PATCH] Include the file/add functionality taken from the media module.

---
 file_entity.module    |   30 ++++++++
 file_entity.pages.inc |  184 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 214 insertions(+), 0 deletions(-)

diff --git a/file_entity.module b/file_entity.module
index 8d2e31c..c725323 100644
--- a/file_entity.module
+++ b/file_entity.module
@@ -15,6 +15,8 @@ require_once dirname(__FILE__) . '/file_entity.file_api.inc';
 // @todo Remove when http://drupal.org/node/977052 is fixed.
 require_once dirname(__FILE__) . '/file_entity.field.inc';
 
+require_once dirname(__FILE__) . '/file_entity.variables.inc';
+
 /**
  * Implements hook_hook_info().
  */
@@ -112,6 +114,21 @@ function file_entity_menu() {
     'type' => MENU_DEFAULT_LOCAL_TASK,
   );
   // general view, edit, delete for files
+  $items['file/add'] = array(
+    'title' => 'Add file',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('file_entity_add_upload'),
+    'access arguments' => array('administer files'),
+    'file' => 'file_entity.pages.inc',
+  );
+  if (module_exists('plupload') && module_exists('multiform')) {
+    $items['file/add']['page arguments'] = array('file_entity_add_upload_multiple');
+  }
+  $items['file/add/upload'] = array(
+    'title' => 'Upload',
+    'type' => MENU_DEFAULT_LOCAL_TASK,
+    'weight' => -10,
+  );
   $items['file/%file'] = array(
     'title callback' => 'entity_label',
     'title arguments' => array('file', 1),
@@ -867,3 +884,16 @@ function file_entity_file_is_local($file) {
   $wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL);
   return !empty($wrappers[$scheme]) && empty($wrappers[$scheme]['remote']);
 }
+
+/**
+ * Sets the status to FILE_STATUS_PERMANENT.
+ *
+ * @param $file
+ *  A file object.
+ */
+function _file_entity_save_file_permenently(&$file) {
+  if ($file->status < FILE_STATUS_PERMANENT) {
+    $file->status = FILE_STATUS_PERMANENT;
+    file_save($file);
+  }
+}
diff --git a/file_entity.pages.inc b/file_entity.pages.inc
index 00f8a84..dad4764 100644
--- a/file_entity.pages.inc
+++ b/file_entity.pages.inc
@@ -31,6 +31,190 @@ function file_entity_view_page($file) {
 }
 
 /**
+ * Form callback for adding media via an upload form.
+ * @todo: should use the AJAX uploader
+ */
+function file_entity_add_upload($form, &$form_state, $params = array()) {
+  // Set up file upload validators.
+  $validators = array();
+
+  // Validate file extensions. If there are no file extensions in $params and
+  // there are no Media defaults, there is no file extension validation.
+  if (!empty($params['file_extensions'])) {
+    $validators['file_validate_extensions'] = array($params['file_extensions']);
+  }
+  elseif ($tmp = file_entity_variable_get('file_extensions')) {
+    $validators['file_validate_extensions'] = array($tmp);
+  }
+
+  // Validate file size but do not allow anything higher than file_upload_max_size().
+  $max_filesize = file_upload_max_size();
+  if (!empty($params['max_filesize']) && $params['max_filesize'] < $max_filesize) {
+    $validators['file_validate_size'] = array(parse_size($params['max_filesize']));
+  }
+  elseif (($tmp = file_entity_variable_get('max_filesize')) && $tmp < $max_filesize) {
+    $validators['file_validate_size'] = array(parse_size($tmp));
+  }
+  else {
+    $validators['file_validate_size'] = array($max_filesize);
+  }
+
+  // Add image validators.
+  $params += array('min_resolution' => 0, 'max_resolution' => 0);
+  if ($params['min_resolution'] || $params['max_resolution']) {
+    $validators['file_validate_image_resolution'] = array($params['max_resolution'], $params['min_resolution']);
+  }
+
+  $form['#validators'] = $validators;
+
+  $form['upload'] = array(
+    '#type' => 'file',
+    '#title' => t('Upload a new file'),
+    '#description' => theme('file_upload_help', array('description' => '', 'upload_validators' => $validators)),
+    '#upload_validators' => $validators,
+  );
+
+  $form['actions'] = array('#type' => 'actions');
+  $form['actions']['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Submit'),
+  );
+
+  return $form;
+}
+
+/**
+ * Validate the generic file upload with the global media settings.
+ */
+function file_entity_add_upload_validate($form, &$form_state) {
+  // Save the file as a temporary file.
+  $file = file_save_upload('upload', $form['#validators']);
+
+  if ($file === NULL) {
+    form_set_error('upload', t("No file appears to have been selected."));
+  }
+  elseif ($file === FALSE) {
+    form_set_error('upload', t('File upload error.'));
+  }
+  else {
+    $form_state['values']['upload'] = $file;
+  }
+}
+
+/**
+ * Upload a file.
+ */
+function file_entity_add_upload_submit($form, &$form_state) {
+  $params = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : array();
+  $file = $form_state['values']['upload'];
+
+  // The media browser widget does not use the 'display' field.
+  $file->display = TRUE;
+
+  // Change the file status from temporary to permanent.
+  _file_entity_save_file_permenently($file);
+
+  // Determine what URI scheme this file should use.
+  $scheme = !empty($params['uri_scheme']) && file_stream_wrapper_valid_scheme($params['uri_scheme']) ? $params['uri_scheme'] : file_default_scheme();
+  $scheme .= '://';
+
+  // Prepare the file's subdirectory path.
+  $directory = '';
+  if (!empty($params['file_directory'])) {
+    $directory = token_replace($params['file_directory']) . '/';
+
+    // If the directory isn't writable, or doesn't exist and can't be created,
+    // the upload will fail.
+    $prepare_directory = file_stream_wrapper_uri_normalize($scheme . $directory);
+    if (!file_prepare_directory($prepare_directory, FILE_CREATE_DIRECTORY)) {
+      drupal_set_message(t('The file directory @dir does not exist or is not writable. Please contact an administrator.', array('@dir' => $prepare_directory)), 'error');
+      return;
+    }
+  }
+
+  // Compose the file's permanent destination.
+  $destination = file_stream_wrapper_uri_normalize($scheme . $directory . $file->filename);
+
+  // Save the uploaded file to the permanent location.
+  $file = file_move($file, $destination, FILE_EXISTS_RENAME);
+
+  if ($file) {
+    $form_state['file'] = $file;
+    drupal_set_message(t('The file @name was uploaded', array('@name' => $file->filename)));
+  }
+  else {
+    drupal_set_message(t('An error occurred and no file was uploaded.'), 'error');
+    return;
+  }
+
+  // Redirect to the file edit page after submission.
+  if (file_entity_access('edit')) {
+    $destination = array('destination' => 'admin/content/file');
+    if (isset($_GET['destination'])) {
+      $destination = drupal_get_destination();
+      unset($_GET['destination']);
+    }
+    $form_state['redirect'] = array('file/' . $file->fid . '/edit', array('query' => $destination));
+  }
+  else {
+    $form_state['redirect'] = 'admin/content/file';
+  }
+}
+
+function file_entity_add_upload_multiple($form, &$form_state, $params = array()) {
+  $form = file_entity_add_upload($form, $form_state, $params);
+  unset($form['upload']['#title']);
+  // The validators will be set from plupload anyway.  This isn't pretty, but don't
+  // it to show up twice.
+  unset($form['upload']['#description']);
+
+  $form['upload']['#type'] = 'plupload';
+  $form['submit']['#value'] = t('Start upload');
+  return $form;
+}
+
+function file_entity_add_upload_multiple_submit($form, &$form_state) {
+  $scheme = variable_get('file_default_scheme', 'public') . '://';
+
+  // We can't use file_save_upload() because of http://www.jacobsingh.name/content/tight-coupling-no-not
+  foreach ($form_state['values']['upload'] as $uploaded_file) {
+    if ($uploaded_file['status'] == 'done') {
+      $source = $uploaded_file['tmppath'];
+      $destination = file_stream_wrapper_uri_normalize($scheme . $uploaded_file['name']);
+      // Rename it to its original name, and put it in its final home.
+      // Note - not using file_move here because if we call file_get_mime
+      // (in file_uri_to_object) while it has a .tmp extension, it horks.
+
+      $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
+
+      $file = file_uri_to_object($destination);
+      file_save($file);
+      _file_entity_save_file_permenently($file);
+
+      $saved_files[] = $file;
+      $form_state['files'][$file->fid] = $file;
+    }
+    else {
+      // @todo: move this to element validate or something.
+      form_set_error('pud', t('The specified file %name could not be uploaded.', array('%name' => $uploaded_file['name'])));
+    }
+  }
+
+  // Redirect to the file edit page.
+  if (file_entity_access('edit') && module_exists('multiform')) {
+    $destination = array('destination' => 'admin/content/file');
+    if (isset($_GET['destination'])) {
+      $destination = drupal_get_destination();
+      unset($_GET['destination']);
+    }
+    $form_state['redirect'] = array('admin/content/file/edit-multiple/' . implode(' ', array_keys($form_state['files'])), array('query' => $destination));
+  }
+  else {
+    $form_state['redirect'] = 'admin/content/file';
+  }
+}
+
+/**
  * Page callback: Form constructor for the file edit form.
  *
  * Path: file/%file/edit
-- 
1.7.3.4

