ILIAS  trunk Revision v12.0_alpha-377-g3641b37b9db
class.ilFileDataMail.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
23
25{
26 public string $mail_path;
30 protected ilDBInterface $db;
31 protected ILIAS $ilias;
32
33 public function __construct(public int $user_id = 0)
34 {
35 global $DIC;
36
37 if (!defined('MAILPATH')) {
38 define('MAILPATH', 'mail');
39 }
41 $this->mail_path = $this->getPath() . '/' . MAILPATH;
42 $this->ilias = $DIC['ilias'];
43 $this->db = $DIC->database();
44 $this->tmp_directory = $DIC->filesystem()->temp();
45 $this->storage_directory = $DIC->filesystem()->storage();
46
47 $this->checkReadWrite();
49 }
50
51 public function initDirectory(): bool
52 {
53 if (is_writable($this->getPath())
54 && mkdir($this->getPath() . '/' . MAILPATH)
55 && chmod($this->getPath() . '/' . MAILPATH, 0755)) {
56 $this->mail_path = $this->getPath() . '/' . MAILPATH;
57 return true;
58 }
59
60 return false;
61 }
62
63 public function getUploadLimit(): int
64 {
66 }
67
68 public function getAttachmentsTotalSizeLimit(): ?float
69 {
70 $max_size = $this->ilias->getSetting('mail_maxsize_attach', '');
71 if ($max_size === '') {
72 return null;
73 }
74
75 return (float) $this->ilias->getSetting('mail_maxsize_attach', '0') * 1024;
76 }
77
78 public function getMailPath(): string
79 {
80 return $this->mail_path;
81 }
82
83 public function getAbsoluteAttachmentPoolPathPrefix(): string
84 {
85 return $this->mail_path . '/' . $this->user_id . '_';
86 }
87
92 public function getAttachmentPathAndFilenameByMd5Hash(string $md5FileHash, int $mail_id): array
93 {
94 $res = $this->db->queryF(
95 'SELECT path FROM mail_attachment WHERE mail_id = %s',
96 ['integer'],
97 [$mail_id]
98 );
99
100 if ($this->db->numRows($res) !== 1) {
101 throw new OutOfBoundsException();
102 }
103
104 $row = $this->db->fetchAssoc($res);
105
106 $relative_path = $row['path'];
107 $path = $this->getMailPath() . '/' . $row['path'];
108
109 $files = ilFileUtils::getDir($path);
110 foreach ($files as $file) {
111 if ($file['type'] === 'file' && md5($file['entry']) === $md5FileHash) {
112 return [
113 'path' => $this->getMailPath() . '/' . $relative_path . '/' . $file['entry'],
114 'filename' => $file['entry'],
115 ];
116 }
117 }
118
119 throw new OutOfBoundsException();
120 }
121
122
123 private function getAttachmentPathByMailId(int $mail_id): string
124 {
125 $query = $this->db->query(
126 'SELECT path FROM mail_attachment WHERE mail_id = ' . $this->db->quote($mail_id, 'integer')
127 );
128
129 while ($row = $this->db->fetchObject($query)) {
130 return $row->path;
131 }
132
133 return '';
134 }
135
136 public function getAttachmentPath(string $a_filename, int $a_mail_id): string
137 {
138 $path = $this->getMailPath() . '/' . $this->getAttachmentPathByMailId($a_mail_id) . '/' . $a_filename;
139
140 if (is_readable($path)) {
141 return $path;
142 }
143
144 return '';
145 }
146
150 public function adoptAttachments(array $a_attachments, int $a_mail_id): string
151 {
152 foreach ($a_attachments as $file) {
153 $path = $this->getAttachmentPath($file, $a_mail_id);
154 if (!copy($path, $this->getMailPath() . '/' . $this->user_id . '_' . $file)) {
155 return 'ERROR: ' . $this->getMailPath() . '/' . $this->user_id . '_' . $file . ' cannot be created';
156 }
157 }
158
159 return '';
160 }
161
162 public function checkReadWrite(): bool
163 {
164 if (is_writable($this->mail_path) && is_readable($this->mail_path)) {
165 return true;
166 }
167
168 $this->ilias->raiseError(
169 'Mail directory is not readable/writable by webserver: ' .
170 $this->mail_path,
171 $this->ilias->error_obj->FATAL
172 );
173
174 return false;
175 }
176
180 public function getUserFilesData(): array
181 {
182 return $this->getUnsentFiles();
183 }
184
188 private function getUnsentFiles(): array
189 {
190 $files = [];
191
192 $iter = new RegexIterator(new DirectoryIterator($this->mail_path), "/^{$this->user_id}_(.+)$/");
193 foreach ($iter as $file) {
195 if (!$file->isFile()) {
196 continue;
197 }
198
199 [$uid, $rest] = explode('_', $file->getFilename(), 2);
200 if ($uid === (string) $this->user_id) {
201 $files[] = [
202 'name' => $rest,
203 'size' => $file->getSize(),
204 'ctime' => $file->getCTime(),
205 ];
206 }
207 }
208
209 return $files;
210 }
211
212 public function storeAsAttachment(string $a_filename, string $a_content): string
213 {
214 if (strlen($a_content) >= $this->getUploadLimit()) {
215 throw new DomainException(
216 sprintf(
217 'Mail upload limit reached for user with id %s',
218 $this->user_id
219 )
220 );
221 }
222
223 $name = ilFileUtils::_sanitizeFilemame($a_filename);
224 $this->rotateFiles($this->getMailPath() . '/' . $this->user_id . '_' . $name);
225
226 $abs_path = $this->getMailPath() . '/' . $this->user_id . '_' . $name;
227
228 $fp = fopen($abs_path, 'wb+');
229 if (!is_resource($fp)) {
230 throw new RuntimeException(
231 sprintf(
232 'Could not read file: %s',
233 $abs_path
234 )
235 );
236 }
237
238 if (fwrite($fp, $a_content) === false) {
239 fclose($fp);
240 throw new RuntimeException(
241 sprintf(
242 'Could not write file: %s',
243 $abs_path
244 )
245 );
246 }
247
248 fclose($fp);
249
250 return $name;
251 }
252
256 public function storeUploadedFile(array $file): string
257 {
258 $file['name'] = ilFileUtils::_sanitizeFilemame($file['name']);
259
260 $this->rotateFiles($this->getMailPath() . '/' . $this->user_id . '_' . $file['name']);
261
263 $file['tmp_name'],
264 $file['name'],
265 $this->getMailPath() . '/' . $this->user_id . '_' . $file['name']
266 );
267
268 return $file['name'];
269 }
270
271 public function copyAttachmentFile(string $a_abs_path, string $a_new_name): bool
272 {
273 @copy($a_abs_path, $this->getMailPath() . '/' . $this->user_id . '_' . $a_new_name);
274
275 return true;
276 }
277
278 private function rotateFiles(string $a_path): bool
279 {
280 if (is_file($a_path)) {
281 $this->rotateFiles($a_path . '.old');
282 return ilFileUtils::rename($a_path, $a_path . '.old');
283 }
284
285 return true;
286 }
287
291 public function unlinkFiles(array $a_filenames): string
292 {
293 foreach ($a_filenames as $file) {
294 if (!$this->unlinkFile($file)) {
295 return $file;
296 }
297 }
298
299 return '';
300 }
301
302 public function unlinkFile(string $a_filename): bool
303 {
304 if (is_file($this->mail_path . '/' . basename($this->user_id . '_' . $a_filename))) {
305 return unlink($this->mail_path . '/' . basename($this->user_id . '_' . $a_filename));
306 }
307
308 return false;
309 }
310
316 {
318 }
319
324 public function saveFiles(int $a_mail_id, array $a_attachments): void
325 {
326 if (!is_numeric($a_mail_id) || $a_mail_id < 1) {
327 throw new InvalidArgumentException('The passed mail_id must be a valid integer!');
328 }
329
330 foreach ($a_attachments as $attachment) {
331 $this->saveFile($a_mail_id, $attachment);
332 }
333 }
334
335 public static function getStorage(int $a_mail_id, int $a_usr_id): ilFSStorageMail
336 {
337 static $fsstorage_cache = [];
338
339 $fsstorage_cache[$a_mail_id][$a_usr_id] = new ilFSStorageMail($a_mail_id, $a_usr_id);
340
341 return $fsstorage_cache[$a_mail_id][$a_usr_id];
342 }
343
347 public function saveFile(int $a_mail_id, string $a_attachment): bool
348 {
349 $storage = self::getStorage($a_mail_id, $this->user_id);
350 $storage->create();
351 $storage_directory = $storage->getAbsolutePath();
352
353 if (!is_dir($storage_directory)) {
354 return false;
355 }
356
357 return copy(
358 $this->mail_path . '/' . $this->user_id . '_' . $a_attachment,
359 $storage_directory . '/' . $a_attachment
360 );
361 }
362
366 public function checkFilesExist(array $a_files): bool
367 {
368 if ($a_files !== []) {
369 foreach ($a_files as $file) {
370 if (!is_file($this->mail_path . '/' . $this->user_id . '_' . $file)) {
371 return false;
372 }
373 }
374 }
375
376 return true;
377 }
378
379 public function assignAttachmentsToDirectory(int $a_mail_id, int $a_sent_mail_id): void
380 {
381 $storage = self::getStorage($a_sent_mail_id, $this->user_id);
382 $this->db->manipulateF(
383 '
384 INSERT INTO mail_attachment
385 ( mail_id, path) VALUES (%s, %s)',
386 ['integer', 'text'],
387 [$a_mail_id, $storage->getRelativePathExMailDirectory()]
388 );
389 }
390
391 public function deassignAttachmentFromDirectory(int $a_mail_id): bool
392 {
393 $res = $this->db->query(
394 'SELECT path FROM mail_attachment WHERE mail_id = ' . $this->db->quote($a_mail_id, 'integer')
395 );
396
397 $path = '';
398 while ($row = $this->db->fetchObject($res)) {
399 $path = (string) $row->path;
400 }
401
402 if ($path !== '') {
403 $res = $this->db->query(
404 'SELECT COUNT(mail_id) count_mail_id FROM mail_attachment WHERE path = ' .
405 $this->db->quote($path, 'text')
406 ) ;
407
408 $cnt_mail_id = 0;
409 while ($row = $this->db->fetchObject($res)) {
410 $cnt_mail_id = (int) $row->count_mail_id;
411 }
412
413 if ($cnt_mail_id === 1) {
415 }
416 }
417
418 $this->db->manipulateF(
419 'DELETE FROM mail_attachment WHERE mail_id = %s',
420 ['integer'],
421 [$a_mail_id]
422 );
423
424 return true;
425 }
426
427 private function deleteAttachmentDirectory(string $a_rel_path): void
428 {
429 ilFileUtils::delDir($this->mail_path . '/' . $a_rel_path);
430 }
431
432 protected function initAttachmentMaxUploadSize(): void
433 {
436 // Copy of ilFileInputGUI: begin
437 // get the value for the maximal uploadable filesize from the php.ini (if available)
438 $umf = ini_get('upload_max_filesize');
439 // get the value for the maximal post data from the php.ini (if available)
440 $pms = ini_get('post_max_size');
441
442 //convert from short-string representation to "real" bytes
443 $multiplier_a = ['K' => 1024, 'M' => 1024 * 1024, 'G' => 1024 * 1024 * 1024];
444
445 $umf_parts = preg_split(
446 "/(\d+)([K|G|M])/",
447 (string) $umf,
448 -1,
449 PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
450 );
451 $pms_parts = preg_split(
452 "/(\d+)([K|G|M])/",
453 (string) $pms,
454 -1,
455 PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
456 );
457
458 if ((is_countable($umf_parts) ? count($umf_parts) : 0) === 2) {
459 $umf = (float) $umf_parts[0] * $multiplier_a[$umf_parts[1]];
460 }
461 if ((is_countable($pms_parts) ? count($pms_parts) : 0) === 2) {
462 $pms = (float) $pms_parts[0] * $multiplier_a[$pms_parts[1]];
463 }
464
465 // use the smaller one as limit
466 $max_filesize = min($umf, $pms);
467
468 if (!$max_filesize) {
469 $max_filesize = max($umf, $pms);
470 }
471
472 $this->mail_max_upload_file_size = (int) $max_filesize;
473 }
474
475 public function onUserDelete(): void
476 {
477 // Delete uploaded mail files which are not attached to any message
478 try {
479 $iter = new RegexIterator(
480 new DirectoryIterator($this->getMailPath()),
481 '/^' . $this->user_id . '_/'
482 );
483 foreach ($iter as $file) {
485 if ($file->isFile()) {
486 @unlink($file->getPathname());
487 }
488 }
489 } catch (Exception) {
490 }
491
492 // Select all files attached to messages which are not shared (... = 1) with other messages anymore
493 $query = '
494 SELECT DISTINCT(ma1.path)
495 FROM mail_attachment ma1
496 INNER JOIN mail
497 ON mail.mail_id = ma1.mail_id
498 WHERE mail.user_id = %s
499 AND (SELECT COUNT(tmp.path) FROM mail_attachment tmp WHERE tmp.path = ma1.path) = 1
500 ';
501 $res = $this->db->queryF(
502 $query,
503 ['integer'],
504 [$this->user_id]
505 );
506 while ($row = $this->db->fetchAssoc($res)) {
507 try {
508 $path = $this->getMailPath() . DIRECTORY_SEPARATOR . $row['path'];
509 $iter = new RecursiveIteratorIterator(
510 new RecursiveDirectoryIterator($path),
511 RecursiveIteratorIterator::CHILD_FIRST
512 );
513 foreach ($iter as $file) {
515 if ($file->isDir()) {
516 @rmdir($file->getPathname());
517 } else {
518 @unlink($file->getPathname());
519 }
520 }
521 @rmdir($path);
522 } catch (Exception) {
523 }
524 }
525
526 // Delete each mail attachment rows assigned to a message of the deleted user.
527 $this->db->manipulateF(
528 '
529 DELETE
530 FROM mail_attachment
531 WHERE EXISTS(
532 SELECT mail.mail_id
533 FROM mail
534 WHERE mail.user_id = %s AND mail.mail_id = mail_attachment.mail_id
535 )
536 ',
537 ['integer'],
538 [$this->user_id]
539 );
540 }
541
545 public function deliverAttachmentsAsZip(
546 string $basename,
547 int $mail_id,
548 array $files = [],
549 bool $is_draft = false
550 ): void {
551 $path = '';
552 if (!$is_draft) {
553 $path = $this->getAttachmentPathByMailId($mail_id);
554 if ($path === '') {
555 throw new ilMailException('mail_download_zip_no_attachments');
556 }
557 }
558
559 $download_filename = ilFileUtils::getASCIIFilename($basename);
560 if ($download_filename === '') {
561 $download_filename = 'attachments';
562 }
563
564 $processing_directory = ilFileUtils::ilTempnam();
565 $relative_processing_directory = basename($processing_directory);
566
567 $absolute_zip_directory = $processing_directory . '/' . $download_filename;
568 $relative_zip_directory = $relative_processing_directory . '/' . $download_filename;
569
570 $this->tmp_directory->createDir($relative_zip_directory);
571
572 foreach ($files as $filename) {
573 if ($is_draft) {
574 $source = str_replace(
575 $this->mail_path,
576 MAILPATH,
578 );
579 } else {
580 $source = MAILPATH . '/' . $path . '/' . $filename;
581 }
582
583 $source = str_replace('//', '/', $source);
584 if (!$this->storage_directory->has($source)) {
585 continue;
586 }
587
588 $target = $relative_zip_directory . '/' . $filename;
589
590 $stream = $this->storage_directory->readStream($source);
591 $this->tmp_directory->writeStream($target, $stream);
592 }
593
594 $path_to_zip_file = $processing_directory . '/' . $download_filename . '.zip';
595 ilFileUtils::zip($absolute_zip_directory, $path_to_zip_file);
596
597 $this->tmp_directory->deleteDir($relative_zip_directory);
598
600 $processing_directory . '/' . $download_filename . '.zip',
601 ilFileUtils::getValidFilename($download_filename . '.zip')
602 );
603 }
604}
$filename
Definition: buildRTE.php:78
deleteAttachmentDirectory(string $a_rel_path)
__construct(public int $user_id=0)
unlinkFiles(array $a_filenames)
static getStorage(int $a_mail_id, int $a_usr_id)
getAttachmentPath(string $a_filename, int $a_mail_id)
storeUploadedFile(array $file)
Filesystem $storage_directory
saveFile(int $a_mail_id, string $a_attachment)
Save attachment file in a specific mail directory .../mail/<calculated_path>/mail_<mail_id>_<user_id>...
checkFilesExist(array $a_files)
unlinkFile(string $a_filename)
assignAttachmentsToDirectory(int $a_mail_id, int $a_sent_mail_id)
saveFiles(int $a_mail_id, array $a_attachments)
Saves all attachment files in a specific mail directory .../mail/<calculated_path>/mail_<mail_id>_<us...
getAttachmentPathByMailId(int $mail_id)
deassignAttachmentFromDirectory(int $a_mail_id)
deliverAttachmentsAsZip(string $basename, int $mail_id, array $files=[], bool $is_draft=false)
copyAttachmentFile(string $a_abs_path, string $a_new_name)
adoptAttachments(array $a_attachments, int $a_mail_id)
getAbsoluteAttachmentPoolPathByFilename(string $filename)
Resolves a path for a passed filename in regards of a user's mail attachment pool,...
storeAsAttachment(string $a_filename, string $a_content)
getAttachmentPathAndFilenameByMd5Hash(string $md5FileHash, int $mail_id)
rotateFiles(string $a_path)
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
static deliverFileAttached(string $path_to_file, ?string $download_file_name=null, ?string $mime_type=null, bool $delete_file=false)
static getASCIIFilename(string $a_filename)
static getDir(string $a_dir, bool $a_rec=false, ?string $a_sub_dir="")
get directory
static zip(string $a_dir, string $a_file, bool $compress_content=false)
static ilTempnam(?string $a_temp_path=null)
Returns a unique and non existing Path for e temporary file or directory.
static rename(string $a_source, string $a_target)
static delDir(string $a_dir, bool $a_clean_only=false)
removes a dir and all its content (subdirs and files) recursively
static getValidFilename(string $a_filename)
static _sanitizeFilemame(string $a_filename)
static moveUploadedFile(string $a_file, string $a_name, string $a_target, bool $a_raise_errors=true, string $a_mode="move_uploaded")
move uploaded file
string $path
const MAILPATH
Definition: constants.php:50
The filesystem interface provides the public interface for the Filesystem service API consumer.
Definition: Filesystem.php:37
Interface ilDBInterface.
$res
Definition: ltiservices.php:69
__construct(Container $dic, ilPlugin $plugin)
@inheritDoc
Interface Observer \BackgroundTasks Contains several chained tasks and infos about them.
Class ilObjForumAdministration.
global $DIC
Definition: shib_login.php:26
PREG_SPLIT_NO_EMPTY PREG_SPLIT_DELIM_CAPTURE