You are here

function _node_resource_file_save_upload in Services 7.3

Services wrapper for file_save_upload.

See also

file_save_upload()

file_managed_file_save_upload()

1 call to _node_resource_file_save_upload()
_node_resource_attach_file in resources/node_resource.inc
Attaches or overwrites file(s) to an existing node.

File

resources/node_resource.inc, line 729

Code

function _node_resource_file_save_upload($node_type, $field_name, $options = array()) {

  // The field_name on node_type should be checked in the access callback.
  $instance = field_info_instance('node', $field_name, $node_type);
  $field = field_read_field($field_name);
  $cardinality = $field['cardinality'];

  // If cardinality is not unlimited check the how many 'slots' we have left.
  if ($cardinality > 0 && isset($options['file_count'])) {

    // Already uploaded files
    $file_already_uploaded_count = $options['file_count'];

    // How many files we are going to upload.
    $file_upload_count = count($_FILES['files']['name']);

    // If we add new files and not replace already uploaded.
    if (isset($options['attach']) && $options['attach'] && $file_already_uploaded_count + $file_upload_count > $cardinality || (!isset($options['attach']) || !$options['attach']) && $file_upload_count > $cardinality) {
      return services_error(t('You cannot upload so many files.'));
    }
  }
  $destination = file_field_widget_uri($field, $instance);
  if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
    return services_error(t('The upload directory %directory for the file field !name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.', array(
      '%directory' => $destination,
      '!name' => $field_name,
    )));
  }
  $validators = array(
    'file_validate_extensions' => (array) $instance['settings']['file_extensions'],
    'file_validate_size' => array(
      0 => parse_size($instance['settings']['max_filesize']),
    ),
  );
  $files = $file_objs = array();
  foreach ($_FILES['files']['name'] as $key => $val) {

    // Let the file module handle the upload and moving.
    if (!($file = file_save_upload($key, $validators, $destination, FILE_EXISTS_RENAME))) {
      return services_error(t('Failed to upload file. @upload', array(
        '@upload' => $key,
      )), 406);
    }
    if ($file->fid) {

      // Add info to the array that will be returned/encdoed to xml/json.
      $files[] = array(
        'fid' => $file->fid,
        'uri' => services_resource_uri(array(
          'file',
          $file->fid,
        )),
      );
      $file_objs[] = $file;
    }
    else {
      return services_error(t('An unknown error occurred'), 500);
    }
  }
  return array(
    $files,
    $file_objs,
  );
}