FileUploadSecureValidator.php in File Upload Secure Validator 8
File
src/Service/FileUploadSecureValidator.php
View source
<?php
namespace Drupal\file_upload_secure_validator\Service;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\file\Entity\File;
use Symfony\Component\HttpFoundation\File\MimeType\FileinfoMimeTypeGuesser as SymfonyFileinfoMimeTypeGuesser;
class FileUploadSecureValidator {
protected $loggerChannelFactory;
protected $translator;
protected $configFactory;
public function __construct(LoggerChannelFactoryInterface $logger_factory, TranslationInterface $translator, ConfigFactoryInterface $config_factory) {
$this->loggerChannelFactory = $logger_factory;
$this->translator = $translator;
$this->configFactory = $config_factory;
}
public function validate(File $file) {
$mimeByFilename = $file
->getMimeType();
$mimeByFileinfo = (new SymfonyFileinfoMimeTypeGuesser())
->guess($file
->getFileUri());
if ($mimeByFilename === $mimeByFileinfo) {
return [];
}
$mimeTypesGroups = $this->configFactory
->get('file_upload_secure_validator.settings')
->get('mime_types_equivalence_groups');
foreach ($mimeTypesGroups as $mimeTypesGroup) {
if (empty(array_diff([
$mimeByFilename,
$mimeByFileinfo,
], $mimeTypesGroup))) {
return [];
}
}
$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 [
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),
];
}
}