You are here

function filefield_source_attach_value in FileField Sources 6

Same name and namespace in other branches
  1. 7 sources/attach.inc \filefield_source_attach_value()

A #filefield_value_callback function.

1 string reference to 'filefield_source_attach_value'
filefield_source_attach_info in sources/attach.inc
Implements hook_filefield_source_info().

File

sources/attach.inc, line 204
A FileField extension to allow use of files within a server directory.

Code

function filefield_source_attach_value($element, &$item) {
  if (!empty($item['filefield_attach']['filename'])) {
    $field = content_fields($element['#field_name'], $element['#type_name']);
    $filepath = $item['filefield_attach']['filename'];

    // Check that the destination is writable.
    $directory = filefield_widget_file_path($field);
    if (!field_file_check_directory($directory, FILE_CREATE_DIRECTORY, $element['filefield_attach']['filename'])) {
      return;
    }

    // Clean up the file name extensions and transliterate.
    $original_filepath = $filepath;
    $new_filepath = filefield_sources_clean_filename($filepath);
    rename($filepath, $new_filepath);
    $filepath = $new_filepath;

    // Run all the normal validations, minus file size restrictions.
    $validators = $element['#upload_validators'];
    if (isset($validators['filefield_validate_size'])) {
      unset($validators['filefield_validate_size']);
    }

    // Save the file to the new location.
    if ($file = field_file_save_file($filepath, $validators, $directory)) {
      $item = array_merge($item, $file);

      // Delete the original file if "moving" the file instead of copying.
      if (empty($field['widget']['filefield_source_attach_mode']) || $field['widget']['filefield_source_attach_mode'] !== 'copy') {
        @unlink($filepath);
      }
    }

    // Restore the original file name if the file still exists.
    if (file_exists($filepath) && $filepath != $original_filepath) {
      rename($filepath, $original_filepath);
    }
    $item['filefield_attach']['filename'] = '';
  }
}