You are here

function upload_element_save in Upload element 6

Saves an uploaded file

Parameters

object $file File object:

string $dest destination directory to move the file to:

int $replace files move action:

string $presetname Imagecache preset to perfrom on the uploaded image.:

bool $delete_original A flag to tell the function how to handle: the existing file when it is deleted or replaced. This is used to prevent the status flag being set to temperory when the file is still used by the system somewhere else. For example, if you are saving a new node revision, with a new file, you would want to ensure that this is set to FALSE if the old image is still valid for some other revision.

Return value

int The {files}.fid or 0

File

./upload_element.module, line 441
A module that provides two new elements to the FAPI for file handling.

Code

function upload_element_save(&$file, $dest = 0, $replace = FILE_EXISTS_RENAME, $presetname = FALSE, $delete_original = TRUE) {
  $fid = 0;
  if (is_object($file)) {
    $base = file_directory_path();
    if (strstr($dest, $base) === FALSE) {
      $dest = $base . '/' . ltrim($dest, '/');
    }
    file_check_directory($dest, 1);
    if (!isset($file->submit_action)) {
      $file->submit_action = UPLOAD_ELEMENT_NONE;
    }
    switch ($file->submit_action) {
      case UPLOAD_ELEMENT_NONE:
        $fid = $file->fid;
        break;
      case UPLOAD_ELEMENT_DELETE:
        if ($delete_original) {
          _upload_element_delete($file->fid);
        }
        break;
      case UPLOAD_ELEMENT_REPLACE:
        if ($delete_original) {
          _upload_element_delete($file->original_fid);
        }

      // fall through
      case UPLOAD_ELEMENT_NEW:
        $uploaded = FALSE;
        if ($presetname) {
          $destination = file_create_filename($file->filename, $dest);
          if (upload_element_imagecache_action($presetname, $file->filepath, $destination)) {
            $file->filepath = $destination;
            $uploaded = TRUE;
          }
        }
        if (!$uploaded) {
          $uploaded = file_move($file, $dest . '/' . $file->filename, $replace);
        }
        if ($uploaded) {
          $file->status = FILE_STATUS_PERMANENT;

          // Clear PHP stat cache in case filesize has changed.
          clearstatcache();
          if ($file_size = @filesize($file->filepath)) {
            $file->filesize = $file_size;
          }
          drupal_write_record('files', $file, 'fid');
          $fid = $file->fid;

          // Imagecache may need flushing if using the same filepath.
          if (function_exists('imagecache_image_flush')) {
            imagecache_image_flush($file->filepath);
          }
        }
        else {
          drupal_set_message(t('Error occured while saving the image!'), 'error');
        }
        break;
    }
  }

  // This cleans up the session by flushing old values.
  upload_element_clean_session();
  return $fid;
}