Debian Codegraph @

lib/modules/nisMailAlias.inc

raw
1 <?php
2 /*
3
4 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
5 Copyright (C) 2004 - 2026 Roland Gruber
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 */
21
22 /**
23 * Provides NIS mail alias management.
24 *
25 * @package modules
26 * @author Roland Gruber
27 */
28
29 use LAM\TYPES\ConfiguredType;
30
31 /**
32 * Provides NIS mail alias management.
33 *
34 * @package modules
35 */
36 class nisMailAlias extends baseModule {
37
38 /** @var string[]|null mail cache */
39 private ?array $cachedMailList = null;
40 /** @var string[]|null $cachedUserList user cache */
41 private ?array $cachedUserList = null;
42 /** display limit */
43 private const DISPLAY_LIMIT = 50;
44
45 /**
46 * {@inheritDoc}
47 */
48 public function can_manage(): bool {
49 return $this->get_scope() === 'mailAlias';
50 }
51
52 /**
53 * {@inheritDoc}
54 */
55 public function get_metaData(): array {
56 $return = [];
57 // icon
58 $return['icon'] = 'mail.svg';
59 // base module
60 $return["is_base"] = true;
61 // LDAP filter
62 $return["ldap_filter"] = ['or' => "(objectClass=nisMailAlias)"];
63 // alias name
64 $return["alias"] = _("Mail aliases");
65 // RDN attribute
66 $return["RDN"] = ["cn" => "normal"];
67 // module dependencies
68 $return['dependencies'] = ['depends' => [], 'conflicts' => []];
69 // managed object classes
70 $return['objectClasses'] = ['nisMailAlias'];
71 // managed attributes
72 $return['attributes'] = ['cn', 'rfc822MailMember'];
73 // help Entries
74 $return['help'] = [
75 'alias' => [
76 "Headline" => _("Alias name"), 'attr' => 'cn',
77 "Text" => _("Mails to this name are forwarded to the recipients.")
78 ],
79 'recipient' => [
80 "Headline" => _("Recipients"), 'attr' => 'rfc822MailMember',
81 "Text" => _("Please enter the recipients for this alias.")
82 ],
83 'recipientList' => [
84 "Headline" => _("Recipient list"), 'attr' => 'rfc822MailMember',
85 "Text" => _("This is a comma separated list of recipients.")
86 ],
87 'filter' => [
88 "Headline" => _("Filter"),
89 "Text" => _("Here you can enter a filter value. Only entries which contain the filter text will be shown.")
90 ],
91 ];
92 // upload fields
93 $return['upload_columns'] = [
94 [
95 'name' => 'nisMailAlias_alias',
96 'description' => _('Alias name'),
97 'help' => 'alias',
98 'example' => 'root',
99 'required' => true
100 ],
101 [
102 'name' => 'nisMailAlias_recipients',
103 'description' => _('Recipient list'),
104 'help' => 'recipientList',
105 'example' => _('smiller')
106 ]
107 ];
108 // available PDF fields
109 $return['PDF_fields'] = [
110 'alias' => _('Alias name'),
111 'recipients' => _('Recipient list')
112 ];
113 return $return;
114 }
115
116 /**
117 * {@inheritDoc}
118 */
119 protected function load_Messages(): void {
120 $this->messages['alias'][0] = ['ERROR', _('Alias is empty or invalid!')]; // third array value is set dynamically
121 $this->messages['alias'][1] = ['ERROR', _('Account %s:') . ' nisMailAlias_alias', _('Alias is empty or invalid!')];
122 $this->messages['recipient'][0] = ['ERROR', _('Recipient is invalid!')]; // third array value is set dynamically
123 $this->messages['recipient'][1] = ['ERROR', _('Account %s:') . ' nisMailAlias_recipient', _('Recipient is invalid!')];
124 }
125
126 /**
127 * {@inheritDoc}
128 */
129 public function save_attributes(): array {
130 // skip saving if account is based on another structural object class
131 if (!$this->getAccountContainer()->isNewAccount && !in_array('nisMailAlias', $this->getAccountContainer()->attributes_orig['objectClass'])) {
132 return [];
133 }
134 return parent::save_attributes();
135 }
136
137 /**
138 * {@inheritDoc}
139 */
140 public function display_html_attributes(): htmlElement|array {
141 $return = new htmlResponsiveRow();
142 // alias name
143 $alias = '';
144 if (isset($this->attributes['cn'][0])) {
145 $alias = $this->attributes['cn'][0];
146 }
147 $nameInput = new htmlResponsiveInputField(_('Alias name'), 'cn', $alias, 'alias');
148 $nameInput->setRequired(true);
149 $nameInput->setCSSClasses(['maxwidth20']);
150 $return->add($nameInput);
151 // list current recipients
152 $mailList = $this->getMailList();
153 $userList = $this->getUserList();
154 $autoList = [];
155 if ((count($userList) + count($mailList)) < 300) {
156 $autoList = array_merge($userList, $mailList);
157 }
158 $recipientCount = 0;
159 if (isset($this->attributes['rfc822MailMember'])) {
160 natcasesort($this->attributes['rfc822MailMember']);
161 $this->attributes['rfc822MailMember'] = array_values($this->attributes['rfc822MailMember']);
162 $recipientCount = count($this->attributes['rfc822MailMember']);
163 if ($recipientCount < self::DISPLAY_LIMIT) {
164 for ($i = 0; $i < $recipientCount; $i++) {
165 if ($i === 0) {
166 if ($recipientCount === 1) {
167 $return->addLabel(new htmlOutputText(_('Recipient')));
168 }
169 else {
170 $return->addLabel(new htmlOutputText(_('Recipients')));
171 }
172 }
173 else {
174 $return->addLabel(new htmlOutputText('&nbsp;', false));
175 }
176 $mailField = new htmlInputField('rfc822MailMember' . $i, $this->attributes['rfc822MailMember'][$i]);
177 if ($autoList !== []) {
178 $mailField->enableAutocompletion($autoList);
179 }
180 $mailField->setCSSClasses(['maxwidth20']);
181 $mailGroup = new htmlGroup();
182 $mailGroup->addElement($mailField);
183 $mailGroup->addElement(new htmlAccountPageButton(static::class, 'selectMail', 'recipient' . $i, 'mail.svg', true, _('Select mail')));
184 $mailGroup->addElement(new htmlAccountPageButton(static::class, 'selectUser', 'recipient' . $i, 'user.svg', true, _('Select user')));
185 $mailGroup->addElement(new htmlButton('delRec' . $i, 'del.svg', true));
186 $mailGroup->addElement(new htmlHelpLink('recipient'));
187 $return->addField($mailGroup);
188 }
189 }
190 else {
191 $memberText = implode("\r\n", $this->attributes['rfc822MailMember']);
192 $return->add(new htmlResponsiveInputTextarea('rfc822MailMember', $memberText, 50, 30, _('Recipients'), 'recipient'));
193 }
194 }
195 if ($recipientCount < self::DISPLAY_LIMIT) {
196 // input box for new recipient
197 $return->addLabel(new htmlOutputText(_('New recipient')));
198 $newMailField = new htmlInputField('rfc822MailMember');
199 $newMailField->setOnKeyPress('SubmitForm(\'addRec\', event);');
200 if ($autoList !== []) {
201 $newMailField->enableAutocompletion($autoList);
202 }
203 $newMailField->setCSSClasses(['maxwidth20']);
204 $newGroup = new htmlGroup();
205 $newGroup->addElement($newMailField);
206 $newGroup->addElement(new htmlAccountPageButton(static::class, 'selectMail', 'recipientNew', 'mail.svg', true, _('Select mail')));
207 $newGroup->addElement(new htmlAccountPageButton(static::class, 'selectUser', 'recipientNew', 'user.svg', true, _('Select user')));
208 $newGroup->addElement(new htmlButton('addRec', 'add.svg', true));
209 $newGroup->addElement(new htmlHelpLink('recipient'));
210 $newGroup->addElement(new htmlHiddenInput('rec_number', (string) $recipientCount));
211 $return->addField($newGroup);
212 }
213 return $return;
214 }
215
216 /**
217 * {@inheritDoc}
218 */
219 public function process_attributes(): array {
220 $errors = [];
221 $this->attributes['cn'] = [];
222 $recipientCount = empty($this->attributes['rfc822MailMember']) ? 0 : count($this->attributes['rfc822MailMember']);
223 $this->attributes['rfc822MailMember'] = [];
224 // check alias name
225 $this->attributes['cn'][] = $_POST['cn'];
226 if (!isset($_POST['cn']) || ($_POST['cn'] == "") || !get_preg($_POST['cn'], 'nis_alias')) {
227 $message = $this->messages['alias'][0];
228 $message[] = $_POST['cn'];
229 $errors[] = $message;
230 }
231 if ($recipientCount < self::DISPLAY_LIMIT) {
232 // check old recipients
233 if (isset($_POST['rec_number'])) {
234 for ($i = 0; $i < $_POST['rec_number']; $i++) {
235 if (isset($_POST['delRec' . $i])) {
236 continue;
237 }
238 if (isset($_POST['rfc822MailMember' . $i]) && ($_POST['rfc822MailMember' . $i] != "")) {
239 // check if address has correct format
240 if (!get_preg($_POST['rfc822MailMember' . $i], 'nis_recipient') && !get_preg($_POST['rfc822MailMember' . $i], 'email')) {
241 $message = $this->messages['recipient'][0];
242 $message[] = $_POST['rfc822MailMember' . $i];
243 $errors[] = $message;
244 }
245 $this->attributes['rfc822MailMember'][] = $_POST['rfc822MailMember' . $i];
246 }
247 }
248 }
249 // check new recipient
250 if (isset($_POST['rfc822MailMember']) && ($_POST['rfc822MailMember'] != "")) {
251 // check if recipient has correct format
252 if (get_preg($_POST['rfc822MailMember'], 'nis_recipient') || get_preg($_POST['rfc822MailMember'], 'email')) {
253 $this->attributes['rfc822MailMember'][] = $_POST['rfc822MailMember'];
254 }
255 else {
256 $message = $this->messages['recipient'][0];
257 $message[] = $_POST['rfc822MailMember'];
258 $errors[] = $message;
259 }
260 }
261 }
262 else {
263 $recipients = explode("\r\n", $_POST['rfc822MailMember']);
264 foreach ($recipients as $recipient) {
265 $recipient = trim($recipient);
266 if (empty($recipient)) {
267 continue;
268 }
269 $this->attributes['rfc822MailMember'][] = $recipient;
270 // check if recipient has correct format
271 if (!get_preg($recipient, 'nis_recipient') && !get_preg($recipient, 'email')) {
272 $message = $this->messages['recipient'][0];
273 $message[] = htmlspecialchars($recipient);
274 $errors[] = $message;
275 }
276 }
277 }
278 $this->attributes['rfc822MailMember'] = array_unique($this->attributes['rfc822MailMember']);
279 return $errors;
280 }
281
282 /**
283 * Displays the mail selection.
284 *
285 * @return htmlElement meta HTML code
286 */
287 public function display_html_selectMail(): htmlElement {
288 return $this->display_html_select(true);
289 }
290
291 /**
292 * Processes user input of the host/user selection page.
293 * It checks if all input values are correct and updates the associated LDAP attributes.
294 *
295 * @return array<string|string[]>[] list of info/error messages
296 */
297 public function process_selectMail(): array {
298 return $this->process_select();
299 }
300
301 /**
302 * Displays the user selection.
303 *
304 * @return htmlElement meta HTML code
305 */
306 public function display_html_selectUser(): htmlElement {
307 return $this->display_html_select(false);
308 }
309
310 /**
311 * Processes user input of the host/user selection page.
312 * It checks if all input values are correct and updates the associated LDAP attributes.
313 *
314 * @return array<string|string[]>[] list of info/error messages
315 */
316 public function process_selectUser(): array {
317 return $this->process_select();
318 }
319
320 /**
321 * Displays the user/mail selection.
322 *
323 * @param boolean $isMail mail selection (user selection if false)
324 * @return htmlElement meta HTML code
325 */
326 public function display_html_select($isMail): htmlElement {
327 if ($isMail) {
328 $regex = 'email';
329 $options = $this->getMailList();
330 $suffix = 'Mail';
331 $label = _('Email');
332 }
333 else {
334 $regex = 'username';
335 $options = $this->getUserList();
336 $suffix = 'User';
337 $label = _('User');
338 }
339 $return = new htmlResponsiveRow();
340 $postKeys = array_keys($_POST);
341 $position = 'New';
342 for ($i = 0; $i < count($postKeys); $i++) {
343 if (str_starts_with($postKeys[$i], 'form_subpage_' . static::class . '_select' . $suffix . '_recipient')) {
344 $position = substr($postKeys[$i], strlen('form_subpage_' . static::class . '_select' . $suffix . '_recipient'));
345 break;
346 }
347 }
348 // load list with all mail addresses
349 $count = count($options);
350 for ($i = 0; $i < $count; $i++) {
351 if (!get_preg($options[$i], $regex)) {
352 unset($options[$i]);
353 }
354 }
355 $options = array_values($options);
356 $return->addLabel(new htmlOutputText(_('Filter')));
357 $filterGroup = new htmlGroup();
358 $filterInput = new htmlInputField('filter', null);
359 $filterInput->setCSSClasses(['maxwidth10']);
360 $filterInput->filterSelectBox('selectBox');
361 $filterGroup->addElement($filterInput);
362 $filterGroup->addElement(new htmlHelpLink('filter'));
363 $return->addField($filterGroup);
364 $return->addLabel(new htmlOutputText($label));
365 $mailSelect = new htmlSelect('selectBox', $options, [], 15);
366 $mailSelect->setMultiSelect($position === 'New');
367 $mailSelect->colspan = 5;
368 $return->addField($mailSelect);
369 $return->addVerticalSpacer('2rem');
370 $return->addLabel(new htmlAccountPageButton(static::class, 'attributes', 'select', _('Ok')));
371 $return->addField(new htmlAccountPageButton(static::class, 'attributes', 'back', _('Cancel')));
372 $return->add(new htmlHiddenInput('position', $position));
373 return $return;
374 }
375
376 /**
377 * Processes user input of the host/user selection page.
378 * It checks if all input values are correct and updates the associated LDAP attributes.
379 *
380 * @return array<string|string[]>[] list of info/error messages
381 */
382 public function process_select(): array {
383 if (isset($_POST['form_subpage_' . static::class . '_attributes_select'])) {
384 if (!isset($this->attributes['rfc822MailMember'])) {
385 $this->attributes['rfc822MailMember'] = [];
386 }
387 $position = $_POST['position'];
388 if ($position == 'New') {
389 $this->attributes['rfc822MailMember'] = array_merge($this->attributes['rfc822MailMember'], $_POST['selectBox']);
390 }
391 else {
392 $this->attributes['rfc822MailMember'][$_POST['position']] = $_POST['selectBox'];
393 }
394 return [];
395 }
396 return [];
397 }
398
399 /**
400 * {@inheritDoc}
401 */
402 public function getButtonStatus(): string {
403 if (!$this->getAccountContainer()->isNewAccount) {
404 // check if account is based on our object class
405 $objectClasses = $this->getAccountContainer()->attributes_orig['objectClass'];
406 if (is_array($objectClasses) && !in_array('nisMailAlias', $objectClasses)) {
407 return "disabled";
408 }
409 }
410 return "enabled";
411 }
412
413 /**
414 * {@inheritDoc}
415 */
416 public function build_uploadAccounts(array $rawAccounts, array $ids, array &$partialAccounts, array $selectedModules, ConfiguredType &$type): array {
417 $messages = [];
418 for ($i = 0; $i < count($rawAccounts); $i++) {
419 // add object class
420 if (!in_array("nisMailAlias", $partialAccounts[$i]['objectClass'])) {
421 $partialAccounts[$i]['objectClass'][] = "nisMailAlias";
422 }
423 // add alias name
424 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'nisMailAlias_alias', 'cn',
425 'nis_alias', $this->messages['alias'][1], $messages);
426 // add recipients
427 if ($rawAccounts[$i][$ids['nisMailAlias_recipients']] != "") {
428 $aliases = explode(',', $rawAccounts[$i][$ids['nisMailAlias_recipients']]);
429 // check format
430 for ($a = 0; $a < count($aliases); $a++) {
431 if (get_preg($aliases[$a], 'nis_recipient') || get_preg($aliases[$a], 'email')) {
432 $partialAccounts[$i]['rfc822MailMember'][] = $aliases[$a];
433 }
434 else {
435 $errMsg = $this->messages['recipient'][1];
436 $errMsg[] = [$i];
437 $messages[] = $errMsg;
438 }
439 }
440 }
441 }
442 return $messages;
443 }
444
445 /**
446 * {@inheritDoc}
447 */
448 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
449 $return = [];
450 $this->addSimplePDFField($return, 'alias', _('Alias name'), 'cn');
451 $this->addSimplePDFField($return, 'recipients', _('Recipient list'), 'rfc822MailMember');
452 return $return;
453 }
454
455 /**
456 * Returns a list of existing email addresses.
457 *
458 * @return string[] email addresses
459 */
460 private function getMailList(): array {
461 if ($this->cachedMailList !== null) {
462 return $this->cachedMailList;
463 }
464 $this->cachedMailList = [];
465 $entries = searchLDAPByAttribute('mail', '*', null, ['mail'], ['user']);
466 foreach ($entries as $entry) {
467 $this->cachedMailList[] = $entry['mail'][0];
468 }
469 $this->cachedMailList = array_values(array_unique($this->cachedMailList));
470 return $this->cachedMailList;
471 }
472
473 /**
474 * Returns a list of existing usernames.
475 *
476 * @return string[] usernames
477 */
478 private function getUserList(): array {
479 if ($this->cachedUserList !== null) {
480 return $this->cachedUserList;
481 }
482 $this->cachedUserList = [];
483 $result = searchLDAPByFilter('(|(objectClass=posixAccount)(objectClass=inetOrgPerson))', ['uid'], ['user']);
484 $count = count($result);
485 for ($i = 0; $i < $count; $i++) {
486 if (empty($result[$i]['uid'][0])) {
487 unset($result[$i]);
488 continue;
489 }
490 $this->cachedUserList[] = $result[$i]['uid'][0];
491 }
492 $this->cachedUserList = array_values(array_unique($this->cachedUserList));
493 return $this->cachedUserList;
494 }
495
496 /**
497 * @inheritDoc
498 */
499 public function getListAttributeDescriptions(ConfiguredType $type): array {
500 return [
501 "cn" => _("Alias name"),
502 "rfc822mailmember" => _("Recipient list")
503 ];
504 }
505
506 }