file.module

Same filename and directory in other branches
  1. 10 core/modules/file/file.module
  2. 11.x core/modules/file/file.module
  3. 9 core/modules/file/file.module
  4. 8.9.x core/modules/file/file.module
  5. 7.x modules/file/file.module

File

core/modules/file/file.module

View source
<?php


/**
 * @file
 */

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\File\FileExists;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\FileInterface;
use Drupal\file\Upload\ManagedFileElementHelper;
use Drupal\file\Upload\FormFileUploader;

/**
 * Saves form file uploads.
 *
 * The files will be added to the {file_managed} table as temporary files.
 * Temporary files are periodically cleaned. Use the 'file.usage' service to
 * register the usage of the file which will automatically mark it as permanent.
 *
 * @param array $element
 *   The FAPI element whose values are being saved.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The current state of the form.
 * @param null|int $delta
 *   (optional) The delta of the file to return the file entity.
 *   Defaults to NULL.
 * @param \Drupal\Core\File\FileExists $fileExists
 *   (optional) The replace behavior when the destination file already exists.
 *
 * @return array|\Drupal\file\FileInterface|null|false
 *   An array of file entities or a single file entity if $delta != NULL. Each
 *   array element contains the file entity if the upload succeeded or FALSE if
 *   there was an error. Function returns NULL if no file was uploaded.
 *
 * @internal
 *   This function is internal, and may be removed in a minor version release.
 *   It wraps FormFileUploader::saveFormUploadedFiles() to allow correct error
 *   handling in forms. Contrib and custom code should not call this function,
 *   they should use the managed file upload widgets in core.
 *
 * @deprecated in drupal:11.5.0 and is removed from drupal:13.0.0. Use
 *   \Drupal::service(ManagedFileElementHelper::class)->saveFileUploads()
 *   instead.
 *
 * @see https://www.drupal.org/node/3382414
 * @see https://www.drupal.org/project/drupal/issues/3069020
 * @see https://www.drupal.org/project/drupal/issues/2482783
 */
function _file_save_upload_from_form(array $element, FormStateInterface $form_state, $delta = NULL, FileExists $fileExists = FileExists::Rename) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:11.5.0 and is removed from drupal:13.0.0. Use \\Drupal::service(ManagedFileElementHelper::class)->saveFileUploads() instead. See https://www.drupal.org/node/3382414', E_USER_DEPRECATED);
  return \Drupal::service(ManagedFileElementHelper::class)->saveFileUploads($element, $form_state, $delta, $fileExists);
}

/**
 * Saves file uploads to a new location.
 *
 * The files will be added to the {file_managed} table as temporary files.
 * Temporary files are periodically cleaned. Use the 'file.usage' service to
 * register the usage of the file which will automatically mark it as permanent.
 *
 * Note that this function does not support correct form error handling. The
 * file upload widgets in core do support this. It is advised to use these in
 * any custom form, instead of calling this function.
 *
 * @param string $form_field_name
 *   A string that is the associative array key of the upload form element in
 *   the form array.
 * @param array $validators
 *   (optional) An associative array of Validation Constraint plugins used to
 *   validate the file.
 *   If the array is empty, 'FileExtension' will be used by default with a safe
 *   list of extensions, as follows: "jpg jpeg gif png txt doc xls pdf ppt pps
 *   odt ods odp". To allow all extensions, you must explicitly set this array
 *   to ['FileExtension' => []]. (Beware: this is not safe and should only be
 *   allowed for trusted users, if at all.)
 * @param string|false $destination
 *   (optional) A string containing the URI that the file should be copied to.
 *   This must be a stream wrapper URI. If this value is omitted or set to
 *   FALSE, Drupal's temporary files scheme will be used ("temporary://").
 * @param null|int $delta
 *   (optional) The delta of the file to return the file entity.
 *   Defaults to NULL.
 * @param \Drupal\Core\File\FileExists $fileExists
 *   (optional) The replace behavior when the destination file already exists.
 *
 * @return array|\Drupal\file\FileInterface|null|false
 *   An array of file entities or a single file entity if $delta != NULL. Each
 *   array element contains the file entity if the upload succeeded or FALSE if
 *   there was an error. Function returns NULL if no file was uploaded.
 *
 * @deprecated in drupal:11.5.0 and is removed from drupal:13.0.0. Use
 *   \Drupal::service(FormFileUploader::class)->saveFormUploadedFiles() instead.
 *
 * @see https://www.drupal.org/node/3382414
 * @see ManagedFileElementHelper::saveFileUploads()
 */
function file_save_upload($form_field_name, $validators = [], $destination = FALSE, $delta = NULL, FileExists $fileExists = FileExists::Rename) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:11.5.0 and is removed from drupal:13.0.0. Use \\Drupal::service(FormFileUploader::class)->saveFormUploadedFiles() instead. See https://www.drupal.org/node/3382414', E_USER_DEPRECATED);
  if ($destination === FALSE || $destination === NULL) {
    $destination = 'temporary://';
  }
  return \Drupal::service(FormFileUploader::class)->saveFormUploadedFiles($form_field_name, $validators, $destination, $delta, $fileExists);
}

/**
 * Saves any files that have been uploaded into a managed_file element.
 *
 * @param array $element
 *   The FAPI element whose values are being saved.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The current state of the form.
 *
 * @return array|false
 *   An array of file entities for each file that was saved, keyed by its file
 *   ID. Each array element contains a file entity. Function returns FALSE if
 *   upload directory could not be created or no files were uploaded.
 *
 * @deprecated in drupal:11.5.0 and is removed from drupal:13.0.0. Use
 *   \Drupal::service(ManagedFileElementHelper::class)->managedFileSaveUpload()
 *   instead.
 *
 * @see https://www.drupal.org/node/3382414
 */
function file_managed_file_save_upload($element, FormStateInterface $form_state) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:11.5.0 and is removed from drupal:13.0.0. Use \\Drupal::service(ManagedFileElementHelper::class)->managedFileSaveUpload() instead. See https://www.drupal.org/node/3382414', E_USER_DEPRECATED);
  return \Drupal::service(ManagedFileElementHelper::class)->managedFileSaveUpload($element, $form_state);
}

/**
 * Retrieves a list of references to a file.
 *
 * @param \Drupal\file\FileInterface $file
 *   A file entity.
 * @param \Drupal\Core\Field\FieldDefinitionInterface|null $field
 *   (optional) A field definition to be used for this check. If given,
 *   limits the reference check to the given field. Defaults to NULL.
 * @param string $age
 *   (optional) A constant that specifies which references to count. Use
 *   EntityStorageInterface::FIELD_LOAD_REVISION (the default) to retrieve all
 *   references within all revisions or
 *   EntityStorageInterface::FIELD_LOAD_CURRENT to retrieve references only in
 *   the current revisions of all entities that have references to this file.
 * @param string $field_type
 *   (optional) The name of a field type. If given, limits the reference check
 *   to fields of the given type. If both $field and $field_type are given but
 *   $field is not the same type as $field_type, an empty array will be
 *   returned. Defaults to 'file'.
 *
 * @return array
 *   A multidimensional array. The keys are field_name, entity_type,
 *   entity_id and the value is an entity referencing this file.
 *
 * @ingroup file
 *
 * @deprecated in drupal:11.4.0 and is removed from drupal:13.0.0. Use
 *   \Drupal::service(\Drupal\file\FileReferenceResolver::class) instead.
 *
 * @see https://www.drupal.org/node/3573884
 */
function file_get_file_references(FileInterface $file, ?FieldDefinitionInterface $field = NULL, $age = EntityStorageInterface::FIELD_LOAD_REVISION, $field_type = 'file') {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:11.4.0 and is removed from drupal:13.0.0. Use \\Drupal::service(\\Drupal\\file\\FileReferenceResolver::class)->getReferences($file) instead. See https://www.drupal.org/node/3573884', E_USER_DEPRECATED);
  $references =& drupal_static(__FUNCTION__, []);
  $field_columns =& drupal_static(__FUNCTION__ . ':field_columns', []);
  // Fill the static cache, disregard $field and $field_type for now.
  if (!isset($references[$file->id()][$age])) {
    $references[$file->id()][$age] = [];
    $usage_list = \Drupal::service('file.usage')->listUsage($file);
    $file_usage_list = $usage_list['file'] ?? [];
    foreach ($file_usage_list as $entity_type_id => $entity_ids) {
      $entities = \Drupal::entityTypeManager()->getStorage($entity_type_id)
        ->loadMultiple(array_keys($entity_ids));
      foreach ($entities as $entity) {
        $bundle = $entity->bundle();
        // We need to find file fields for this entity type and bundle.
        if (!isset($file_fields[$entity_type_id][$bundle])) {
          $file_fields[$entity_type_id][$bundle] = [];
          // This contains the possible field names.
          foreach ($entity->getFieldDefinitions() as $field_name => $field_definition) {
            // If this is the first time this field type is seen, check
            // whether it references files.
            if (!isset($field_columns[$field_definition->getType()])) {
              $field_columns[$field_definition->getType()] = file_field_find_file_reference_column($field_definition);
            }
            // If the field type does reference files then record it.
            if ($field_columns[$field_definition->getType()]) {
              $file_fields[$entity_type_id][$bundle][$field_name] = $field_columns[$field_definition->getType()];
            }
          }
        }
        foreach ($file_fields[$entity_type_id][$bundle] as $field_name => $field_column) {
          // Iterate over the field items to find the referenced file and field
          // name. This will fail if the usage checked is in a non-current
          // revision because field items are from the current
          // revision.
          // We also iterate over all translations because a file can be linked
          // to a language other than the default.
          foreach ($entity->getTranslationLanguages() as $langcode => $language) {
            foreach ($entity->getTranslation($langcode)
              ->get($field_name) as $item) {
              if ($file->id() == $item->{$field_column}) {
                $references[$file->id()][$age][$field_name][$entity_type_id][$entity->id()] = $entity;
                break;

              }
            }
          }
        }
      }
    }
  }
  $return = $references[$file->id()][$age];
  // Filter the static cache down to the requested entries. The usual static
  // cache is very small so this will be very fast.
  $entity_field_manager = \Drupal::service('entity_field.manager');
  if ($field || $field_type) {
    foreach ($return as $field_name => $data) {
      foreach (array_keys($data) as $entity_type_id) {
        $field_storage_definitions = $entity_field_manager->getFieldStorageDefinitions($entity_type_id);
        $current_field = $field_storage_definitions[$field_name];
        if ($field_type && $current_field->getType() != $field_type || $field && $field->uuid() != $current_field->uuid()) {
          unset($return[$field_name][$entity_type_id]);
        }
      }
    }
  }
  return $return;
}

/**
 * Determine whether a field references files stored in {file_managed}.
 *
 * @param \Drupal\Core\Field\FieldDefinitionInterface $field
 *   A field definition.
 *
 * @return bool
 *   The field column if the field references {file_managed}.fid, typically
 *   fid, FALSE if it does not.
 *
 * @deprecated in drupal:11.4.0 and is removed from drupal:13.0.0. There is no
 *   replacement.
 *
 * @see https://www.drupal.org/node/3573884
 */
function file_field_find_file_reference_column(FieldDefinitionInterface $field) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:11.4.0 and is removed from drupal:13.0.0. There is no replacement. See https://www.drupal.org/node/3573884', E_USER_DEPRECATED);
  $schema = $field->getFieldStorageDefinition()
    ->getSchema();
  foreach ($schema['foreign keys'] as $data) {
    if ($data['table'] == 'file_managed') {
      foreach ($data['columns'] as $field_column => $column) {
        if ($column == 'fid') {
          return $field_column;
        }
      }
    }
  }
  return FALSE;
}

Functions

Title Deprecated Summary
file_field_find_file_reference_column

in drupal:11.4.0 and is removed from drupal:13.0.0. There is no replacement.

Determine whether a field references files stored in {file_managed}.
file_get_file_references

in drupal:11.4.0 and is removed from drupal:13.0.0. Use \Drupal::service(\Drupal\file\FileReferenceResolver::class) instead.

Retrieves a list of references to a file.
file_managed_file_save_upload

in drupal:11.5.0 and is removed from drupal:13.0.0. Use \Drupal::service(ManagedFileElementHelper::class)->managedFileSaveUpload() instead.

Saves any files that have been uploaded into a managed_file element.
file_save_upload

in drupal:11.5.0 and is removed from drupal:13.0.0. Use \Drupal::service(FormFileUploader::class)->saveFormUploadedFiles() instead.

Saves file uploads to a new location.
_file_save_upload_from_form

in drupal:11.5.0 and is removed from drupal:13.0.0. Use \Drupal::service(ManagedFileElementHelper::class)->saveFileUploads() instead.

Saves form file uploads.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.