Debian Codegraph @

lib/modules/posixGroup.inc

raw
1 <?php
2
3 use LAM\TYPES\TypeManager;
4 use function LAM\TYPES\getScopeFromTypeId;
5 use LAM\TYPES\ConfiguredType;
6
7 /*
8
9 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
10 Copyright (C) 2003 - 2006 Tilo Lutz
11 2007 - 2026 Roland Gruber
12
13 This program is free software; you can redistribute it and/or modify
14 it under the terms of the GNU General Public License as published by
15 the Free Software Foundation; either version 2 of the License, or
16 (at your option) any later version.
17
18 This program is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 */
27
28
29 /**
30 * Manages Unix accounts for groups.
31 *
32 * @package modules
33 *
34 * @author Tilo Lutz
35 * @author Roland Gruber
36 * @author Michael Duergner
37 */
38
39 /**
40 * Manages the object class "posixGroup" for groups.
41 *
42 * @package modules
43 */
44 class posixGroup extends baseModule implements passwordService {
45
46 /** change GIDs of users and hosts? */
47 protected bool $changegids = false;
48 /** password attribute */
49 protected string $passwordAttrName = 'userPassword';
50 /** @var string[]|null $cachedGIDList cache for existing GID numbers */
51 private ?array $cachedGIDList = null;
52 /** @var array<string, array<string, string>>|null $cachedUserToGIDList cache for existing users and their GIDs */
53 private ?array $cachedUserToGIDList = null;
54 /** @var string[]|null $cachedGroupNameList cache for existing groups */
55 private ?array $cachedGroupNameList = null;
56
57 /**
58 * {@inheritDoc}
59 */
60 public function get_uploadColumns(array $selectedModules, ConfiguredType $type): array {
61 $return = parent::get_uploadColumns($selectedModules, $type);
62 $typeId = $type->getId();
63 if ($this->manageCnAndDescription($selectedModules)) {
64 array_unshift($return,
65 [
66 'name' => 'posixGroup_cn',
67 'description' => _('Group name'),
68 'help' => 'cn',
69 'example' => _('adminstrators'),
70 'required' => true,
71 'unique' => true
72 ]
73 );
74 array_unshift($return,
75 [
76 'name' => 'posixGroup_description',
77 'description' => _('Group description'),
78 'help' => 'descriptionList',
79 'example' => _('Administrators group')
80 ]
81 );
82 }
83 if (!$this->isBooleanConfigOptionSet('posixGroup_' . $typeId . '_hidememberUid')) {
84 $return[] = [
85 'name' => 'posixGroup_members',
86 'description' => _('Group members'),
87 'help' => 'upload_members',
88 'example' => _('user01,user02,user03')
89 ];
90 }
91 return $return;
92 }
93
94 /**
95 * {@inheritDoc}
96 */
97 public function build_uploadAccounts(array $rawAccounts, array $ids, array &$partialAccounts, array $selectedModules, ConfiguredType &$type): array {
98 $error_messages = [];
99 $needAutoGID = [];
100 $typeId = $type->getId();
101 for ($i = 0; $i < count($rawAccounts); $i++) {
102 if (!in_array("posixGroup", $partialAccounts[$i]['objectClass'])) {
103 $partialAccounts[$i]['objectClass'][] = "posixGroup";
104 }
105 if ($this->manageCnAndDescription($selectedModules)) {
106 // group name
107 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'posixGroup_cn', 'cn', 'groupname', $this->messages['cn'][3], $error_messages);
108 // description
109 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'posixGroup_description',
110 'description', null, [], $errors, '/;[ ]*/');
111 }
112 // GID
113 if ($rawAccounts[$i][$ids['posixGroup_gid']] == "") {
114 // autoGID
115 $needAutoGID[] = $i;
116 }
117 elseif (get_preg($rawAccounts[$i][$ids['posixGroup_gid']], 'digit')) {
118 $partialAccounts[$i]['gidNumber'] = $rawAccounts[$i][$ids['posixGroup_gid']];
119 }
120 else {
121 $errMsg = $this->messages['gidNumber'][8];
122 $errMsg[] = [$i];
123 $error_messages[] = $errMsg;
124 }
125 // group members
126 if (!$this->isBooleanConfigOptionSet('posixGroup_' . $typeId . '_hidememberUid') && ($rawAccounts[$i][$ids['posixGroup_members']] != "")) {
127 if (get_preg($rawAccounts[$i][$ids['posixGroup_members']], 'usernameList')) {
128 $partialAccounts[$i]['memberUid'] = explode(",", $rawAccounts[$i][$ids['posixGroup_members']]);
129 }
130 else {
131 $errMsg = $this->messages['memberUID'][0];
132 $errMsg[] = $i;
133 $error_messages[] = $errMsg;
134 }
135 }
136 // password
137 if ($rawAccounts[$i][$ids['posixGroup_password']] != "") {
138 if (get_preg($rawAccounts[$i][$ids['posixGroup_password']], 'password')) {
139 $partialAccounts[$i][$this->passwordAttrName] = pwd_hash($rawAccounts[$i][$ids['posixGroup_password']], true, $this->moduleSettings['posixAccount_pwdHash'][0]);
140 }
141 else {
142 $error_messages[] = $this->messages['userPassword'][1];
143 }
144 }
145 }
146 // fill in autoGIDs
147 if ($needAutoGID !== []) {
148 $errorsTemp = [];
149 $gids = $this->getNextGIDs(count($needAutoGID), $errorsTemp, $type);
150 if (is_array($gids)) {
151 for ($i = 0; $i < count($needAutoGID); $i++) {
152 $partialAccounts[$i]['gidNumber'] = $gids[$i];
153 }
154 }
155 else {
156 $error_messages[] = $this->messages['gidNumber'][2];
157 }
158 }
159 return $error_messages;
160 }
161
162 /**
163 * {@inheritDoc}
164 */
165 public function delete_attributes(): array {
166 $return = [];
167 $result = searchLDAPByFilter('(&(objectClass=posixAccount)(gidNumber=' . $this->attributes['gidNumber'][0] . '))', ['dn'], ['user', 'host']);
168 if (count($result) > 0) {
169 $max = 5;
170 if (count($result) < 5) {
171 $max = count($result);
172 }
173 $users = [];
174 for ($i = 0; $i < $max; $i++) {
175 $users[] = getAbstractDN($result[$i]['dn']);
176 }
177 $message = $this->messages['primaryGroup'][0];
178 $message[] = implode(', ', $users);
179 $return[$this->getAccountContainer()->dn_orig]['errors'][] = $message;
180 }
181 return $return;
182 }
183
184 /**
185 * {@inheritDoc}
186 */
187 public function display_html_attributes(): htmlElement|array {
188 $return = new htmlResponsiveRow();
189 $modules = $this->getAccountContainer()->get_type()->getModules();
190 $typeId = $this->getAccountContainer()->get_type()->getId();
191 if ($this->autoAddObjectClasses || (isset($this->attributes['objectClass']) && in_array('posixGroup', $this->attributes['objectClass']))) {
192 // auto sync group members
193 if ($this->isBooleanConfigOptionSet('posixGroup_autoSyncGon')) {
194 $this->syncGon(true);
195 }
196 // group name
197 if ($this->manageCnAndDescription($modules)) {
198 $this->addSimpleInputTextField($return, 'cn', _("Group name"), true);
199 }
200 // GID number
201 $gidNumberInput = $this->addSimpleInputTextField($return, 'gidNumber', _('GID number'));
202 $gidNumberInput->setMinimumAndMaximumNumber();
203 // description
204 if ($this->manageCnAndDescription($modules)) {
205 $this->addMultiValueInputTextField($return, 'description', _('Description'));
206 }
207 // password buttons
208 if (checkIfWriteAccessIsAllowed($this->get_scope()) && isset($this->attributes[$this->passwordAttrName][0])) {
209 $return->addLabel(new htmlOutputText(_('Password')));
210 $pwdContainer = new htmlGroup();
211 if (pwd_is_enabled($this->attributes[$this->passwordAttrName][0])) {
212 $pwdContainer->addElement(new htmlButton('lockPassword', _('Lock password')));
213 }
214 else {
215 $pwdContainer->addElement(new htmlButton('unlockPassword', _('Unlock password')));
216 }
217 $pwdContainer->addElement(new htmlSpacer('0.5rem', null));
218 $pwdContainer->addElement(new htmlButton('removePassword', _('Remove password')));
219 $return->addField($pwdContainer);
220 }
221 if (isset($this->orig['gidNumber'][0]) && $this->attributes['gidNumber'][0] != $this->orig['gidNumber'][0]) {
222 $return->add(new htmlResponsiveInputCheckbox('changegids', $this->changegids, _('Change GID number of users and hosts'), 'changegids'));
223 }
224 // group members
225 if (!$this->isBooleanConfigOptionSet('posixGroup_' . $typeId . '_hidememberUid')) {
226 $return->addVerticalSpacer('0.5rem');
227 $return->addLabel(new htmlOutputText(_("Group members")));
228 $membersGroup = new htmlGroup();
229 if (!$this->isBooleanConfigOptionSet('posixGroup_autoSyncGon')) {
230 $membersGroup->addElement(new htmlAccountPageButton(static::class, 'user', 'open', _('Edit members')));
231 }
232 $membersGroup->addElement(new htmlHelpLink('members'));
233 $return->addField($membersGroup);
234 $return->addLabel(new htmlOutputText('&nbsp;', false));
235 $users = $this->getUsers();
236 $members = [];
237 if (isset($this->attributes['memberUid'][0])) {
238 foreach ($this->attributes['memberUid'] as $uid) {
239 $members[] = (isset($users[$uid]) && isset($users[$uid]['cn'])) ? $uid . ' (' . $users[$uid]['cn'] . ')' : $uid;
240 }
241 }
242 $members = array_unique($members);
243 natcasesort($members);
244 $members = array_map(htmlspecialchars(...), $members);
245 $return->addField(new htmlOutputText(implode('<br>', $members), false));
246 }
247 // remove button
248 if (!$this->autoAddObjectClasses) {
249 $return->addVerticalSpacer('2rem');
250 $remButton = new htmlButton('remObjectClass', _('Remove Unix extension'));
251 $remButton->setCSSClasses(['lam-danger']);
252 $return->add($remButton, 12, 12, 12, 'text-center');
253 }
254 }
255 else {
256 // add button
257 $return->add(new htmlButton('addObjectClass', _('Add Unix extension')));
258 }
259 return $return;
260 }
261
262
263 /**
264 * Displays selections to add or remove users from current group.
265 *
266 * @return htmlElement meta HTML output
267 */
268 public function display_html_user() {
269 $return = new htmlResponsiveRow();
270 if (!isset($this->attributes['memberUid'])) {
271 $this->attributes['memberUid'] = [];
272 }
273 // load list with all users
274 $userAndGIDs = $this->getUsers();
275 $users = [];
276 foreach ($userAndGIDs as $user => $userAttrs) {
277 if (!in_array($user, $this->attributes['memberUid'])) {
278 $display = $user . ' (' . $userAttrs['cn'] . ')';
279 if ($this->attributes['gidNumber'][0] == $userAttrs['gid']) {
280 if (isset($this->moduleSettings['posixAccount_primaryGroupAsSecondary'][0])
281 && ($this->moduleSettings['posixAccount_primaryGroupAsSecondary'][0] == 'true')) {
282 $users[$display] = $user;
283 }
284 }
285 else {
286 $users[$display] = $user;
287 }
288 }
289 }
290 natcasesort($users);
291 $return->add(new htmlSubTitle(_("Group members")));
292
293 $remUsers = $this->attributes['memberUid'];
294 natcasesort($remUsers);
295 $remUsersDescriptive = [];
296 foreach ($remUsers as $user) {
297 if (isset($userAndGIDs[$user])) {
298 $remUsersDescriptive[$user . ' (' . $userAndGIDs[$user]['cn'] . ')'] = $user;
299 }
300 else {
301 $remUsersDescriptive[$user] = $user;
302 }
303 }
304
305 $this->addDoubleSelectionArea($return, _("Selected users"), _("Available users"), $remUsersDescriptive, [],
306 $users, [], 'members', false, true);
307
308 // sync from group of names
309 $gon = $this->getAccountContainer()->getAccountModule('groupOfNames');
310 if ($gon == null) {
311 $gon = $this->getAccountContainer()->getAccountModule('groupOfUniqueNames');
312 }
313 if ($gon == null) {
314 $gon = $this->getAccountContainer()->getAccountModule('groupOfMembers');
315 }
316 if ($gon != null) {
317 $return->addVerticalSpacer('2rem');
318 $syncButton = new htmlButton('syncGON', sprintf(_('Sync from %s'), $gon->get_alias()));
319 $return->add($syncButton, 12, 12, 12, 'text-center');
320 $return->addVerticalSpacer('1rem');
321 $return->add(new htmlResponsiveInputCheckbox('syncGON_delete', true, _('Delete non-matching entries'), null, false));
322 }
323 $windows = $this->getAccountContainer()->getAccountModule('windowsGroup');
324 if ($windows != null) {
325 $return->addVerticalSpacer('2rem');
326 $syncButton = new htmlButton('syncWindows', sprintf(_('Sync from %s'), $windows->get_alias()));
327 $return->add($syncButton, 12, 12, 12, 'text-center');
328 $return->addVerticalSpacer('1rem');
329 $return->add(new htmlResponsiveInputCheckbox('syncWindows_delete', true, _('Delete non-matching entries'), null, false));
330 }
331
332 // back button
333 $return->addVerticalSpacer('2rem');
334 $return->add(new htmlAccountPageButton(static::class, 'attributes', 'back', _('Back')));
335
336 return $return;
337 }
338
339 /**
340 * {@inheritDoc}
341 */
342 public function can_manage(): bool {
343 return $this->get_scope() === 'group';
344 }
345
346 /**
347 * {@inheritDoc}
348 */
349 public function get_metaData(): array {
350 $return = [];
351 // icon
352 $return['icon'] = 'tux.svg';
353 if ($this->get_scope() == "group") {
354 // this is a base module
355 $return["is_base"] = true;
356 // LDAP filter
357 $return["ldap_filter"] = ['or' => "(objectClass=posixGroup)"];
358 }
359 // alias name
360 $return["alias"] = _('Unix');
361 // RDN attribute
362 $return["RDN"] = ["cn" => "normal"];
363 // module dependencies
364 $return['dependencies'] = ['depends' => [], 'conflicts' => []];
365 // managed object classes
366 $return['objectClasses'] = ['posixGroup'];
367 // LDAP aliases
368 $return['LDAPaliases'] = ['commonName' => 'cn'];
369 // managed attributes
370 $return['attributes'] = ['gidNumber', $this->passwordAttrName, 'memberUid'];
371 // profile options
372 if (!$this->autoAddObjectClasses) {
373 $profileContainer = new htmlResponsiveRow();
374 $profileContainer->add(new htmlResponsiveInputCheckbox('posixGroup_addExt', false, _('Automatically add this extension'), 'autoAdd'));
375 $return['profile_options'] = $profileContainer;
376 }
377 // available PDF fields
378 $return['PDF_fields'] = [
379 'gidNumber' => _('GID number'),
380 ];
381 // upload fields
382 $return['upload_columns'] = [
383 [
384 'name' => 'posixGroup_gid',
385 'description' => _('GID number'),
386 'help' => 'gidNumber',
387 'example' => '2034'
388 ],
389 [
390 'name' => 'posixGroup_password',
391 'description' => _('Group password'),
392 'help' => 'password',
393 'example' => _('secret')
394 ]
395 ];
396 // help Entries
397 $return['help'] = [
398 'gidNumber' => [
399 "Headline" => _("GID number"), 'attr' => 'gidNumber',
400 "Text" => _("If empty GID number will be generated automatically depending on your configuration settings.")
401 ],
402 'description' => [
403 "Headline" => _("Description"), 'attr' => 'description',
404 "Text" => _("Here you can enter a description for this group.")
405 ],
406 'descriptionList' => [
407 "Headline" => _("Description"), 'attr' => 'description',
408 "Text" => _("Here you can enter a description for this group.") . ' ' . _("Multiple values are separated by semicolon.")
409 ],
410 'members' => [
411 "Headline" => _("Group members"), 'attr' => 'memberUid',
412 "Text" => _("Users who are member of the current group. Users who have set their primary group to this group will not be shown.")
413 ],
414 'upload_members' => [
415 "Headline" => _("Group members"), 'attr' => 'memberUid',
416 "Text" => _("Users who will become member of the current group. User names are separated by semicolons.")
417 ],
418 'password' => [
419 "Headline" => _("Group password"), 'attr' => $this->passwordAttrName,
420 "Text" => _("Sets the group password.")
421 ],
422 'minMaxGID' => [
423 "Headline" => _("GID number"),
424 "Text" => _("These are the minimum and maximum numbers to use for group IDs when creating new group accounts. New group accounts will always get the highest number in use plus one.")
425 ],
426 'pwdHash' => [
427 "Headline" => _("Password hash type"),
428 "Text" => _("LAM supports a large number of possibilities to generate the hash value of passwords. CRYPT-SHA512 and SSHA are the most common. We do not recommend to use plain text passwords unless passwords are hashed server-side.")
429 ],
430 'cn' => [
431 "Headline" => _("Group name"), 'attr' => 'cn',
432 "Text" => _("Group name of the group which should be created. Valid characters are: a-z, A-Z, 0-9 and .-_ . If group name is already used group name will be expanded with a number. The next free number will be used.")
433 ],
434 'changegids' => [
435 "Headline" => _("Change GID number of users and hosts"),
436 "Text" => _("The ID of this group was changed. You can update all user and host entries to the new group ID.")
437 ],
438 'gidCheckSuffix' => [
439 "Headline" => _("Suffix for GID/group name check"),
440 "Text" => _("LAM checks if the entered group name and GID are unique. Here you can enter the LDAP suffix that is used to search for duplicates. By default, the account type suffix is used. You only need to change this if you use multiple server profiles with different OUs but need unique group names or GIDs.")
441 ],
442 'gidGenerator' => [
443 "Headline" => _("GID generator"),
444 "Text" => _("LAM will automatically suggest UID/GID numbers. You can either use a fixed range of numbers or an LDAP entry with object class \"sambaUnixIdPool\" or \"msSFU30DomainInfo\".")
445 . ' ' . _('Magic number will set a fixed value that must match your server configuration.')
446 ],
447 'sambaIDPoolDN' => [
448 "Headline" => _("Samba ID pool DN"),
449 "Text" => _("Please enter the DN of the LDAP entry with object class \"sambaUnixIdPool\".")
450 ],
451 'windowsIDPoolDN' => [
452 "Headline" => _("Windows domain info DN"),
453 "Text" => _("Please enter the DN of the LDAP entry with object class \"msSFU30DomainInfo\".")
454 ],
455 'filter' => [
456 "Headline" => _("Filter"),
457 "Text" => _("Here you can enter a filter value. Only entries which contain the filter text will be shown.")
458 . ' ' . _('The filter can be any regular expression, e.g. ".*" = any characters, "^" = line start, "$" = line end.')
459 ],
460 'hidememberUid' => [
461 "Headline" => _('Disable membership management'), 'attr' => 'memberUid',
462 "Text" => _('Disables the group membership management.')
463 ],
464 'autoAdd' => [
465 "Headline" => _("Automatically add this extension"),
466 "Text" => _("This will enable the extension automatically if this profile is loaded.")
467 ],
468 'autoSyncGon' => [
469 "Headline" => _("Force sync with group of names"),
470 "Text" => _("This will force syncing with group of names members of the same group.")
471 ],
472 'magicNumber' => [
473 "Headline" => _("Magic number"),
474 "Text" => _("Please enter the magic number you configured on server side.")
475 ],
476 ];
477
478 return $return;
479 }
480
481
482 /**
483 * {@inheritDoc}
484 */
485 public function get_configOptions(array $scopes, array $allScopes): htmlElement|array {
486 $typeManager = new TypeManager($_SESSION['conf_config']);
487 // configuration options
488 $configContainer = new htmlResponsiveRow();
489 $configContainer->add(new htmlSubTitle(_("Groups")));
490 foreach ($allScopes[static::class] as $typeId) {
491 if (count($allScopes[static::class]) > 1) {
492 $title = new htmlDiv(null, new htmlOutputText($typeManager->getConfiguredType($typeId)->getAlias()));
493 $title->setCSSClasses(['bold', 'responsiveLabel']);
494 $configContainer->add($title, 12, 6);
495 $configContainer->add(new htmlOutputText('&nbsp;', false), 0, 6);
496 }
497 $this->addAccountSpecificConfigOptions($configContainer, $typeId);
498 $configContainer->addVerticalSpacer('2rem');
499 }
500 $gonModules = ['groupOfNames', 'groupOfUniqueNames', 'groupOfMembers'];
501 $gonFound = false;
502 foreach ($gonModules as $gonModule) {
503 if (!empty($allScopes[$gonModule])) {
504 foreach ($allScopes[$gonModule] as $gonTypeId) {
505 if (getScopeFromTypeId($gonTypeId) === 'group') {
506 $gonFound = true;
507 }
508 }
509 }
510 }
511 if ($gonFound || !isset($allScopes['posixAccount'])) {
512 $configContainer->add(new htmlSubTitle(_("Options")));
513 }
514 if ($gonFound) {
515 $configContainer->add(new htmlResponsiveInputCheckbox('posixGroup_autoSyncGon', false, _('Force sync with group of names'), 'autoSyncGon'));
516 }
517 // display password hash option only if posixAccount module is not used
518 if (!isset($allScopes['posixAccount'])) {
519 $configContainer->add(new htmlResponsiveSelect('posixAccount_pwdHash', getSupportedHashTypes(), ['CRYPT-SHA512'], _("Password hash type"), 'pwdHash'));
520 }
521 return $configContainer;
522 }
523
524 /**
525 * Adds the account specific options to the config container.
526 *
527 * @param htmlResponsiveRow $configContainer container
528 * @param string $typeId type ID
529 */
530 protected function addAccountSpecificConfigOptions($configContainer, $typeId): void {
531 $genOptions = [
532 _('Fixed range') => 'range',
533 _('Samba ID pool') => 'sambaPool',
534 _('Windows domain info') => 'windowsDomain',
535 _('Magic number') => 'magicNumber'
536 ];
537 $gidGeneratorSelect = new htmlResponsiveSelect('posixGroup_' . $typeId . '_gidGenerator', $genOptions, ['range'], _('GID generator'), 'gidGenerator');
538 $gidGeneratorSelect->setHasDescriptiveElements(true);
539 $gidGeneratorSelect->setTableRowsToHide([
540 'range' => ['posixGroup_' . $typeId . '_sambaIDPoolDN', 'posixGroup_' . $typeId . '_windowsIDPoolDN', 'posixGroup_' . $typeId . '_magicNumber'],
541 'sambaPool' => ['posixGroup_' . $typeId . '_minGID', 'posixGroup_' . $typeId . '_maxGID', 'posixGroup_' . $typeId . '_windowsIDPoolDN', 'posixGroup_' . $typeId . '_magicNumber'],
542 'windowsDomain' => ['posixGroup_' . $typeId . '_minGID', 'posixGroup_' . $typeId . '_maxGID', 'posixGroup_' . $typeId . '_sambaIDPoolDN', 'posixGroup_' . $typeId . '_magicNumber'],
543 'magicNumber' => ['posixGroup_' . $typeId . '_minGID', 'posixGroup_' . $typeId . '_maxGID', 'posixGroup_' . $typeId . '_windowsIDPoolDN', 'posixGroup_' . $typeId . '_sambaIDPoolDN']
544 ]);
545 $gidGeneratorSelect->setTableRowsToShow([
546 'range' => ['posixGroup_' . $typeId . '_minGID', 'posixGroup_' . $typeId . '_maxGID'],
547 'sambaPool' => ['posixGroup_' . $typeId . '_sambaIDPoolDN'],
548 'windowsDomain' => ['posixGroup_' . $typeId . '_windowsIDPoolDN'],
549 'magicNumber' => ['posixGroup_' . $typeId . '_magicNumber']
550 ]);
551 $configContainer->add($gidGeneratorSelect);
552 $minGidInput = new htmlResponsiveInputField(_('Minimum GID number'), 'posixGroup_' . $typeId . '_minGID', null, 'minMaxGID');
553 $minGidInput->setRequired(true);
554 $configContainer->add($minGidInput);
555 $maxGidInput = new htmlResponsiveInputField(_('Maximum GID number'), 'posixGroup_' . $typeId . '_maxGID', null, 'minMaxGID');
556 $maxGidInput->setRequired(true);
557 $configContainer->add($maxGidInput);
558 $gidGeneratorDN = new htmlResponsiveInputField(_('Samba ID pool DN'), 'posixGroup_' . $typeId . '_sambaIDPoolDN', null, 'sambaIDPoolDN');
559 $gidGeneratorDN->setRequired(true);
560 $configContainer->add($gidGeneratorDN);
561 $winGeneratorDN = new htmlResponsiveInputField(_('Windows domain info DN'), 'posixGroup_' . $typeId . '_windowsIDPoolDN', null, 'windowsIDPoolDN');
562 $winGeneratorDN->setRequired(true);
563 $configContainer->add($winGeneratorDN);
564 $magicNumber = new htmlResponsiveInputField(_('Magic number'), 'posixGroup_' . $typeId . '_magicNumber', null, 'magicNumber');
565 $magicNumber->setRequired(true);
566 $configContainer->add($magicNumber);
567 $configContainer->add(new htmlResponsiveInputField(_('Suffix for GID/group name check'), 'posixGroup_' . $typeId . '_gidCheckSuffix', '', 'gidCheckSuffix'));
568 $configContainer->add(new htmlResponsiveInputCheckbox('posixGroup_' . $typeId . '_hidememberUid', false, _('Disable membership management'), 'hidememberUid'));
569 }
570
571 /**
572 * {@inheritDoc}
573 */
574 public function check_configOptions(array $typeIds, array &$options): array {
575 foreach ($typeIds as $typeId) {
576 if ($options['posixGroup_' . $typeId . '_gidGenerator'][0] == 'range') {
577 $this->meta['config_checks']['group']['posixGroup_' . $typeId . '_minGID'] = [
578 'type' => 'ext_preg',
579 'regex' => 'digit',
580 'required' => true,
581 'required_message' => $this->messages['gidNumber'][5],
582 'error_message' => $this->messages['gidNumber'][5]];
583 $this->meta['config_checks']['group']['posixGroup_' . $typeId . '_maxGID'] = [
584 'type' => 'ext_preg',
585 'regex' => 'digit',
586 'required' => true,
587 'required_message' => $this->messages['gidNumber'][6],
588 'error_message' => $this->messages['gidNumber'][6]];
589 $this->meta['config_checks']['group']['cmpGID'] = [
590 'type' => 'int_greater',
591 'cmp_name1' => 'posixGroup_' . $typeId . '_maxGID',
592 'cmp_name2' => 'posixGroup_' . $typeId . '_minGID',
593 'error_message' => $this->messages['gidNumber'][7]];
594 }
595 elseif ($options['posixGroup_' . $typeId . '_gidGenerator'][0] == 'sambaPool') {
596 $this->meta['config_checks']['group']['posixGroup_' . $typeId . '_sambaIDPoolDN'] = [
597 'type' => 'ext_preg',
598 'regex' => 'dn',
599 'required' => true,
600 'required_message' => $this->messages['sambaIDPoolDN'][0],
601 'error_message' => $this->messages['sambaIDPoolDN'][0]];
602 }
603 elseif ($options['posixGroup_' . $typeId . '_gidGenerator'][0] == 'windowsDomain') {
604 $this->meta['config_checks']['group']['posixGroup_' . $typeId . '_windowsIDPoolDN'] = [
605 'type' => 'ext_preg',
606 'regex' => 'dn',
607 'required' => true,
608 'required_message' => $this->messages['windowsIDPoolDN'][0],
609 'error_message' => $this->messages['windowsIDPoolDN'][0]];
610 }
611 elseif ($options['posixGroup_' . $typeId . '_gidGenerator'][0] == 'magicNumber') {
612 $this->meta['config_checks']['group']['posixGroup_' . $typeId . '_magicNumber'] = [
613 'type' => 'ext_preg',
614 'regex' => 'digit',
615 'required' => true,
616 'required_message' => $this->messages['magicNumber'][0],
617 'error_message' => $this->messages['magicNumber'][0]];
618 }
619 }
620 return parent::check_configOptions($typeIds, $options);
621 }
622
623 /**
624 * {@inheritDoc}
625 */
626 public function get_profileOptions(string $typeId): ?htmlResponsiveRow {
627 $parentOptions = parent::get_profileOptions($typeId);
628 $typeManager = new TypeManager();
629 if (!$this->manageCnAndDescription($typeManager->getConfiguredType($typeId)->getModules())) {
630 return $parentOptions;
631 }
632 $parentOptions ??= new htmlResponsiveRow();
633 $parentOptions->add(new htmlResponsiveInputTextarea('posixGroup_description', '', 30, 4, _('Description'), 'description'));
634 return $parentOptions;
635 }
636
637 /**
638 * {@inheritDoc}
639 */
640 public function get_pdfFields(string $typeId): array {
641 $fields = parent::get_pdfFields($typeId);
642 $typeManager = new TypeManager();
643 $modules = $typeManager->getConfiguredType($typeId)->getModules();
644 if ($this->manageCnAndDescription($modules)) {
645 $fields['cn'] = _('Group name');
646 $fields['description'] = _('Description');
647 }
648 if (!$this->isBooleanConfigOptionSet('posixGroup_' . $typeId . '_hidememberUid')) {
649 $fields['memberUid'] = _('Group members');
650 $fields['memberUidPrimary'] = _('Group members (incl. primary members)');
651 }
652 return $fields;
653 }
654
655 /**
656 * {@inheritDoc}
657 */
658 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
659 $return = [];
660 $this->addSimplePDFField($return, 'memberUid', _('Group members'));
661 $this->addSimplePDFField($return, 'cn', _('Group name'));
662 $this->addSimplePDFField($return, 'gidNumber', _('GID number'));
663 $this->addSimplePDFField($return, 'description', _('Description'));
664 if (in_array(static::class . '_memberUidPrimary', $pdfKeys)) {
665 $members = empty($this->attributes['memberUid']) ? [] : $this->attributes['memberUid'];
666 if (!empty($this->attributes['gidNumber'])) {
667 $filter = "(&(&" . get_ldap_filter('user') . ")(gidNumber=" . $this->attributes['gidNumber'][0] . "))";
668 $entries = searchLDAPByFilter($filter, ['uid'], ['user']);
669 foreach ($entries as $entry) {
670 $members[] = $entry['uid'][0];
671 }
672 }
673 $this->addPDFKeyValue($return, 'memberUidPrimary', _('Group members'), $members);
674 }
675 return $return;
676 }
677
678 /**
679 * {@inheritDoc}
680 */
681 protected function load_Messages(): void {
682 $this->messages['userPassword'][1] = ['ERROR', _('Password'), _('Password contains invalid characters. Valid characters are:') . ' a-z, A-Z, 0-9 and #*,.;:_-+!%&/|?{[()]}=@$ §°!'];
683 $this->messages['gidNumber'][0] = ['INFO', _('GID number'), _('GID number has changed. Please select checkbox to change GID number of users and hosts.')];
684 $this->messages['gidNumber'][2] = ['WARN', _('ID-Number'), _('It is possible that this ID-number is reused. This can cause several problems because files with old permissions might still exist. To avoid this warning set maxUID to a higher value.')];
685 $this->messages['gidNumber'][3] = ['ERROR', _('ID-Number'), _('No free ID-Number!')];
686 $this->messages['gidNumber'][4] = ['ERROR', _('ID-Number'), _('ID is already in use')];
687 $this->messages['gidNumber'][5] = ['ERROR', _('Minimum GID number'), _('Minimum GID number is invalid or empty!')];
688 $this->messages['gidNumber'][6] = ['ERROR', _('Maximum GID number'), _('Maximum GID number is invalid or empty!')];
689 $this->messages['gidNumber'][7] = ['ERROR', _('Maximum GID number'), _('Maximum GID number must be greater than minimum GID number!')];
690 $this->messages['gidNumber'][8] = ['ERROR', _('Account %s:') . ' posixGroup_gid', _('GID number has to be a numeric value!')];
691 $this->messages['cn'][0] = ['WARN', _('Group name'), _('You are using capital letters. This can cause problems because Windows is not case-sensitive.')];
692 $this->messages['cn'][1] = ['WARN', _('Group name'), _('Group name in use. Selected next free group name.')];
693 $this->messages['cn'][2] = ['ERROR', _('Group name'), _('Group name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
694 $this->messages['cn'][3] = ['ERROR', _('Account %s:') . ' posixGroup_cn', _('Group name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
695 $this->messages['memberUID'][0] = ['ERROR', _('Account %s:') . ' posixGroup_members', _("This value must be a list of user names separated by semicolons.")];
696 $this->messages['primaryGroup'][0] = ['ERROR', _('There are still users who have this group as their primary group.')];
697 $this->messages['sambaIDPoolDN'][0] = ['ERROR', _('Samba ID pool DN'), _('This is not a valid DN!')];
698 $this->messages['windowsIDPoolDN'][0] = ['ERROR', _('Windows domain info DN'), _('This is not a valid DN!')];
699 $this->messages['magicNumber'][0] = ['ERROR', _('Magic number'), _('Please enter a valid number.')];
700 }
701
702
703 /**
704 * {@inheritDoc}
705 */
706 public function getManagedAttributes(string $typeId): array {
707 $attrs = parent::getManagedAttributes($typeId);
708 $typeManager = new TypeManager();
709 $modules = $typeManager->getConfiguredType($typeId)->getModules();
710 if ($this->manageCnAndDescription($modules)) {
711 $attrs[] = 'cn';
712 $attrs[] = 'description';
713 }
714 return $attrs;
715 }
716
717 /**
718 * {@inheritDoc}
719 */
720 public function module_complete(): bool {
721 if (!$this->getAccountContainer()->isNewAccount) {
722 // check if account is based on our object class
723 $objectClasses = $this->getAccountContainer()->attributes_orig['objectClass'];
724 if (is_array($objectClasses) && !in_array('posixGroup', $objectClasses)) {
725 return true;
726 }
727 }
728 $modules = $this->getAccountContainer()->get_type()->getModules();
729 if ($this->manageCnAndDescription($modules) && ($this->attributes['cn'][0] == '')) {
730 return false;
731 }
732 return isset($this->attributes['gidNumber'][0]) && $this->attributes['gidNumber'][0] !== '';
733 }
734
735
736 /**
737 * {@inheritDoc}
738 */
739 public function getButtonStatus(): string {
740 if (!$this->getAccountContainer()->isNewAccount) {
741 // check if account is based on our object class
742 $objectClasses = $this->getAccountContainer()->attributes_orig['objectClass'];
743 if (is_array($objectClasses) && !in_array('posixGroup', $objectClasses)) {
744 return "disabled";
745 }
746 }
747 return "enabled";
748 }
749
750 /**
751 * {@inheritdoc}
752 */
753 public function getWildCardReplacements(): array {
754 $replacements = [];
755 // group name
756 if (!empty($_POST['cn'])) {
757 $replacements['group'] = $_POST['cn'];
758 }
759 elseif (!empty($this->attributes['cn'][0])) {
760 $replacements['group'] = $this->attributes['cn'][0];
761 }
762 return $replacements;
763 }
764
765 /**
766 * {@inheritdoc}
767 */
768 public function getWildcardTargetAttributeNames(): array {
769 return ['description'];
770 }
771
772 /**
773 * {@inheritDoc}
774 */
775 public function process_attributes(): array {
776 $this->getAccountContainer()->replaceWildcardsInPOST($this->getWildcardTargetAttributeNames());
777 $errors = [];
778 if (isset($_POST['addObjectClass'])) {
779 if (!isset($this->attributes['objectClass'])) {
780 $this->attributes['objectClass'] = [];
781 }
782 if (!in_array('posixGroup', $this->attributes['objectClass'])) {
783 $this->attributes['objectClass'][] = 'posixGroup';
784 }
785 return $errors;
786 }
787 if (isset($_POST['remObjectClass'])) {
788 $this->attributes['objectClass'] = array_delete(['posixGroup'], $this->attributes['objectClass']);
789 $attrs = $this->getManagedAttributes($this->getAccountContainer()->get_type()->getId());
790 foreach ($attrs as $name) {
791 if (isset($this->attributes[$name])) {
792 unset($this->attributes[$name]);
793 }
794 }
795 return $errors;
796 }
797 $modules = $this->getAccountContainer()->get_type()->getModules();
798 $typeId = $this->getAccountContainer()->get_type()->getId();
799 // skip processing if object class is not set
800 if (!$this->autoAddObjectClasses && (!isset($this->attributes['objectClass']) || !in_array('posixGroup', $this->attributes['objectClass']))) {
801 return $errors;
802 }
803 if ($this->manageCnAndDescription($modules)) {
804 $this->processMultiValueInputTextField('description', $errors);
805 }
806 if (isset($_POST['lockPassword'])) {
807 $this->attributes[$this->passwordAttrName][0] = pwd_disable($this->attributes[$this->passwordAttrName][0]);
808 }
809 if (isset($_POST['unlockPassword'])) {
810 $this->attributes[$this->passwordAttrName][0] = pwd_enable($this->attributes[$this->passwordAttrName][0]);
811 }
812 if (isset($_POST['removePassword'])) {
813 unset($this->attributes[$this->passwordAttrName]);
814 }
815 $this->changegids = isset($_POST['changegids']);
816 if (!isset($this->attributes['gidNumber'][0]) || ($this->attributes['gidNumber'][0] != $_POST['gidNumber'])) {
817 // Check if GID is valid. If none value was entered, the next usable value will be inserted
818 $this->attributes['gidNumber'][0] = $_POST['gidNumber'];
819 if ($this->attributes['gidNumber'][0] == '') {
820 // No id-number given, find free GID
821 if (!isset($this->orig['gidNumber'][0])) {
822 $newGID = $this->getNextGIDs(1, $errors, $this->getAccountContainer()->get_type());
823 if (is_array($newGID)) {
824 $this->attributes['gidNumber'][0] = (string) $newGID[0];
825 }
826 else {
827 $errors[] = $this->messages['gidNumber'][3];
828 }
829 }
830 else {
831 // old account -> return id-number which has been used
832 $this->attributes['gidNumber'][0] = $this->orig['gidNumber'][0];
833 }
834 }
835 else {
836 $gids = $this->getGIDs($this->getAccountContainer()->get_type());
837 // Check manual ID
838 if ($this->getAccountContainer()->isNewAccount || !isset($this->orig['gidNumber'][0]) || ($this->orig['gidNumber'][0] != $this->attributes['gidNumber'][0])) {
839 // check range
840 if ($this->moduleSettings['posixGroup_' . $typeId . '_gidGenerator'][0] == 'range') {
841 $minID = intval($this->moduleSettings['posixGroup_' . $typeId . '_minGID'][0]);
842 $maxID = intval($this->moduleSettings['posixGroup_' . $typeId . '_maxGID'][0]);
843 if (($this->attributes['gidNumber'][0] < $minID) || ($this->attributes['gidNumber'][0] > $maxID) || !is_numeric($this->attributes['gidNumber'][0])) {
844 $errors[] = ['ERROR', _('ID-Number'), sprintf(_('Please enter a value between %s and %s!'), $minID, $maxID)];
845 if (isset($this->orig['gidNumber'][0])) {
846 $this->attributes['gidNumber'][0] = $this->orig['gidNumber'][0];
847 }
848 else {
849 unset($this->attributes['gidNumber'][0]);
850 }
851 }
852 }
853 // id-number is in use and account is a new account
854 if ((in_array($this->attributes['gidNumber'][0], $gids)) && ($this->orig['gidNumber'][0] == '')) {
855 $errors[] = $this->messages['gidNumber'][4];
856 unset($this->attributes['gidNumber'][0]);
857 }
858 // id-number is in use, account is existing account and id-number is changed
859 if ((in_array($this->attributes['gidNumber'][0], $gids)) && ($this->orig['gidNumber'][0] != '') && ($this->orig['gidNumber'][0] != $this->attributes['gidNumber'][0])) {
860 $errors[] = $this->messages['gidNumber'][4];
861 $this->attributes['gidNumber'][0] = $this->orig['gidNumber'][0];
862 }
863 }
864 }
865 }
866 if ($this->manageCnAndDescription($modules)) {
867 $this->attributes['cn'][0] = $_POST['cn'];
868 if (preg_match('/^[A-Z]+$/', $_POST['cn'])) {
869 $errors[] = $this->messages['cn'][0];
870 }
871 // Check if Groupname contains only valid characters
872 if (!get_preg($this->attributes['cn'][0], 'groupname')) {
873 $errors[] = $this->messages['cn'][2];
874 }
875 // Create automatic useraccount with number if original user already exists
876 // Reset name to original name if new name is in use
877 // Set username back to original name if new group name is in use
878 if ($this->groupNameExists($this->attributes['cn'][0]) && ($this->orig['cn'][0] != '')) {
879 $this->attributes['cn'][0] = $this->orig['cn'][0];
880 }
881 // Change gid to a new gid until a free gid is found
882 else {
883 while ($this->groupNameExists($this->attributes['cn'][0])) {
884 // get last character of group name
885 $lastchar = substr($this->attributes['cn'][0], strlen($this->attributes['cn'][0]) - 1, 1);
886 // Last character is no number
887 if (!preg_match('/^(\d)+$/', $lastchar)) {
888 /* Last character is no number. Therefore we only have to
889 * add "2" to it.
890 */
891 $this->attributes['cn'][0] .= '2';
892 }
893 else {
894 /* Last character is a number -> we have to increase the number until we've
895 * found a groupname with trailing number which is not in use.
896 *
897 * $i will show us were we have to split groupname so we get a part
898 * with the groupname and a part with the trailing number
899 */
900 $i = strlen($this->attributes['cn'][0]) - 1;
901 // Set $i to the last character which is a number in $account_new->general_username
902 while (true) {
903 if (preg_match('/^(\d)+$/', substr($this->attributes['cn'][0], $i, strlen($this->attributes['cn'][0]) - $i))) {
904 $i--;
905 }
906 else {
907 break;
908 }
909 }
910 // increase last number with one
911 $firstchars = substr($this->attributes['cn'][0], 0, $i + 1);
912 $lastchars = substr($this->attributes['cn'][0], $i + 1, strlen($this->attributes['cn'][0]) - $i);
913 // Put username together
914 $this->attributes['cn'][0] = $firstchars . (intval($lastchars) + 1);
915 }
916 }
917 }
918 // Show warning if lam has changed group name
919 if ($this->attributes['cn'][0] != $_POST['cn']) {
920 $errors[] = $this->messages['cn'][1];
921 }
922 }
923 // show info when gidnumber has changed
924 if (isset($this->orig['gidNumber'][0]) && ($this->orig['gidNumber'][0] != $this->attributes['gidNumber'][0])
925 && ($this->orig['gidNumber'][0] != '') && !$this->changegids) {
926 $errors[] = $this->messages['gidNumber'][0];
927 }
928 // Return error-messages
929 return $errors;
930 }
931
932
933 /**
934 * Processes user input of the user selection page.
935 * It checks if all input values are correct and updates the associated LDAP attributes.
936 *
937 * @return string[][] list of info/error messages
938 */
939 public function process_user(): array {
940 $return = [];
941 if (!isset($this->attributes['memberUid'])) {
942 $this->attributes['memberUid'] = [];
943 }
944 if (isset($_POST['members_2']) && isset($_POST['members_left'])) { // Add groups to list
945 // add new group
946 $this->attributes['memberUid'] = @array_merge($this->attributes['memberUid'], $_POST['members_2']);
947 }
948 elseif (isset($_POST['members_1']) && isset($_POST['members_right'])) { // remove groups from list
949 $this->attributes['memberUid'] = array_delete($_POST['members_1'], $this->attributes['memberUid']);
950 }
951 // sync users
952 elseif (isset($_POST['syncGON'])) {
953 $return = array_merge($return, $this->syncGon());
954 }
955 // sync Windows
956 elseif (isset($_POST['syncWindows'])) {
957 $return = array_merge($return, $this->syncWindows());
958 }
959 return $return;
960 }
961
962 /**
963 * Syncs with group of names members.
964 *
965 * @param bool $forceDelete force deletion of members
966 * @return string[][] list of status messages
967 */
968 protected function syncGon($forceDelete = false): array {
969 $delete = $forceDelete || (isset($_POST['syncGON_delete']) && ($_POST['syncGON_delete'] == 'on'));
970 $return = [];
971 $gon = $this->getAccountContainer()->getAccountModule('groupOfNames');
972 if ($gon == null) {
973 $gon = $this->getAccountContainer()->getAccountModule('groupOfUniqueNames');
974 }
975 if ($gon == null) {
976 $gon = $this->getAccountContainer()->getAccountModule('groupOfMembers');
977 }
978 if ($gon == null) {
979 return $return;
980 }
981 if (!isset($this->attributes['memberUid'])) {
982 $this->attributes['memberUid'] = [];
983 }
984 $memberDNs = $gon->getMembers();
985 $users = $this->getUsers();
986 $oldValues = $this->attributes['memberUid'];
987 if ($delete) {
988 $this->attributes['memberUid'] = [];
989 }
990 foreach ($memberDNs as $dn) {
991 foreach ($users as $userName => $userAttrs) {
992 if ($userAttrs['dn'] != $dn) {
993 continue;
994 }
995 $this->attributes['memberUid'][] = $userName;
996 }
997 }
998 $added = array_delete($oldValues, $this->attributes['memberUid']);
999 if (!empty($added)) {
1000 $return[] = ['INFO', _('Added users'), htmlspecialchars(implode(', ', $added))];
1001 }
1002 if ($delete) {
1003 $deleted = array_delete($this->attributes['memberUid'], $oldValues);
1004 if (!empty($deleted)) {
1005 $return[] = ['INFO', _('Removed users'), htmlspecialchars(implode(', ', $deleted))];
1006 }
1007 }
1008 return $return;
1009 }
1010
1011 /**
1012 * Syncs with Windows.
1013 *
1014 * @return string[][] list of status messages
1015 */
1016 protected function syncWindows(): array {
1017 $delete = isset($_POST['syncWindows_delete']) && ($_POST['syncWindows_delete'] == 'on');
1018 $return = [];
1019 $windows = $this->getAccountContainer()->getAccountModule('windowsGroup');
1020 if (!isset($this->attributes['memberUid'])) {
1021 $this->attributes['memberUid'] = [];
1022 }
1023 $windowsAttributes = $windows->getAttributes();
1024 $memberDNs = [];
1025 if (!empty($windowsAttributes['member'])) {
1026 $memberDNs = $windowsAttributes['member'];
1027 }
1028 $users = $this->getUsers();
1029 $oldValues = $this->attributes['memberUid'];
1030 if ($delete) {
1031 $this->attributes['memberUid'] = [];
1032 }
1033 foreach ($memberDNs as $dn) {
1034 foreach ($users as $userName => $userAttrs) {
1035 if ($userAttrs['dn'] != $dn) {
1036 continue;
1037 }
1038 $this->attributes['memberUid'][] = $userName;
1039 }
1040 }
1041 $added = array_delete($oldValues, $this->attributes['memberUid']);
1042 if (!empty($added)) {
1043 $return[] = ['INFO', _('Added users'), htmlspecialchars(implode(', ', $added))];
1044 }
1045 if ($delete) {
1046 $deleted = array_delete($this->attributes['memberUid'], $oldValues);
1047 if (!empty($deleted)) {
1048 $return[] = ['INFO', _('Removed users'), htmlspecialchars(implode(', ', $deleted))];
1049 }
1050 }
1051 return $return;
1052 }
1053
1054 /**
1055 * {@inheritDoc}
1056 */
1057 public function save_attributes(): array {
1058 // skip saving if account is based on another structural object class
1059 if ($this->is_base_module() && !$this->getAccountContainer()->isNewAccount && !in_array('posixGroup', $this->getAccountContainer()->attributes_orig['objectClass'])) {
1060 return [];
1061 }
1062 if (!in_array('posixGroup', $this->attributes['objectClass']) && !in_array('posixGroup', $this->orig['objectClass'])) {
1063 // skip saving if the extension was not added/modified
1064 return [];
1065 }
1066 // auto sync group members
1067 if ($this->isBooleanConfigOptionSet('posixGroup_autoSyncGon')) {
1068 $this->syncGon(true);
1069 }
1070 $return = $this->getAccountContainer()->save_module_attributes($this->attributes, $this->orig);
1071 // Change gids of users and hosts?
1072 if ($this->changegids) {
1073 // find all accounts to change
1074 $result = searchLDAPByFilter('(&(objectClass=posixAccount)(gidNumber=' . $this->orig['gidNumber'][0] . '))', ['dn'], ['user', 'host']);
1075 if (count($result) > 0) {
1076 for ($i = 0; $i < count($result); $i++) {
1077 $return[$result[$i]['dn']]['modify']['gidNumber'][0] = $this->attributes['gidNumber'][0];
1078 }
1079 }
1080 }
1081 return $return;
1082 }
1083
1084 /**
1085 * {@inheritDoc}
1086 */
1087 public function load_profile(array $profile): void {
1088 // profile mappings in meta data
1089 parent::load_profile($profile);
1090 // add extension
1091 if (isset($profile['posixGroup_addExt'][0]) && ($profile['posixGroup_addExt'][0] == "true")
1092 && !in_array('posixGroup', $this->attributes['objectClass'])) {
1093 $this->attributes['objectClass'][] = 'posixGroup';
1094 }
1095 if ($this->manageCnAndDescription($this->getAccountContainer()->get_type()->getModules()) && !empty($profile['posixGroup_description'][0])) {
1096 $this->attributes['description'] = $profile['posixGroup_description'];
1097 }
1098 }
1099
1100 /**
1101 * Returns one or more free GID numbers.
1102 *
1103 * @param integer $count Number of needed free GIDs.
1104 * @param array<string|string[]>[] $errors list of error messages where errors can be added
1105 * @param ConfiguredType $type account type
1106 * @return int[]|null Null if no GIDs are free else an array of free GIDs.
1107 */
1108 public function getNextGIDs($count, &$errors, $type): ?array {
1109 $typeId = $type->getId();
1110 // check if UIDs should be taken from Samba pool entry
1111 if (isset($this->moduleSettings['posixGroup_' . $typeId . '_gidGenerator']) && ($this->moduleSettings['posixGroup_' . $typeId . '_gidGenerator'][0] == 'sambaPool')) {
1112 return $this->getNextSambaPoolGIDs($count, $typeId);
1113 }
1114 // check if UIDs should be taken from domain info entry
1115 if (isset($this->moduleSettings['posixGroup_' . $typeId . '_gidGenerator']) && ($this->moduleSettings['posixGroup_' . $typeId . '_gidGenerator'][0] == 'windowsDomain')) {
1116 return $this->getNextDomainInfoGIDs($count, $typeId);
1117 }
1118 // use magic number
1119 if (isset($this->moduleSettings['posixGroup_' . $typeId . '_gidGenerator']) && ($this->moduleSettings['posixGroup_' . $typeId . '_gidGenerator'][0] == 'magicNumber')) {
1120 $return = [];
1121 for ($i = 0; $i < $count; $i++) {
1122 $return[] = intval($this->moduleSettings['posixGroup_' . $typeId . '_magicNumber'][0]);
1123 }
1124 return $return;
1125 }
1126 $ret = [];
1127 $minID = intval($this->moduleSettings['posixGroup_' . $typeId . '_minGID'][0]);
1128 $maxID = intval($this->moduleSettings['posixGroup_' . $typeId . '_maxGID'][0]);
1129 $gidList = $this->getGIDs($type);
1130 $gids = [];
1131 foreach ($gidList as $gid) {
1132 if (($gid <= $maxID) && ($gid >= $minID)) {
1133 $gids[] = intval($gid); // ignore GIDs > maxID and GIDs < minID
1134 }
1135 }
1136 for ($i = 0; $i < $count; $i++) {
1137 if (count($gids) !== 0) {
1138 // there already are some GIDs
1139 // store highest id-number
1140 $id = $gids[count($gids) - 1];
1141 // Return minimum allowed id-number if all found id-numbers are too low
1142 if ($id < $minID) {
1143 $ret[] = $minID;
1144 $gids[] = $minID;
1145 }
1146 // return highest used id-number + 1 if it's still in valid range
1147 elseif ($id < $maxID) {
1148 $ret[] = $id + 1;
1149 $gids[] = $id + 1;
1150 }
1151 // find free numbers between existing ones
1152 else {
1153 $k = intval($minID);
1154 while (in_array($k, $gids)) {
1155 $k++;
1156 }
1157 if ($k > $maxID) {
1158 return null;
1159 }
1160 else {
1161 $ret[] = $k;
1162 $gids[] = $k;
1163 sort($gids, SORT_NUMERIC);
1164 }
1165 // show warning message
1166 $errors[] = $this->messages['gidNumber'][2];
1167 }
1168 }
1169 else {
1170 // return minimum allowed id-number if no id-numbers are found
1171 $ret[] = $minID;
1172 $gids[] = $minID;
1173 }
1174 }
1175 return $ret;
1176 }
1177
1178 /**
1179 * Gets the free GID numbers from an Samba pool entry in LDAP.
1180 *
1181 * @param integer $count number of needed free GIDs.
1182 * @param string $typeId account type id
1183 * @return int[]|null null if no GIDs are free else an array of free GIDs
1184 */
1185 private function getNextSambaPoolGIDs($count, $typeId) {
1186 $dn = $this->moduleSettings['posixGroup_' . $typeId . '_sambaIDPoolDN'][0];
1187 $attrs = ldapGetDN($dn, ['gidNumber']);
1188 if (isset($attrs['gidnumber'][0]) && ($attrs['gidnumber'][0] != '')) {
1189 $newValue = intval($attrs['gidnumber'][0]) + $count;
1190 $ldapHandle = $_SESSION['ldap']->server();
1191 ldap_modify($ldapHandle, $dn, ['gidnumber' => [$newValue]]);
1192 logNewMessage(LOG_DEBUG, 'Updated Samba ID pool ' . $dn . ' with GID number ' . $newValue . ' and LDAP code ' . ldap_errno($ldapHandle));
1193 if (ldap_errno($ldapHandle) !== 0) {
1194 logNewMessage(LOG_NOTICE, 'Updating Samba ID pool ' . $dn . ' with GID number ' . $newValue . ' failed. ' . ldap_error($ldapHandle));
1195 return null;
1196 }
1197 $result = [];
1198 for ($i = 0; $i < $count; $i++) {
1199 $result[] = intval($attrs['gidnumber'][0]) + $i;
1200 }
1201 return $result;
1202 }
1203 return null;
1204 }
1205
1206 /**
1207 * Gets the free GID numbers from an Windows domain info entry in LDAP.
1208 *
1209 * @param integer $count number of needed free GIDs.
1210 * @param string $typeId account type id
1211 * @return int[]|null null if no GIDs are free else an array of free GIDs
1212 */
1213 private function getNextDomainInfoGIDs($count, $typeId) {
1214 $dn = $this->moduleSettings['posixGroup_' . $typeId . '_windowsIDPoolDN'][0];
1215 $attrs = ldapGetDN($dn, ['msSFU30MaxGidNumber']);
1216 if (isset($attrs['mssfu30maxgidnumber'][0]) && ($attrs['mssfu30maxgidnumber'][0] != '')) {
1217 $newValue = intval($attrs['mssfu30maxgidnumber'][0]) + $count;
1218 $ldapHandle = $_SESSION['ldap']->server();
1219 ldap_modify($ldapHandle, $dn, ['mssfu30maxgidnumber' => [$newValue]]);
1220 logNewMessage(LOG_DEBUG, 'Updated domain info ' . $dn . ' with GID number ' . $newValue . ' and LDAP code ' . ldap_errno($ldapHandle));
1221 if (ldap_errno($ldapHandle) !== 0) {
1222 logNewMessage(LOG_NOTICE, 'Updating domain info ' . $dn . ' with GID number ' . $newValue . ' failed. ' . ldap_error($ldapHandle));
1223 return null;
1224 }
1225 $result = [];
1226 for ($i = 0; $i < $count; $i++) {
1227 $result[] = intval($attrs['mssfu30maxgidnumber'][0]) + $i;
1228 }
1229 return $result;
1230 }
1231 return null;
1232 }
1233
1234 /**
1235 * {@inheritDoc}
1236 */
1237 public function managesPasswordAttributes(): bool {
1238 return true;
1239 }
1240
1241 /**
1242 * {@inheritDoc}
1243 */
1244 public function supportsForcePasswordChange(): bool {
1245 return false;
1246 }
1247
1248 /**
1249 * {@inheritDoc}
1250 */
1251 public function passwordChangeRequested(string $password, array $modules, bool $forcePasswordChange): array {
1252 if (!in_array(static::class, $modules)) {
1253 return [];
1254 }
1255 $this->attributes[$this->passwordAttrName][0] = pwd_hash($password, true, $this->moduleSettings['posixAccount_pwdHash'][0]);
1256 return [];
1257 }
1258
1259 /**
1260 * Returns a list of existing GID numbers.
1261 *
1262 * @param ConfiguredType $type account type
1263 * @return string[] list of GID numbers
1264 */
1265 private function getGIDs(ConfiguredType $type): array {
1266 if ($this->cachedGIDList !== null) {
1267 return $this->cachedGIDList;
1268 }
1269 $this->cachedGIDList = [];
1270 $attrs = ['gidNumber'];
1271 $filter = '(&(objectClass=posixGroup)(gidNumber=*))';
1272 $suffix = $type->getSuffix();
1273 $typeId = $type->getId();
1274 if (!empty($this->moduleSettings['posixGroup_' . $typeId . '_gidCheckSuffix'][0])) {
1275 $suffix = $this->moduleSettings['posixGroup_' . $typeId . '_gidCheckSuffix'][0];
1276 }
1277 $result = searchLDAP($suffix, $filter, $attrs);
1278 for ($i = 0; $i < count($result); $i++) {
1279 $this->cachedGIDList[] = $result[$i]['gidnumber'][0];
1280 }
1281 sort($this->cachedGIDList, SORT_NUMERIC);
1282 return $this->cachedGIDList;
1283 }
1284
1285 /**
1286 * Returns a list of existing users and their GID numbers and cn.
1287 *
1288 * @return array<string, array<string, string>> list in format array(uid => array('gid' => 123, 'cn' => 'Some user'))
1289 */
1290 protected function getUsers(): array {
1291 if ($this->cachedUserToGIDList !== null) {
1292 return $this->cachedUserToGIDList;
1293 }
1294 $this->cachedUserToGIDList = [];
1295 $filter = '(&(objectClass=posixAccount)(gidNumber=*)(uid=*))';
1296 if ($this->isWindows()) {
1297 $filter = '(&(objectClass=user)(gidNumber=*)(uid=*))';
1298 }
1299 $result = searchLDAPByFilter($filter, ['uid', 'gidNumber', 'cn'], ['user']);
1300 $resultCount = count($result);
1301 for ($i = 0; $i < $resultCount; $i++) {
1302 $this->cachedUserToGIDList[$result[$i]['uid'][0]] = [
1303 'gid' => $result[$i]['gidnumber'][0],
1304 'cn' => $result[$i]['cn'][0],
1305 'dn' => $result[$i]['dn']];
1306 }
1307 logNewMessage(LOG_DEBUG, 'Found ' . $resultCount . ' Unix users.');
1308 return $this->cachedUserToGIDList;
1309 }
1310
1311 /**
1312 * Checks if the given group name already exists in LDAP.
1313 *
1314 * @param String $groupName group name
1315 * @return boolean true if already exists
1316 */
1317 private function groupNameExists($groupName) {
1318 return in_array($groupName, $this->getGroupNames());
1319 }
1320
1321 /**
1322 * Returns a list of all group names in LDAP.
1323 *
1324 * @return string[] group names
1325 */
1326 private function getGroupNames(): array {
1327 if ($this->cachedGroupNameList !== null) {
1328 return $this->cachedGroupNameList;
1329 }
1330 $this->cachedGroupNameList = [];
1331 $attrs = ['cn'];
1332 $filter = '(&(objectClass=posixGroup)(cn=*))';
1333 $suffix = $this->getAccountContainer()->get_type()->getSuffix();
1334 $typeId = $this->getAccountContainer()->get_type()->getId();
1335 if (!empty($this->moduleSettings['posixGroup_' . $typeId . '_gidCheckSuffix'][0])) {
1336 $suffix = $this->moduleSettings['posixGroup_' . $typeId . '_gidCheckSuffix'][0];
1337 }
1338 $result = searchLDAP($suffix, $filter, $attrs);
1339 for ($i = 0; $i < count($result); $i++) {
1340 $this->cachedGroupNameList[] = $result[$i]['cn'][0];
1341 }
1342 return $this->cachedGroupNameList;
1343 }
1344
1345 /**
1346 * Returns if the Windows module is active.
1347 *
1348 * @return boolean is Windows
1349 */
1350 private function isWindows() {
1351 return (in_array('windowsGroup', $this->getAccountContainer()->get_type()->getModules()));
1352 }
1353
1354 /**
1355 * Returns if cn and description attributes should be managed.
1356 *
1357 * @param string[] $modules modules
1358 * @return boolean manage cn+description
1359 */
1360 protected function manageCnAndDescription($modules) {
1361 return true;
1362 }
1363
1364 /**
1365 * @inheritDoc
1366 */
1367 public function supportsPasswordQuickChangePage(): bool {
1368 return false;
1369 }
1370
1371 /**
1372 * @inheritDoc
1373 */
1374 public function addPasswordQuickChangeAccountDetails(htmlResponsiveRow $row): void {
1375 // no details
1376 }
1377
1378 /**
1379 * @inheritDoc
1380 */
1381 public function getPasswordQuickChangeOptions(bool $forcePasswordChangeByDefault): array {
1382 return [];
1383 }
1384
1385 /**
1386 * @inheritDoc
1387 */
1388 public function getPasswordQuickChangeChanges(string $password): array {
1389 return [];
1390 }
1391
1392 /**
1393 * @inheritDoc
1394 */
1395 public function getPasswordQuickChangePasswordStrengthUserName(): ?string {
1396 return null;
1397 }
1398
1399 /**
1400 * @inheritDoc
1401 */
1402 public function getPasswordQuickChangePasswordStrengthAttributes(): array {
1403 return [];
1404 }
1405
1406 /**
1407 * @inheritDoc
1408 */
1409 public function getPasswordQuickChangeIsPasswordInHistory(string $password): bool {
1410 return false;
1411 }
1412
1413 /**
1414 * @inheritDoc
1415 */
1416 public function getListAttributeDescriptions(ConfiguredType $type): array {
1417 return [
1418 "cn" => _("Name"),
1419 "description" => _("Group description"),
1420 "gidnumber" => _("GID number"),
1421 "memberuid" => _("Group members"),
1422 ];
1423 }
1424
1425 }