Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions components/ILIAS/Mail/classes/Folder/MailFolderData.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ public function isDrafts(): bool
return $this->type === MailFolderType::DRAFTS;
}

public function isOutbox(): bool
{
return $this->type === MailFolderType::OUTBOX;
}

public function isSent(): bool
{
return $this->type === MailFolderType::SENT;
Expand Down
4 changes: 2 additions & 2 deletions components/ILIAS/Mail/classes/Folder/MailFolderTableUI.php
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ private function getActions(): array
}
}

if ($this->current_folder->isDrafts()) {
if ($this->current_folder->isDrafts() || $this->current_folder->isOutbox()) {
unset($actions[self::ACTION_SHOW], $actions[self::ACTION_REPLY], $actions[self::ACTION_FORWARD]);
} else {
unset($actions[self::ACTION_EDIT]);
Expand Down Expand Up @@ -421,7 +421,7 @@ private function getSubject(MailRecordData $record): Link
(string) $this->url_builder
->withParameter(
$this->action_token,
$this->current_folder->isDrafts() ? self::ACTION_EDIT : self::ACTION_SHOW
$this->current_folder->isDrafts() || $this->current_folder->isOutbox() ? self::ACTION_EDIT : self::ACTION_SHOW
)
->withParameter($this->row_id_token, (string) $record->getMailId())
->buildURI()
Expand Down
1 change: 1 addition & 0 deletions components/ILIAS/Mail/classes/Folder/MailFolderType.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,5 @@ enum MailFolderType: string
case SENT = 'sent';
case LOCAL = 'local';
case USER = 'user_folder';
case OUTBOX = 'outbox';
}
53 changes: 52 additions & 1 deletion components/ILIAS/Mail/classes/class.ilMail.php
Original file line number Diff line number Diff line change
Expand Up @@ -461,16 +461,18 @@ public function updateDraft(
string $a_m_subject,
string $a_m_message,
int $a_draft_id = 0,
?ilDateTime $a_send_time = null,
Copy link
Contributor

@mjansenDatabay mjansenDatabay Oct 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use a DateTimeImmutable here.

Since the "Schedule Date/Time" is a future date/time, we MUST NOT store this a UTC.

We MUST use the user timezone and the corresponding date/time string. Storing this as UTC can lead to issues like described here: https://andreas.heigl.org/2016/12/22/why-not-to-convert-a-datetime-to-timestamp/ / https://heiglandreas.github.io/slidedeck/time_is_an_illusion/20191113_aachen/index.html#/

So I recommend introducing two new explicit database fields in a database update objective.

bool $a_use_placeholders = false,
?string $a_tpl_context_id = null,
array $a_tpl_context_params = []
): int {
$a_send_time?->switchTimeZone('UTC');
Copy link
Contributor

@mjansenDatabay mjansenDatabay Oct 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my comment above: Storing a Sent Time (past) is okay, but a "Schedule Date/Time" (future) should be stored as a date/time string with the user's timezone in a separate field.

Addendum: We should NOT even "normalize" the timezone for the "Send Date". I suggested this years a go as a pull request, an while discussing this on the JourFixe, we stumbled upon the issue of how to tread the date/time values of all existing records in the database table? Now one knows the respective user timezones of these records.

$this->db->update(
$this->table_mail,
[
'folder_id' => ['integer', $a_folder_id],
'attachments' => ['clob', serialize($a_attachments)],
'send_time' => ['timestamp', date('Y-m-d H:i:s')],
'send_time' => ['timestamp', $a_send_time ? $a_send_time->get(IL_CAL_DATETIME) : date('Y-m-d H:i:s')],
'rcp_to' => ['clob', $a_rcp_to],
'rcp_cc' => ['clob', $a_rcp_cc],
'rcp_bcc' => ['clob', $a_rcp_bcc],
Expand All @@ -489,6 +491,55 @@ public function updateDraft(
return $a_draft_id;
}

public function sendTerminatedMail(
int $outbox_id,
int $folder_id,
int $sender_usr_id,
array $attachments,
string $to,
string $cc,
string $bcc,
string $subject,
string $message,
?ilDateTime $a_send_time = null,
bool $use_placeholders = false,
?string $template_context_id = null,
array $template_context_parameters = []
): int {
if ($use_placeholders) {
$message = $this->replacePlaceholders($message, $sender_usr_id);
}
$a_send_time?->switchTimeZone('UTC');
Copy link
Contributor

@mjansenDatabay mjansenDatabay Oct 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See comment above.

$message = str_ireplace(['<br />', '<br>', '<br/>'], "\n", $message);
$mail_values = [
'user_id' => ['integer', $sender_usr_id],
'folder_id' => ['integer', $folder_id],
'sender_id' => ['integer', $sender_usr_id],
'attachments' => ['clob', serialize($attachments)],
'send_time' => ['timestamp', $a_send_time ? $a_send_time->get(IL_CAL_DATETIME) : date('Y-m-d H:i:s')],
'rcp_to' => ['clob', $to],
'rcp_cc' => ['clob', $cc],
'rcp_bcc' => ['clob', $bcc],
'm_status' => ['text', 'read'],
'm_subject' => ['text', $subject],
'm_message' => ['clob', $message],
'tpl_ctx_id' => ['text', $template_context_id],
'tpl_ctx_params' => ['blob', json_encode($template_context_parameters, JSON_THROW_ON_ERROR)],
];

if (!$outbox_id) {
$outbox_id = $this->db->nextId($this->table_mail);
$mail_values['mail_id'] = ['integer', $outbox_id];
$this->db->insert($this->table_mail, $mail_values);
} else {
$this->db->update($this->table_mail, $mail_values, [
'mail_id' => ['integer', $outbox_id],
]);
}

return $outbox_id;
}

private function sendInternalMail(
int $folder_id,
int $sender_usr_id,
Expand Down
177 changes: 177 additions & 0 deletions components/ILIAS/Mail/classes/class.ilMailCronTerminatedMails.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
<?php

/**
* This file is part of ILIAS, a powerful learning management system
* published by ILIAS open source e-Learning e.V.
*
* ILIAS is licensed with the GPL-3.0,
* see https://www.gnu.org/licenses/gpl-3.0.en.html
* You should have received a copy of said license along with the
* source code, too.
*
* If this is not the case or you just want to try ILIAS, you'll find
* us at:
* https://www.ilias.de
* https://github.com/ILIAS-eLearning
*
*********************************************************************/

declare(strict_types=1);

namespace ILIAS\Mail;

use ilMail;
use ilContext;
use ilObjUser;
use ilSetting;
use ilLanguage;
use DateTimeZone;
use ilFormatMail;
use ilDBInterface;
use DateTimeImmutable;
use ILIAS\Cron\CronJob;
use ILIAS\Cron\Job\JobResult;
use ILIAS\Cron\Job\JobManager;
use ILIAS\HTTP\GlobalHttpState;
use ILIAS\Cron\Job\Schedule\JobScheduleType;
use ilLoggerFactory;
use Generator;

class ilMailCronTerminatedMails extends CronJob
{
private GlobalHttpState $http;
private ilLanguage $lng;
private ilSetting $settings;
private ilDBInterface $db;
private ilObjUser $user;
private bool $init_done = false;
private JobManager $cron_manager;
private ilMail $mail;
private ilFormatMail $umail;
Comment on lines +42 to +50
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we make them readonly, or the complete class??


private function init(): void
{
global $DIC;

if (!$this->init_done) {
$this->settings = $DIC->settings();
$this->lng = $DIC->language();
$this->db = $DIC->database();
$this->user = $DIC->user();
$this->http = $DIC->http();
$this->cron_manager = $DIC->cron()->manager();
$this->mail = new ilMail($this->user->getId());
$this->umail = new ilFormatMail($this->user->getId());

$this->lng->loadLanguageModule('mail');
$this->init_done = true;
}
}

public function getId(): string
{
return 'mail_terminated_mails';
}

public function getTitle(): string
{
$this->init();

return $this->lng->txt('mail_cron_terminated_mails');
}

public function getDescription(): string
{
$this->init();

return $this->lng->txt('mail_cron_terminated_mails_desc');
}

public function hasAutoActivation(): bool
{
return true;
}

public function hasFlexibleSchedule(): bool
{
return true;
}

public function getDefaultScheduleType(): JobScheduleType
{
return JobScheduleType::DAILY;
}

public function getDefaultScheduleValue(): ?int
{
return 1;
}

public function run(): JobResult
{
$this->init();

$job_result = new JobResult();
$job_result->setStatus(JobResult::STATUS_OK);

ilLoggerFactory::getLogger('mail')->info('Start sending terminated mails from all users.');

$mails = $this->getOutboxMails();
$sent_mail_ids = [];
foreach ($mails as $mail) {
try {
$mailer = $this->umail
->withContextId(ilContext::CONTEXT_CRON);

$mailer->setSaveInSentbox(true);

$mailer->autoresponder()->enableAutoresponder();
$errors = $mailer->enqueue(
$mail['rcp_to'],
$mail['rcp_cc'],
$mail['rcp_bcc'],
$mail['m_subject'],
$mail['m_message'],
unserialize($mail['attachments'], ['allowed_classes' => false]),
(bool) ($mail['use_placeholders'] ?? false)
);

if (empty($errors)) {
$sent_mail_ids[] = (int) ($mail['mail_id'] ?? 0);
}
} catch (\Exception $e) {
$job_result->setStatus(JobResult::STATUS_FAIL);
ilLoggerFactory::getLogger('mail')->error(
'Error sending terminated mail with id ' . ($mail['mail_id'] ?? 'unknown') . ': ' . $e->getMessage()
);
$job_result->setMessage($e->getMessage());
return $job_result;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return $job_result;
return $job_result;

}
}
$this->mail->deleteMails($sent_mail_ids);
ilLoggerFactory::getLogger('mail')->info(
'Sent ' . count($sent_mail_ids) . ' terminated mails and removed them from outbox.'
);
$job_result->setMessage('Processed ' . count($sent_mail_ids) . ' mails.');
return $job_result;
}

public function getOutboxMails(): Generator
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be good if we could describe the shape of the array and use this type in the Genertor.

...
/**
 * @phpstan-type MailWithFolderDatabaseRecordType array{
 *     obj_id: int,
 * }
 */
class ilMail
{
...

AI could really help to define such record types.

You could then use \Generator<MailWithFolderDatabaseRecordType> and import this type into consuming classes:

...
/**
 * @phpstan-import-type MailWithFolderDatabaseRecordType from \ilMail
 */
class MailConsumer
{
...

{
$res = $this->db->queryF(
<<<'SQL'
SELECT * FROM mail
JOIN mail_obj_data ON mail.folder_id = mail_obj_data.obj_id
WHERE mail_obj_data.m_type = %s
AND send_time IS NOT NULL
AND send_time <= %s
SQL,
['text', 'timestamp'],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use ilDBConstants types here.

['outbox', (new DateTimeImmutable('NOW', new DateTimeZone('UTC')))->format('Y-m-d H:i:s')]
);

while ($row = $this->db->fetchAssoc($res)) {
yield $row;
}
}
}
10 changes: 9 additions & 1 deletion components/ILIAS/Mail/classes/class.ilMailFolderGUI.php
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,15 @@ protected function executeTableAction(): void
(string) $this->folder->getFolderId()
);
$this->ctrl->setParameterByClass(ilMailFormGUI::class, self::PARAM_MAIL_ID, (string) $mail_ids[0]);
$this->ctrl->setParameterByClass(ilMailFormGUI::class, 'type', ilMailFormGUI::MAIL_FORM_TYPE_DRAFT);
if ($this->folder->isOutbox()) {
$this->ctrl->setParameterByClass(
ilMailFormGUI::class,
'type',
ilMailFormGUI::MAIL_FORM_TYPE_OUTBOX
);
} else {
$this->ctrl->setParameterByClass(ilMailFormGUI::class, 'type', ilMailFormGUI::MAIL_FORM_TYPE_DRAFT);
}
$this->ctrl->redirectByClass(ilMailFormGUI::class);

// no break
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,13 @@ public function insert(ilTemplate $a_tpl): void
$a_tpl->setVariable('PROP_GENERIC', $tpl->get());
$a_tpl->parseCurrentBlock();
}

public function checkInput(): bool
{
return true;
}

public function setValueByArray(): void
{
}
}
Loading