From 3100af07a782205a0b0f1f0376a147415b8df4d3 Mon Sep 17 00:00:00 2001 From: mjansen Date: Fri, 9 Aug 2024 14:53:18 +0200 Subject: [PATCH] Mail: Cleanup old files from attachment stage (for anonymous user) (cherry picked from commit 04f9348242bfa637632707e28d8e45682c8f67ec) --- .../ILIAS/Mail/classes/class.ilMail.php | 10 +++ .../class.ilMailAttachmentStageCleanup.php | 71 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 components/ILIAS/Mail/classes/class.ilMailAttachmentStageCleanup.php diff --git a/components/ILIAS/Mail/classes/class.ilMail.php b/components/ILIAS/Mail/classes/class.ilMail.php index 0d16329b1e1c..f4ba6273a60a 100755 --- a/components/ILIAS/Mail/classes/class.ilMail.php +++ b/components/ILIAS/Mail/classes/class.ilMail.php @@ -1141,6 +1141,16 @@ public function sendMail( $this->deleteMails([$internalMessageId]); } + if ($this->isSystemMail()) { + $random = new ilRandom(); + if ($random->int(0, 50) === 2) { + (new ilMailAttachmentStageCleanup( + $this->logger, + $this->mfile + ))->run(); + } + } + return array_values($errors); } diff --git a/components/ILIAS/Mail/classes/class.ilMailAttachmentStageCleanup.php b/components/ILIAS/Mail/classes/class.ilMailAttachmentStageCleanup.php new file mode 100644 index 000000000000..80a11eb7645e --- /dev/null +++ b/components/ILIAS/Mail/classes/class.ilMailAttachmentStageCleanup.php @@ -0,0 +1,71 @@ +logger = $logger; + $this->mail_file_manager = $mail_file_manager; + } + + public function run(): void + { + $right_interval = (new DateTimeImmutable(self::OLD_FILE_MTIME_EXPRESSION))->format('U'); + + $iter = new CallbackFilterIterator( + new RegexIterator( + new DirectoryIterator($this->mail_file_manager->getMailPath()), + '/^' . $this->mail_file_manager->user_id . '_/' + ), + function (SplFileInfo $file) use ($right_interval): bool { + if (!$file->isFile()) { + return false; + } + + return (int) $file->getMTime() < (int) $right_interval; + } + ); + + $filesystem = \ILIAS\Filesystem\Util\LegacyPathHelper::deriveFilesystemFrom( + $this->mail_file_manager->getMailPath() + ); + + foreach ($iter as $file) { + /** @var SplFileInfo $file */ + if (strpos($file->getFilename(), $this->mail_file_manager->user_id . '_') === 0) { + try { + $relative_path = 'mail/' . $file->getFilename(); + if ($filesystem->has($relative_path)) { + $filesystem->delete($relative_path); + $this->logger->info('Deleting file from attachment stage: ' . $file->getPath()); + } + } catch (Exception $e) { + $this->logger->error('Error deleting file from attachment stage: ' . $file->getPath()); + } + } + } + } +}