You are here

public function FileUploadSecureValidator::validate in File Upload Secure Validator 8

File validation function.

Parameters

\Drupal\file\Entity\File $file: The file to be uploaded.

File

src/Service/FileUploadSecureValidator.php, line 64

Class

FileUploadSecureValidator
A service class for fileinfo-based validation.

Namespace

Drupal\file_upload_secure_validator\Service

Code

public function validate(File $file) {

  // Get mime type from filename.
  $mimeByFilename = $file
    ->getMimeType();

  // Get mime type from fileinfo.
  $mimeByFileinfo = (new SymfonyFileinfoMimeTypeGuesser())
    ->guess($file
    ->getFileUri());

  // Early exit, fileinfo agrees with the file's extension.
  if ($mimeByFilename === $mimeByFileinfo) {
    return [];
  }

  // Check against known MIME types equivalence groups.
  $mimeTypesGroups = $this->configFactory
    ->get('file_upload_secure_validator.settings')
    ->get('mime_types_equivalence_groups');

  // Exit when a mime-type equivalence pairing is found.
  foreach ($mimeTypesGroups as $mimeTypesGroup) {
    if (empty(array_diff([
      $mimeByFilename,
      $mimeByFileinfo,
    ], $mimeTypesGroup))) {
      return [];
    }
  }

  // Log disagreement.
  $this->loggerChannelFactory
    ->get('file_upload_secure_validator')
    ->error("Error while uploading file: MimeTypeGuesser guessed '%mime_by_fileinfo' and fileinfo '%mime_by_filename'", [
    '%mime_by_fileinfo' => $mimeByFileinfo,
    '%mime_by_filename' => $mimeByFilename,
  ]);

  // Return error.
  return [
    new TranslatableMarkup('There was a problem with this file. The uploaded file is of type @extension but the real content seems to be @real_extension', [
      '@extension' => $mimeByFilename,
      '@real_extension' => $mimeByFileinfo,
    ], [], $this->translator),
  ];
}