1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
|
<?php
namespace MassMail;
use \Semester, \DBManager, \UserFilter, \Folder, \User, \Config;
/**
* @license GPL2 or any later version
*
* @property int $id alias column for message_id
* @property int $message_id database column
* @property string|null $sender_id database column
* @property string $author_id database column
* @property int|null $send_at_date database column
* @property string|null $target database column
* @property \JSONArrayObject|null $config database column
* @property string|null $exclude_users database column
* @property string|null $cc database column
* @property string $subject database column
* @property string $message database column
* @property string|null $folder_id database column
* @property int $is_template database column
* @property int $locked database column
* @property int $sent database column
* @property int $protected database column
* @property int $mkdate database column
* @property int $chdate database column
* @property \SimpleORMapCollection<MassMailFilter> $filters has_many MassMailFilter
* @property \SimpleORMapCollection<MassMailToken> $tokens has_many MassMailToken
* @property \User $author has_one \User
* @property \User|null $sender has_one \User
* @property \Folder|null $folder has_one \Folder
*/
class MassMailMessage extends \SimpleORMap implements \UserFilterRange
{
protected static function configure($config = [])
{
$config['db_table'] = 'massmail_messages';
$config['serialized_fields']['config'] = \JSONArrayObject::class;
$config['has_one']['author'] = [
'class_name' => User::class,
'foreign_key' => 'author_id',
'assoc_foreign_key' => 'user_id'
];
$config['has_one']['sender'] = [
'class_name' => User::class,
'foreign_key' => 'sender_id',
'assoc_foreign_key' => 'user_id'
];
$config['has_many']['filters'] = [
'class_name' => MassMailFilter::class,
'assoc_foreign_key' => 'message_id',
'on_store' => 'store',
'on_delete' => 'delete'
];
$config['has_one']['folder'] = [
'class_name' => Folder::class,
'foreign_key' => 'folder_id',
'assoc_foreign_key' => 'id',
'on_store' => 'store',
'on_delete' => 'delete'
];
$config['has_many']['tokens'] = [
'class_name' => MassMailToken::class,
'assoc_foreign_key' => 'message_id',
'on_store' => 'store',
'on_delete' => 'delete'
];
parent::configure($config);
}
/**
* Finds all messages that are currently due to be sent.
* @return MassMailMessage[]
*/
public static function findUnsent(): array
{
return static::findBySQL(
"`is_template` = 0
AND `sent` = 0
AND `locked` = 0
AND (`send_at_date` IS NULL OR `send_at_date` <= UNIX_TIMESTAMP())
ORDER BY `mkdate`"
);
}
/**
* Finds all messages that have been successfully sent and can be deleted now according to their age.
* @return MassMailMessage[]
*/
public static function findObsolete(): array
{
return static::findBySQL(
"`sent` = 1 AND `is_template` = 0 AND `protected` = 0 AND `chdate` <= :threshold",
['threshold' => time() - (Config::get()->MASSMAIL_GC_DAYS * 24 * 60 * 60)]
);
}
/**
* Possible targets for mass mails.
* @return array
*/
public static function getTargets(): array
{
return [
'all' => _('alle'),
'students' => _('Studierende'),
'employees' => _('Beschäftigte'),
'lecturers' => _('Aktive Lehrende'),
'courses' => _('Veranstaltungen'),
'usernames' => _('Liste von Benutzernamen'),
];
}
/**
* Fetches all semesters.
* @return array
*/
public static function getSemesters(): array
{
$semesters = [];
foreach (array_reverse(Semester::getAll()) as $one) {
$semesters[$one->id] = $one->name;
}
return $semesters;
}
/**
* Get the folder belonging to this message. If none is found, it will be auto-created as a
* personal folder of the current user..
* @param string $id
* @return \FolderType
*/
public function findFolder(string $id): \FolderType
{
$messageFolder = Folder::findOneBySQL(
"`range_id` = :id AND `range_type` = 'massmail'",
['id' => $id]
);
if (!$messageFolder) {
$messageFolder = new \StandardFolder([
'user_id' => User::findCurrent()->id,
'range_id' => $id,
'range_type' => 'massmail',
'parent_id' => 'root',
'name' => _('Nachricht an Zielgruppen')
]);
$messageFolder->store();
} else {
$messageFolder = $messageFolder->getTypedFolder();
}
return $messageFolder;
}
/**
* Gets the real recipient list for this message.
* @return string[] the usernames that will get this message.
*/
public function getRecipients(): array
{
$ids = [];
switch ($this->target) {
// Everyone studying something or working at an institute.
case 'all':
$sql = "SELECT DISTINCT `user_id` FROM `user_studiengang`";
$parameters = [];
if (!MassMailPermission::has($this->author_id, true)) {
$permission = MassMailPermission::getForUser($this->author);
$sql .= " WHERE `abschluss_id` IN (:degrees) OR `fach_id` IN (:subjects)";
$parameters = [
'degrees' => $permission['allowed_degrees'],
'subjects' => $permission['allowed_subjects']
];
}
$students = DBManager::get()->fetchFirst($sql, $parameters);
$sql = "SELECT DISTINCT `user_id` FROM `user_inst` WHERE `inst_perms` IN (:perms)";
$parameters = ['perms' => ['autor', 'tutor', 'dozent']];
if (!MassMailPermission::has($this->author_id, true)) {
$sql .= " AND `Institut_id` IN (:institutes)";
$parameters = [
'institutes' => $permission['allowed_institutes']
];
}
$employees = DBManager::get()->fetchFirst($sql, $parameters);
$ids = array_unique(array_merge($students, $employees));
break;
// Students are users with at least one studycourse assignment in user_studiengang.
case 'students':
$sql = "SELECT DISTINCT `user_id` FROM `user_studiengang`";
$parameters = [];
if (!MassMailPermission::has($this->author_id, true)) {
$permission = MassMailPermission::getForUser($this->author);
$sql .= " WHERE `abschluss_id` IN (:degrees) OR `fach_id` IN (:subjects)";
$parameters = [
'degrees' => $permission['allowed_degrees'],
'subjects' => $permission['allowed_subjects']
];
}
$ids = DBManager::get()->fetchFirst($sql, $parameters);
if (count($this->filters) > 0) {
$filtered = [];
foreach ($this->filters as $filter) {
$f = new UserFilter($filter->filter_id);
$filtered = array_merge($filtered, $f->getUsers());
}
$ids = array_unique(array_intersect($ids, $filtered));
}
break;
// Employees are users with at least one institute assignment at 'autor" level or more.
case 'employees':
$sql = "SELECT DISTINCT `user_id` FROM `user_inst` WHERE `inst_perms` IN (:perms)";
$parameters = ['perms' => ['autor', 'tutor', 'dozent']];
if (!MassMailPermission::has($this->author_id, true)) {
$permission = MassMailPermission::getForUser($this->author);
$sql .= " AND `Institut_id` IN (:institutes)";
$parameters = [
'institutes' => $permission->allowed_institutes ? $permission->allowed_institutes->pluck('id') : []
];
}
$ids = DBManager::get()->fetchFirst($sql, $parameters);
if (count($this->filters) > 0) {
$filtered = [];
foreach ($this->filters as $filter) {
$f = new UserFilter($filter->filter_id);
$filtered = array_merge($filtered, $f->getUsers());
}
$ids = array_unique(array_intersect($ids, $filtered));
}
break;
// Course members having the specified permission level.
case 'courses':
$courses = array_map(
fn ($course) => $course['id'],
$this->config['courses']->getArrayCopy()
);
$permission = $this->config['perm']->getArrayCopy();
$ids = DBManager::get()->fetchFirst(
"SELECT DISTINCT `user_id` FROM `seminar_user` WHERE `Seminar_id` IN (:courses) AND `status` IN (:perm)",
['courses' => $courses, 'perm' => $permission]
);
break;
// Lecturers of at least one course in the given semester
case 'lecturers':
$ids = DBManager::get()->fetchFirst(
"SELECT DISTINCT u.`user_id` FROM `seminar_user` u
LEFT JOIN `semester_courses` sc ON (sc.`course_id` = u.`Seminar_id`)
JOIN `seminare` s ON (s.`Seminar_id` = u.`Seminar_id`)
JOIN `sem_types` t ON (t.`id` = s.`status`)
WHERE (sc.`semester_id` = :semester OR sc.`semester_id` IS NULL)
AND t.`class` IN (:categories)
AND u.`status` = 'dozent'",
[
'semester' => $this->config['semester'],
'categories' => Config::get()->MASSMAIL_LECTURER_SEM_CATEGORIES
]
);
break;
case 'usernames':
$ids = DBManager::get()->fetchFirst(
"SELECT DISTINCT `user_id` FROM `auth_user_md5` WHERE `Username` IN (:usernames)",
['usernames' => explode("\n", $this->config['usernames'])]
);
}
return DBManager::get()->fetchFirst(
"SELECT DISTINCT `username`
FROM `auth_user_md5`
WHERE `visible` != :visible
AND `locked` = :locked
AND `user_id` IN (:ids)
AND `username` NOT IN (:exclude)
ORDER BY `username`",
[
'visible' => 'never',
'locked' => 0,
'ids' => $ids,
'exclude' => $this->exclude_users ? explode("\n", $this->exclude_users) : ['']
]
);
}
/**
* Checks whether this message has replacement markers in its message text.
* @param $with_tokens Check for tokens or just for "normal" markers?
* @return bool
*/
public function hasMarkers($type = 'all'): bool
{
$markers = MassMailMarker::findAndMapBySQL(
fn($m) => '{{' . $m->marker . '}}',
$type === 'all' ? "1" : "`type` = :type",
$type === 'all' ? [] : ['type' => $type]
);
foreach ($markers as $marker) {
if (str_contains($this->message, $marker)) {
return true;
}
}
return false;
}
/**
* Replaces serial message markers with the data of the given user.
* @param User $user
* @return string
*/
public function replaceMarkers(User $user): string
{
$text = MassMailMarker::processText($this->message, $user, $this->getMarkers());
if (count($this->tokens) > 0) {
$text = MassMailMarker::processToken($this->message, $text, $user);
}
return $text;
}
/**
* Get available serial message markers, optionally including person token markers
* @param bool $with_tokens
* @return array
*/
private function getMarkers($with_tokens = true): array
{
$found = [];
$markers = MassMailMarker::findBySQL($with_tokens ? "1" : "`type` != 'token'");
foreach ($markers as $marker) {
if (str_contains($this->message, $marker->marker)) {
$found[] = $marker;
}
}
return $found;
}
/**
* Get message attachments (excluding files used fot token generation)
* @return array|\FileRef[]
*/
public function getAttachments()
{
$files = [];
$folder = Folder::find($this->folder_id);
return array_filter(
$folder->getTypedFolder()->getFiles(),
fn ($ref) => !isset($ref->file->metadata['is_token_file'])
);
}
/**
* @see UserFilterRange::canEdit()
*/
public function canEditFilter(User $user, UserFilter $filter): bool
{
return MassMailPermission::has($user->id, true)
|| MassMailPermission::has($user->id, false) && $this->creator_id === $user->id;
}
}
|