From fb493cc837579149aca116b2d08eebc1922b4cf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20B=C3=B6hmer?= Date: Mon, 29 Jan 2024 21:25:30 +0100 Subject: [PATCH] Fixed export of entities, if their name contained slash or other reserved charcters --- src/Helpers/FilenameSanatizer.php | 56 +++++++++++++++++++ .../ImportExportSystem/EntityExporter.php | 4 ++ 2 files changed, 60 insertions(+) create mode 100644 src/Helpers/FilenameSanatizer.php diff --git a/src/Helpers/FilenameSanatizer.php b/src/Helpers/FilenameSanatizer.php new file mode 100644 index 00000000..1c7b18d9 --- /dev/null +++ b/src/Helpers/FilenameSanatizer.php @@ -0,0 +1,56 @@ +. + */ + +declare(strict_types=1); + + +namespace App\Helpers; + +/** + * This class provides functions to sanitize filenames. + */ +class FilenameSanatizer +{ + /** + * Converts a given filename to a version, which is guaranteed to be safe to use on all filesystems. + * This function is adapted from https://stackoverflow.com/a/42058764/21879970 + * @param string $filename + * @return string + */ + public static function sanitizeFilename(string $filename): string + { + $filename = preg_replace( + '~ + [<>:"/\\\|?*]| # file system reserved https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words + [\x00-\x1F]| # control characters http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx + [\x7F\xA0\xAD]| # non-printing characters DEL, NO-BREAK SPACE, SOFT HYPHEN + [#\[\]@!$&\'()+,;=]| # URI reserved https://www.rfc-editor.org/rfc/rfc3986#section-2.2 + [{}^\~`] # URL unsafe characters https://www.ietf.org/rfc/rfc1738.txt + ~x', + '-', $filename); + + // avoids ".", ".." or ".hiddenFiles" + $filename = ltrim($filename, '.-'); + //Limit filename length to 255 bytes + $ext = pathinfo($filename, PATHINFO_EXTENSION); + $filename = mb_strcut(pathinfo($filename, PATHINFO_FILENAME), 0, 255 - ($ext ? strlen($ext) + 1 : 0), mb_detect_encoding($filename)) . ($ext ? '.' . $ext : ''); + return $filename; + } +} \ No newline at end of file diff --git a/src/Services/ImportExportSystem/EntityExporter.php b/src/Services/ImportExportSystem/EntityExporter.php index c99a3672..2619c975 100644 --- a/src/Services/ImportExportSystem/EntityExporter.php +++ b/src/Services/ImportExportSystem/EntityExporter.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace App\Services\ImportExportSystem; use App\Entity\Base\AbstractNamedDBElement; +use App\Helpers\FilenameSanatizer; use Symfony\Component\OptionsResolver\OptionsResolver; use InvalidArgumentException; use function is_array; @@ -166,6 +167,9 @@ class EntityExporter $filename = 'export_'.$entity_name.'_'.$level.'.'.$format; + //Sanitize the filename + $filename = FilenameSanatizer::sanitizeFilename($filename); + // Create the disposition of the file $disposition = $response->headers->makeDisposition( ResponseHeaderBag::DISPOSITION_ATTACHMENT,