Verified Commit 08c0efdf authored by Alex Pott's avatar Alex Pott
Browse files

Issue #3432882 by kim.pepper, Satane, andypost, alexpott, longwave: Removed...

Issue #3432882 by kim.pepper, Satane, andypost, alexpott, longwave: Removed deprecated code in File module (core/module/file)
parent fc0aa24e
Loading
Loading
Loading
Loading
Loading
+0 −5
Original line number Diff line number Diff line
@@ -826,11 +826,6 @@
	'count' => 1,
	'path' => __DIR__ . '/modules/file/file.module',
];
$ignoreErrors[] = [
	'message' => '#^Variable \\$message might not be defined\\.$#',
	'count' => 1,
	'path' => __DIR__ . '/modules/file/file.module',
];
$ignoreErrors[] = [
	'message' => '#^Variable \\$rows in empty\\(\\) always exists and is not falsy\\.$#',
	'count' => 1,
+1 −1
Original line number Diff line number Diff line
@@ -149,7 +149,7 @@ public function upload(Request $request): Response {

    try {
      $uploadedFile = new FormUploadedFile($upload);
      $uploadResult = $this->fileUploadHandler->handleFileUpload($uploadedFile, $validators, $destination, FileSystemInterface::EXISTS_RENAME, FALSE);
      $uploadResult = $this->fileUploadHandler->handleFileUpload($uploadedFile, $validators, $destination, FileSystemInterface::EXISTS_RENAME);
      if ($uploadResult->hasViolations()) {
        throw new UnprocessableEntityHttpException((string) $uploadResult->getViolations());
      }
+2 −2
Original line number Diff line number Diff line
@@ -27,8 +27,8 @@
 *   '#type' => 'file',
 *   '#title' => $this->t('Upload file'),
 *   '#upload_validators' => [
 *     'file_validate_extensions' => [
 *       'png gif jpg',
 *     'FileExtension' => [
 *       'extensions' => 'png gif jpg',
 *     ],
 *   ],
 * ];
+6 −368
Original line number Diff line number Diff line
@@ -68,289 +68,6 @@ function file_field_widget_info_alter(array &$info) {
  $info['uri']['field_types'][] = 'file_uri';
}

/**
 * Checks that a file meets the criteria specified by the validators.
 *
 * After executing the validator callbacks specified hook_file_validate() will
 * also be called to allow other modules to report errors about the file.
 *
 * @param \Drupal\file\FileInterface $file
 *   A file entity.
 * @param array $validators
 *   (optional) An associative array of callback functions used to validate
 *   the file. The keys are function names and the values arrays of callback
 *   parameters which will be passed in after the file entity. The functions
 *   should return an array of error messages; an empty array indicates that
 *   the file passed validation. The callback functions will be called in the
 *   order specified in the array, then the hook hook_file_validate()
 *   will be invoked so other modules can validate the new file.
 *
 * @return array
 *   An array containing validation error messages.
 *
 * @deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the
 *   'file.validator' service instead.
 *
 * @see https://www.drupal.org/node/3363700
 */
function file_validate(FileInterface $file, $validators = []) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the \'file.validator\' service instead. See https://www.drupal.org/node/3363700', E_USER_DEPRECATED);
  $violations = \Drupal::service('file.validator')->validate($file, $validators);
  $errors = [];
  foreach ($violations as $violation) {
    $errors[] = $violation->getMessage();
  }
  return $errors;
}

/**
 * Checks for files with names longer than can be stored in the database.
 *
 * @param \Drupal\file\FileInterface $file
 *   A file entity.
 *
 * @return array
 *   An empty array if the file name length is smaller than the limit or an
 *   array containing an error message if it's not or is empty.
 *
 * @deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the
 *   'file.validator' service instead.
 *
 * @see https://www.drupal.org/node/3363700
 */
function file_validate_name_length(FileInterface $file) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the \'file.validator\' service instead. See https://www.drupal.org/node/3363700', E_USER_DEPRECATED);
  $errors = [];

  if (!$file->getFilename()) {
    $errors[] = t("The file's name is empty. Enter a name for the file.");
  }
  if (strlen($file->getFilename()) > 240) {
    $errors[] = t("The file's name exceeds the 240 characters limit. Rename the file and try again.");
  }
  return $errors;
}

/**
 * Checks that the filename ends with an allowed extension.
 *
 * @param \Drupal\file\FileInterface $file
 *   A file entity.
 * @param string $extensions
 *   A string with a space separated list of allowed extensions.
 *
 * @return array
 *   An empty array if the file extension is allowed or an array containing an
 *   error message if it's not.
 *
 * @deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the
 *   'file.validator' service instead.
 *
 * @see https://www.drupal.org/node/3363700
 * @see hook_file_validate()
 */
function file_validate_extensions(FileInterface $file, $extensions) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the \'file.validator\' service instead. See https://www.drupal.org/node/3363700', E_USER_DEPRECATED);
  $errors = [];

  $regex = '/\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
  // Filename may differ from the basename, for instance in case files migrated
  // from D7 file entities. Because of that new files are saved temporarily with
  // a generated file name, without the original extension, we will use the
  // generated filename property for extension validation only in case of
  // temporary files; and use the file system file name in case of permanent
  // files.
  $subject = $file->isTemporary() ? $file->getFilename() : $file->getFileUri();
  if (!preg_match($regex, $subject)) {
    $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', ['%files-allowed' => $extensions]);
  }
  return $errors;
}

/**
 * Checks that the file's size is below certain limits.
 *
 * @param \Drupal\file\FileInterface $file
 *   A file entity.
 * @param int $file_limit
 *   (optional) The maximum file size in bytes. Zero (the default) indicates
 *   that no limit should be enforced.
 * @param int $user_limit
 *   (optional) The maximum number of bytes the user is allowed. Zero (the
 *   default) indicates that no limit should be enforced.
 *
 * @return array
 *   An empty array if the file size is below limits or an array containing an
 *   error message if it's not.
 *
 * @deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the
 *   'file.validator' service instead.
 *
 * @see https://www.drupal.org/node/3363700
 * @see hook_file_validate()
 */
function file_validate_size(FileInterface $file, $file_limit = 0, $user_limit = 0) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the \'file.validator\' service instead. See https://www.drupal.org/node/3363700', E_USER_DEPRECATED);
  $user = \Drupal::currentUser();
  $errors = [];

  if ($file_limit && $file->getSize() > $file_limit) {
    $errors[] = t('The file is %filesize exceeding the maximum file size of %maxsize.', [
      '%filesize' => ByteSizeMarkup::create($file->getSize()),
      '%maxsize' => ByteSizeMarkup::create($file_limit),
    ]);
  }

  // Save a query by only calling spaceUsed() when a limit is provided.
  if ($user_limit && (\Drupal::entityTypeManager()->getStorage('file')->spaceUsed($user->id()) + $file->getSize()) > $user_limit) {
    $errors[] = t('The file is %filesize which would exceed your disk quota of %quota.', [
      '%filesize' => ByteSizeMarkup::create($file->getSize()),
      '%quota' => ByteSizeMarkup::create($user_limit),
    ]);
  }

  return $errors;
}

/**
 * Checks that the file is recognized as a valid image.
 *
 * @param \Drupal\file\FileInterface $file
 *   A file entity.
 *
 * @return array
 *   An empty array if the file is a valid image or an array containing an error
 *   message if it's not.
 *
 * @deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the
 *   'file.validator' service instead.
 *
 * @see https://www.drupal.org/node/3363700
 * @see hook_file_validate()
 */
function file_validate_is_image(FileInterface $file) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the \'file.validator\' service instead. See https://www.drupal.org/node/3363700', E_USER_DEPRECATED);
  $errors = [];

  $image_factory = \Drupal::service('image.factory');
  $image = $image_factory->get($file->getFileUri());
  if (!$image->isValid()) {
    $supported_extensions = $image_factory->getSupportedExtensions();
    $errors[] = t('The image file is invalid or the image type is not allowed. Allowed types: %types', ['%types' => implode(', ', $supported_extensions)]);
  }

  return $errors;
}

/**
 * Verifies that image dimensions are within the specified maximum and minimum.
 *
 * Non-image files will be ignored. If an image toolkit is available the image
 * will be scaled to fit within the desired maximum dimensions.
 *
 * @param \Drupal\file\FileInterface $file
 *   A file entity. This function may resize the file affecting its size.
 * @param string|int $maximum_dimensions
 *   (optional) A string in the form WIDTHxHEIGHT; for example, '640x480' or
 *   '85x85'. If an image toolkit is installed, the image will be resized down
 *   to these dimensions. A value of zero (the default) indicates no restriction
 *   on size, so no resizing will be attempted.
 * @param string|int $minimum_dimensions
 *   (optional) A string in the form WIDTHxHEIGHT. This will check that the
 *   image meets a minimum size. A value of zero (the default) indicates that
 *   there is no restriction on size.
 *
 * @return array
 *   An empty array if the file meets the specified dimensions, was resized
 *   successfully to meet those requirements or is not an image. If the image
 *   does not meet the requirements or an attempt to resize it fails, an array
 *   containing the error message will be returned.
 *
 * @deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the
 *   'file.validator' service instead.
 *
 * @see https://www.drupal.org/node/3363700
 * @see hook_file_validate()
 */
function file_validate_image_resolution(FileInterface $file, $maximum_dimensions = 0, $minimum_dimensions = 0) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the \'file.validator\' service instead. See https://www.drupal.org/node/3363700', E_USER_DEPRECATED);
  $errors = [];

  // Check first that the file is an image.
  $image_factory = \Drupal::service('image.factory');
  $image = $image_factory->get($file->getFileUri());

  if ($image->isValid()) {
    $scaling = FALSE;
    if ($maximum_dimensions) {
      // Check that it is smaller than the given dimensions.
      [$width, $height] = explode('x', $maximum_dimensions);
      if ($image->getWidth() > $width || $image->getHeight() > $height) {
        // Try to resize the image to fit the dimensions.
        if ($image->scale($width, $height)) {
          $scaling = TRUE;
          $image->save();
          // Update the file size now that the image has been resized.
          $file->setSize($image->getFileSize());
          if (!empty($width) && !empty($height)) {
            $message = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels. The new dimensions of the resized image are %new_widthx%new_height pixels.',
              [
                '%dimensions' => $maximum_dimensions,
                '%new_width' => $image->getWidth(),
                '%new_height' => $image->getHeight(),
              ]);
          }
          elseif (empty($width)) {
            $message = t('The image was resized to fit within the maximum allowed height of %height pixels. The new dimensions of the resized image are %new_widthx%new_height pixels.',
              [
                '%height' => $height,
                '%new_width' => $image->getWidth(),
                '%new_height' => $image->getHeight(),
              ]);
          }
          elseif (empty($height)) {
            $message = t('The image was resized to fit within the maximum allowed width of %width pixels. The new dimensions of the resized image are %new_widthx%new_height pixels.',
              [
                '%width' => $width,
                '%new_width' => $image->getWidth(),
                '%new_height' => $image->getHeight(),
              ]);
          }
          \Drupal::messenger()->addStatus($message);
        }
        else {
          $errors[] = t('The image exceeds the maximum allowed dimensions and an attempt to resize it failed.');
        }
      }
    }

    if ($minimum_dimensions) {
      // Check that it is larger than the given dimensions.
      [$width, $height] = explode('x', $minimum_dimensions);
      if ($image->getWidth() < $width || $image->getHeight() < $height) {
        if ($scaling) {
          $errors[] = t('The resized image is too small. The minimum dimensions are %dimensions pixels and after resizing, the image size will be %widthx%height pixels.',
            [
              '%dimensions' => $minimum_dimensions,
              '%width' => $image->getWidth(),
              '%height' => $image->getHeight(),
            ]);
        }
        else {
          $errors[] = t('The image is too small. The minimum dimensions are %dimensions pixels and the image size is %widthx%height pixels.',
            [
              '%dimensions' => $minimum_dimensions,
              '%width' => $image->getWidth(),
              '%height' => $image->getHeight(),
            ]);
        }
      }
    }
  }

  return $errors;
}

/**
 * Examines a file entity and returns appropriate content headers for download.
 *
@@ -589,7 +306,7 @@ function _file_save_upload_from_form(array $element, FormStateInterface $form_st
 *   If the array is empty, it will be set up to call file_validate_extensions()
 *   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 ['file_validate_extensions' => '']. (Beware: this is not
 *   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.
@@ -661,7 +378,7 @@ function file_save_upload($form_field_name, $validators = [], $destination = FAL
        continue;
      }
      $form_uploaded_file = new FormUploadedFile($uploaded_file);
      $result = $file_upload_handler->handleFileUpload($form_uploaded_file, $validators, $destination, $replace, FALSE);
      $result = $file_upload_handler->handleFileUpload($form_uploaded_file, $validators, $destination, $replace);
      if ($result->hasViolations()) {
        $errors = [];
        foreach ($result->getViolations() as $violation) {
@@ -725,33 +442,6 @@ function file_save_upload($form_field_name, $validators = [], $destination = FAL
  return isset($delta) ? $files[$delta] : $files;
}

/**
 * Determines the preferred upload progress implementation.
 *
 * @return string|false
 *   A string indicating which upload progress system is available. Either "apc"
 *   or "uploadprogress". If neither are available, returns FALSE.
 *
 * @deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. Use
 *    extension_loaded('uploadprogress') instead.
 *
 * @see https://www.drupal.org/node/3397577
 */
function file_progress_implementation() {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. Use extension_loaded(\'uploadprogress\') instead. See https://www.drupal.org/node/3397577', E_USER_DEPRECATED);
  static $implementation;
  if (!isset($implementation)) {
    $implementation = FALSE;

    // We prefer the PECL extension uploadprogress because it supports multiple
    // simultaneous uploads. APCu only supports one at a time.
    if (extension_loaded('uploadprogress')) {
      $implementation = 'uploadprogress';
    }
  }
  return $implementation;
}

/**
 * Implements hook_ENTITY_TYPE_predelete() for file entities.
 */
@@ -1239,32 +929,18 @@ function template_preprocess_file_upload_help(&$variables) {
      $descriptions[] = \Drupal::translation()->formatPlural($cardinality, 'One file only.', 'Maximum @count files.');
    }
  }
  if (isset($upload_validators['file_validate_size'])) {
    @trigger_error('\'file_validate_size\' is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the \'FileSizeLimit\' constraint instead. See https://www.drupal.org/node/3363700', E_USER_DEPRECATED);
    $descriptions[] = t('@size limit.', ['@size' => ByteSizeMarkup::create($upload_validators['file_validate_size'][0])]);
  }

  if (isset($upload_validators['FileSizeLimit'])) {
    $descriptions[] = t('@size limit.', ['@size' => ByteSizeMarkup::create($upload_validators['FileSizeLimit']['fileLimit'])]);
  }

  if (isset($upload_validators['file_validate_extensions'])) {
    @trigger_error('\'file_validate_extensions\' is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the \'FileExtension\' constraint instead. See https://www.drupal.org/node/3363700', E_USER_DEPRECATED);
    $descriptions[] = t('Allowed types: @extensions.', ['@extensions' => $upload_validators['file_validate_extensions'][0]]);
  }
  if (isset($upload_validators['FileExtension'])) {
    $descriptions[] = t('Allowed types: @extensions.', ['@extensions' => $upload_validators['FileExtension']['extensions']]);
  }

  if (isset($upload_validators['file_validate_image_resolution']) || isset($upload_validators['FileImageDimensions'])) {
    if (isset($upload_validators['file_validate_image_resolution'])) {
      @trigger_error('\'file_validate_image_resolution\' is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the \'FileImageDimensions\' constraint instead. See https://www.drupal.org/node/3363700', E_USER_DEPRECATED);
      $max = $upload_validators['file_validate_image_resolution'][0];
      $min = $upload_validators['file_validate_image_resolution'][1];
    }
    else {
  if (isset($upload_validators['FileImageDimensions'])) {
    $max = $upload_validators['FileImageDimensions']['maxDimensions'];
    $min = $upload_validators['FileImageDimensions']['minDimensions'];
    }
    if ($min && $max && $min == $max) {
      $descriptions[] = t('Images must be exactly <strong>@size</strong> pixels.', ['@size' => $max]);
    }
@@ -1285,44 +961,6 @@ function template_preprocess_file_upload_help(&$variables) {
  $variables['descriptions'] = $descriptions;
}

/**
 * Gets a class for the icon for a MIME type.
 *
 * @param string $mime_type
 *   A MIME type.
 *
 * @return string
 *   A class associated with the file.
 *
 * @deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. Use
 *   \Drupal\file\IconMimeTypes::getIconClass() instead.
 *
 * @see https://www.drupal.org/node/3411269
 */
function file_icon_class($mime_type) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. Use \Drupal\file\IconMimeTypes::getIconClass() instead. See https://www.drupal.org/node/3411269', E_USER_DEPRECATED);
  return IconMimeTypes::getIconClass($mime_type);
}

/**
 * Determines the generic icon MIME package based on a file's MIME type.
 *
 * @param string $mime_type
 *   A MIME type.
 *
 * @return string|false
 *   The generic icon MIME package expected for this file.
 *
 *  @deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. Use
 *    \Drupal\file\IconMimeTypes::getGenericMimeType() instead.
 *
 * @see https://www.drupal.org/node/3411269
 */
function file_icon_map($mime_type) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. Use \Drupal\file\IconMimeTypes::getGenericMimeType() instead. See https://www.drupal.org/node/3411269', E_USER_DEPRECATED);
  return IconMimeTypes::getGenericMimeType($mime_type);
}

/**
 * Retrieves a list of references to a file.
 *
+2 −8
Original line number Diff line number Diff line
@@ -358,14 +358,8 @@ public static function processManagedFile(&$element, FormStateInterface $form_st
    }

    // Add the extension list to the page as JavaScript settings.
    if (isset($element['#upload_validators']['file_validate_extensions'][0]) || isset($element['#upload_validators']['FileExtension']['extensions'])) {
      if (isset($element['#upload_validators']['file_validate_extensions'][0])) {
        @trigger_error('\'file_validate_extensions\' is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the \'FileExtension\' constraint instead. See https://www.drupal.org/node/3363700', E_USER_DEPRECATED);
        $allowed_extensions = $element['#upload_validators']['file_validate_extensions'][0];
      }
      else {
    if (isset($element['#upload_validators']['FileExtension']['extensions'])) {
      $allowed_extensions = $element['#upload_validators']['FileExtension']['extensions'];
      }
      $extension_list = implode(',', array_filter(explode(' ', $allowed_extensions)));
      $element['upload']['#attached']['drupalSettings']['file']['elements']['#' . $id] = $extension_list;
    }
Loading