Debian Codegraph @

lib/modules/pykotaGroup.inc

raw
1 <?php
2
3 use LAM\TYPES\ConfiguredType;
4 use LAM\TYPES\TypeManager;
5
6 /*
7
8 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
9 Copyright (C) 2013 - 2026 Roland Gruber
10
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2 of the License, or
14 (at your option) any later version.
15
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 */
25
26 /**
27 * Manages PyKota group accounts.
28 *
29 * @package modules
30 * @author Roland Gruber
31 */
32
33 /**
34 * Manages PyKota group accounts.
35 *
36 * @package modules
37 */
38 class pykotaGroup extends baseModule {
39
40 /**
41 * These attributes will be ignored by default if a new account is copied from an existing one.
42 */
43 private const ATTRIBUTES_TO_IGNORE_ON_COPY = ['pykotaGroupName'];
44
45 /** @var string[]|null $cnCache cache for cn attribute */
46 private ?array $cnCache = null;
47 /** @var string[]|null $pykotaGroupNameCache cache for pykotaGroupName attribute */
48 private ?array $pykotaGroupNameCache = null;
49 /** @var array<string, string> $limitOptions list of limit options label => value */
50 private array $limitOptions;
51
52 /**
53 * Returns if this module also manages the structural object class pykotaObject.
54 * This is overridden by a submodule that must provide the structural object class.
55 *
56 * @return bool structural usage
57 */
58 public function isStructural(): bool {
59 return false;
60 }
61
62 /**
63 * Creates a new pykotaGroup object.
64 *
65 * @param string $scope account type (user, group, host)
66 */
67 public function __construct($scope) {
68 $this->limitOptions = [
69 _('Quota') => 'quota',
70 _('Balance') => 'balance',
71 _('No quota') => 'noquota',
72 _('Free printing') => 'nochange',
73 _('Deny printing') => 'noprint',
74 ];
75 // call parent constructor
76 parent::__construct($scope);
77 $this->autoAddObjectClasses = $this->isStructural();
78 }
79
80 /**
81 * {@inheritDoc}
82 */
83 public function can_manage(): bool {
84 return $this->get_scope() === 'group';
85 }
86
87 /**
88 * {@inheritDoc}
89 */
90 public function get_metaData(): array {
91 $return = [];
92 // icon
93 $return['icon'] = 'printer.svg';
94 // alias name
95 $return["alias"] = _("PyKota");
96 // this is a base module
97 $return["is_base"] = $this->isStructural();
98 // LDAP filter
99 $return["ldap_filter"] = ['or' => "(objectClass=pykotaGroup)"];
100 // module dependencies
101 $return['dependencies'] = ['depends' => [], 'conflicts' => []];
102 // managed object classes
103 $return['objectClasses'] = ['pykotaGroup'];
104 // managed attributes
105 $return['attributes'] = ['pykotaLimitBy', 'pykotaGroupName'];
106 // help Entries
107 $return['help'] = [
108 'cn' => [
109 "Headline" => _("Common name"), 'attr' => 'cn',
110 "Text" => _("Group name of the group which should be created. Valid characters are: a-z, A-Z, 0-9 and .-_ .")
111 ],
112 'description' => [
113 "Headline" => _("Description"), 'attr' => 'description',
114 "Text" => _("Group description.")
115 ],
116 'pykotaGroupName' => [
117 "Headline" => _("PyKota group name"), 'attr' => 'pykotaGroupName',
118 "Text" => _("Group name that is used for PyKota.")
119 ],
120 'pykotaLimitBy' => [
121 "Headline" => _("Limit type"), 'attr' => 'pykotaLimitBy',
122 "Text" => _("Specifies the type of limit for printing if any. Please note that in contrast to \"Free printing\" the option \"No quota\" includes accounting.")
123 ],
124 'autoAdd' => [
125 "Headline" => _("Automatically add this extension"),
126 "Text" => _("This will enable the extension automatically if this profile is loaded.")
127 ],
128 ];
129 // profile options
130 $profileContainer = new htmlResponsiveRow();
131 $pykotaLimitByProfileOption = new htmlResponsiveSelect('pykotaGroup_pykotaLimitBy', $this->limitOptions, [], _('Limit type'), 'pykotaLimitBy');
132 $pykotaLimitByProfileOption->setHasDescriptiveElements(true);
133 $pykotaLimitByProfileOption->setSortElements(false);
134 $profileContainer->add($pykotaLimitByProfileOption);
135 if (!$this->isStructural()) {
136 $profileContainer->add(new htmlResponsiveInputCheckbox('pykotaGroup_addExt', false, _('Automatically add this extension'), 'autoAdd'));
137 }
138 $return['profile_options'] = $profileContainer;
139 $return['profile_mappings']['pykotaGroup_pykotaLimitBy'] = 'pykotaLimitBy';
140 // upload fields
141 $return['upload_columns'] = [
142 [
143 'name' => 'pykotaGroup_pykotaGroupName',
144 'description' => _('PyKota group name'),
145 'help' => 'pykotaGroupName',
146 'example' => _('adminstrators'),
147 'unique' => true,
148 ]
149 ];
150 $return['upload_columns'][] = [
151 'name' => 'pykotaGroup_pykotaLimitBy',
152 'description' => _('Limit type'),
153 'help' => 'pykotaLimitBy',
154 'example' => _('Quota'),
155 'default' => _('Quota'),
156 'values' => implode(', ', array_keys($this->limitOptions))
157 ];
158 // available PDF fields
159 $return['PDF_fields'] = [
160 'pykotaGroupName' => _('PyKota group name'),
161 'pykotaLimitBy' => _('Limit type'),
162 ];
163 return $return;
164 }
165
166 /**
167 * {@inheritDoc}
168 */
169 protected function load_Messages(): void {
170 $this->messages['cn'][0] = ['ERROR', _('Group name'), _('Group name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
171 $this->messages['cn'][1] = ['ERROR', _('Account %s:') . ' pykotaGroup_cn', _('Group name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
172 $this->messages['cn'][2] = ['ERROR', _('Group name'), _('Group name already exists!')];
173 $this->messages['cn'][3] = ['ERROR', _('Account %s:') . ' pykotaGroup_cn', _('Group name already exists!')];
174 $this->messages['pykotaGroupName'][0] = ['ERROR', _('PyKota group name'), _('Group name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
175 $this->messages['pykotaGroupName'][1] = ['ERROR', _('Account %s:') . ' pykotaGroup_pykotaGroupName', _('Group name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
176 $this->messages['pykotaGroupName'][2] = ['ERROR', _('PyKota group name'), _('Group name already exists!')];
177 $this->messages['pykotaGroupName'][3] = ['ERROR', _('Account %s:') . ' pykotaGroup_pykotaGroupName', _('Group name already exists!')];
178 $this->messages['pykotaLimitBy'][0] = ['ERROR', _('Account %s:') . ' pykotaGroup_pykotaLimitBy', _('Please enter a valid limit type.')];
179 }
180
181 /**
182 * {@inheritDoc}
183 */
184 public function loadAttributesFromAccountCopy(array $ldapAttributes, array $attributesToIgnore = []): void {
185 parent::loadAttributesFromAccountCopy($ldapAttributes, array_merge(baseModule::ATTRIBUTES_TO_IGNORE_ON_COPY_DEFAULT, self::ATTRIBUTES_TO_IGNORE_ON_COPY));
186 }
187
188 /**
189 * {@inheritDoc}
190 */
191 public function display_html_attributes(): htmlElement|array {
192 $container = new htmlResponsiveRow();
193 $modules = $this->getAccountContainer()->get_type()->getModules();
194 if ($this->isStructural() || (isset($this->attributes['objectClass']) && in_array('pykotaGroup', $this->attributes['objectClass']))) {
195 // cn
196 if ($this->isUnixOrGonInactive($modules)) {
197 $this->addSimpleInputTextField($container, 'cn', _('Group name'), true);
198 }
199 // pykotaGroupName
200 $this->addSimpleInputTextField($container, 'pykotaGroupName', _('Pykota group name'));
201 // limit by
202 $limitOption = 'quota';
203 if (!empty($this->attributes['pykotaLimitBy'][0])) {
204 $limitOption = $this->attributes['pykotaLimitBy'][0];
205 }
206 $limitSelect = new htmlResponsiveSelect('pykotaLimitBy', $this->limitOptions, [$limitOption], _('Limit type'), 'pykotaLimitBy');
207 $limitSelect->setHasDescriptiveElements(true);
208 $limitSelect->setSortElements(false);
209 $container->add($limitSelect);
210 // description
211 if ($this->isUnixOrGonInactive($modules)) {
212 $this->addMultiValueInputTextField($container, 'description', _('Description'), false, null, true);
213 }
214 // remove button
215 if (!$this->isStructural()) {
216 $container->addVerticalSpacer('2rem');
217 $remButton = new htmlButton('remObjectClass', _('Remove PyKota extension'));
218 $remButton->setCSSClasses(['lam-danger']);
219 $container->add($remButton, 12, 12, 12, 'text-center');
220 }
221 }
222 else {
223 // add button
224 $container->add(new htmlButton('addObjectClass', _('Add PyKota extension')));
225 }
226 return $container;
227 }
228
229 /**
230 * {@inheritDoc}
231 */
232 public function process_attributes(): array {
233 $errors = [];
234 if (isset($_POST['addObjectClass'])) {
235 if (!isset($this->attributes['objectClass'])) {
236 $this->attributes['objectClass'] = [];
237 }
238 if (!in_array('pykotaGroup', $this->attributes['objectClass'])) {
239 $this->attributes['objectClass'][] = 'pykotaGroup';
240 }
241 if (!isset($this->attributes['pykotaGroupName'][0])) {
242 $this->attributes['pykotaGroupName'][0] = $this->getCurrentGroupName();
243 }
244 return $errors;
245 }
246 $modules = $this->getAccountContainer()->get_type()->getModules();
247 if (isset($_POST['remObjectClass'])) {
248 $this->attributes['objectClass'] = array_delete(['pykotaGroup'], $this->attributes['objectClass']);
249 $attrs = ['pykotaLimitBy', 'pykotaGroupName'];
250 if ($this->isUnixOrGonInactive($modules)) {
251 $attrs[] = 'description';
252 }
253 if ($this->isUnixOrGonInactive($modules)) {
254 $attrs[] = 'cn';
255 }
256 foreach ($attrs as $name) {
257 if (isset($this->attributes[$name])) {
258 unset($this->attributes[$name]);
259 }
260 }
261 return $errors;
262 }
263 // skip processing if object class is not set
264 if (!isset($this->attributes['objectClass']) || !in_array('pykotaGroup', $this->attributes['objectClass'])) {
265 return $errors;
266 }
267 // cn
268 if ($this->isUnixOrGonInactive($modules)) {
269 if (isset($_POST['cn']) && ($_POST['cn'] != '')) {
270 if (!get_preg($_POST['cn'], 'groupname')) {
271 $errors[] = $this->messages['cn'][0];
272 }
273 else {
274 $this->attributes['cn'][0] = $_POST['cn'];
275 if ((!isset($this->orig['cn'][0]) || ($this->attributes['cn'][0] != $this->orig['cn'][0]))
276 && $this->cnExists($_POST['cn'])) {
277 $errors[] = $this->messages['cn'][2];
278 }
279 }
280 }
281 elseif (isset($this->attributes['cn'][0])) {
282 unset($this->attributes['cn'][0]);
283 }
284 }
285 // PyKota group name
286 if (!empty($_POST['pykotaGroupName'])) {
287 if (!get_preg($_POST['pykotaGroupName'], 'groupname')) {
288 $errors[] = $this->messages['pykotaGroupName'][0];
289 }
290 else {
291 $this->attributes['pykotaGroupName'][0] = $_POST['pykotaGroupName'];
292 if ((!isset($this->orig['pykotaGroupName'][0]) || ($this->attributes['pykotaGroupName'][0] != $this->orig['pykotaGroupName'][0]))
293 && $this->pykotaGroupNameExists($_POST['pykotaGroupName'])) {
294 $errors[] = $this->messages['pykotaGroupName'][2];
295 }
296 }
297 }
298 else {
299 $this->attributes['pykotaGroupName'][0] = $this->getCurrentGroupName();
300 }
301 // limit by
302 $this->attributes['pykotaLimitBy'][0] = $_POST['pykotaLimitBy'];
303 // description
304 if ($this->isUnixOrGonInactive($modules)) {
305 $this->processMultiValueInputTextField('description', $errors);
306 }
307 return $errors;
308 }
309
310 /**
311 * {@inheritDoc}
312 */
313 public function save_attributes(): array {
314 if (!in_array('pykotaGroup', $this->attributes['objectClass']) && !in_array('pykotaGroup', $this->orig['objectClass'])) {
315 // skip saving if the extension was not added/modified
316 return [];
317 }
318 return parent::save_attributes();
319 }
320
321 /**
322 * {@inheritDoc}
323 */
324 public function getManagedAttributes(string $typeId): array {
325 $attrs = parent::getManagedAttributes($typeId);
326 $typeManager = new TypeManager();
327 if ($this->isUnixOrGonInactive($typeManager->getConfiguredType($typeId)->getModules())) {
328 $attrs[] = 'cn';
329 $attrs[] = 'description';
330 }
331 return $attrs;
332 }
333
334 /**
335 * {@inheritDoc}
336 */
337 public function module_complete(): bool {
338 if (in_array('pykotaGroup', $this->attributes['objectClass'])) {
339 // require cn
340 $cn = $this->getCurrentGroupName();
341 return !empty($cn);
342 }
343 return true;
344 }
345
346 /**
347 * {@inheritDoc}
348 */
349 public function load_profile(array $profile): void {
350 // profile mappings in meta data
351 parent::load_profile($profile);
352 // add extension
353 if (isset($profile['pykotaGroup_addExt'][0])
354 && ($profile['pykotaGroup_addExt'][0] == "true")
355 && !in_array('pykotaGroup', $this->attributes['objectClass'])) {
356 $this->attributes['objectClass'][] = 'pykotaGroup';
357 }
358 }
359
360 /**
361 * {@inheritDoc}
362 */
363 public function get_uploadColumns(array $selectedModules, ConfiguredType $type): array {
364 $return = parent::get_uploadColumns($selectedModules, $type);
365 if ($this->isUnixOrGonInactive($selectedModules)) {
366 $return[] = [
367 'name' => 'pykotaGroup_cn',
368 'description' => _('Common name'),
369 'help' => 'cn',
370 'example' => _('adminstrators'),
371 'required' => true,
372 ];
373 $return[] = [
374 'name' => 'pykotaGroup_description',
375 'description' => _('Description'),
376 'help' => 'description',
377 'example' => _('Administrators group'),
378 ];
379 }
380 return $return;
381 }
382
383 /**
384 * {@inheritDoc}
385 */
386 public function build_uploadAccounts(array $rawAccounts, array $ids, array &$partialAccounts, array $selectedModules, ConfiguredType &$type): array {
387 $messages = [];
388 for ($i = 0; $i < count($rawAccounts); $i++) {
389 // add object classes
390 if (!in_array('pykotaGroup', $partialAccounts[$i]['objectClass'])) {
391 $partialAccounts[$i]['objectClass'][] = 'pykotaGroup';
392 }
393 if ($this->isStructural() && !in_array('pykotaObject', $partialAccounts[$i]['objectClass'])) {
394 $partialAccounts[$i]['objectClass'][] = 'pykotaObject';
395 }
396 // cn
397 if ($this->isUnixOrGonInactive($selectedModules) && !empty($rawAccounts[$i][$ids['pykotaGroup_cn']])) {
398 if (!get_preg($rawAccounts[$i][$ids['pykotaGroup_cn']], 'groupname')) {
399 $errMsg = $this->messages['cn'][1];
400 $errMsg[] = [$i];
401 $messages[] = $errMsg;
402 }
403 elseif ($this->cnExists($rawAccounts[$i][$ids['pykotaGroup_cn']])) {
404 $errMsg = $this->messages['cn'][3];
405 $errMsg[] = [$i];
406 $messages[] = $errMsg;
407 }
408 else {
409 $partialAccounts[$i]['cn'] = $rawAccounts[$i][$ids['pykotaGroup_cn']];
410 }
411 }
412 // description
413 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'pykotaGroup_description', 'description');
414 // PyKota group name
415 if (!empty($rawAccounts[$i][$ids['pykotaGroup_pykotaGroupName']])) {
416 if (!get_preg($rawAccounts[$i][$ids['pykotaGroup_pykotaGroupName']], 'groupname')) {
417 $errMsg = $this->messages['pykotaGroupName'][1];
418 $errMsg[] = [$i];
419 $messages[] = $errMsg;
420 }
421 elseif ($this->pykotaGroupNameExists($rawAccounts[$i][$ids['pykotaGroup_pykotaGroupName']])) {
422 $errMsg = $this->messages['pykotaGroupName'][3];
423 $errMsg[] = [$i];
424 $messages[] = $errMsg;
425 }
426 else {
427 $partialAccounts[$i]['pykotaGroupName'] = $rawAccounts[$i][$ids['pykotaGroup_pykotaGroupName']];
428 }
429 }
430 // limit by
431 if (!empty($rawAccounts[$i][$ids['pykotaGroup_pykotaLimitBy']])) {
432 if (isset($this->limitOptions[$rawAccounts[$i][$ids['pykotaGroup_pykotaLimitBy']]])) {
433 $partialAccounts[$i]['pykotaLimitBy'] = $this->limitOptions[$rawAccounts[$i][$ids['pykotaGroup_pykotaLimitBy']]];
434 }
435 else {
436 $errMsg = $this->messages['pykotaLimitBy'][0];
437 $errMsg[] = [$i];
438 $messages[] = $errMsg;
439 }
440 }
441 else {
442 $partialAccounts[$i]['pykotaLimitBy'] = 'quota';
443 }
444 }
445 return $messages;
446 }
447
448 /**
449 * {@inheritDoc}
450 */
451 public function get_pdfFields(string $typeId): array {
452 $fields = parent::get_pdfFields($typeId);
453 $typeManager = new TypeManager();
454 $modules = $typeManager->getConfiguredType($typeId)->getModules();
455 if ($this->isUnixOrGonInactive($modules)) {
456 $fields['cn'] = _('Common name');
457 $fields['description'] = _('Description');
458 }
459 return $fields;
460 }
461
462 /**
463 * {@inheritDoc}
464 */
465 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
466 $return = [];
467 $this->addSimplePDFField($return, 'cn', _('Common name'));
468 $this->addSimplePDFField($return, 'pykotaGroupName', _('PyKota group name'));
469 $this->addSimplePDFField($return, 'description', _('Description'));
470 $limitByOptions = array_flip($this->limitOptions);
471 $limitByValue = '';
472 if (!empty($this->attributes['pykotaLimitBy'][0]) && isset($limitByOptions[$this->attributes['pykotaLimitBy'][0]])) {
473 $limitByValue = $limitByOptions[$this->attributes['pykotaLimitBy'][0]];
474 }
475 $this->addPDFKeyValue($return, 'pykotaLimitBy', _('Limit type'), $limitByValue);
476 return $return;
477 }
478
479 /**
480 * Checks if the active modules contain Unix or group of names.
481 *
482 * @param string[] $modules modules
483 * @return bool not active
484 */
485 private function isUnixOrGonInactive($modules) {
486 return !in_array('posixGroup', $modules)
487 && !in_array('groupOfNames', $modules)
488 && !in_array('groupOfUniqueNames', $modules);
489 }
490
491 /**
492 * Returns if the given cn already exists.
493 *
494 * @param String $cn cn attribute value
495 * @return boolean cn exists
496 */
497 private function cnExists($cn) {
498 if ($this->cnCache === null) {
499 $this->loadGroupNameCache();
500 }
501 return in_array($cn, $this->cnCache);
502 }
503
504 /**
505 * Returns if the given pykotaGroupName already exists.
506 *
507 * @param String $pykotaGroupName pykotaGroupName attribute value
508 * @return boolean pykotaGroupName exists
509 */
510 private function pykotaGroupNameExists($pykotaGroupName) {
511 if ($this->pykotaGroupNameCache === null) {
512 $this->loadGroupNameCache();
513 }
514 return in_array($pykotaGroupName, $this->pykotaGroupNameCache);
515 }
516
517 /**
518 * Loads the list of group names into the cache.
519 */
520 private function loadGroupNameCache(): void {
521 $results = searchLDAPByFilter('(objectClass=pykotaGroup)', ['cn', 'pykotaGroupName'], [$this->get_scope()]);
522 $this->cnCache = [];
523 $this->pykotaGroupNameCache = [];
524 foreach ($results as $result) {
525 if (isset($result['cn'][0])) {
526 $this->cnCache[] = $result['cn'][0];
527 }
528 if (isset($result['pykotagroupname'][0])) {
529 $this->pykotaGroupNameCache[] = $result['pykotagroupname'][0];
530 }
531 }
532 }
533
534 /**
535 * Returns the current group name (cn) of this account.
536 *
537 * @return String group name
538 */
539 private function getCurrentGroupName() {
540 if (!empty($this->attributes['cn'][0])) {
541 return $this->attributes['cn'][0];
542 }
543 if ($this->getAccountContainer()->getAccountModule('posixGroup') != null) {
544 $posix = $this->getAccountContainer()->getAccountModule('posixGroup');
545 $attrs = $posix->getAttributes();
546 if (!empty($attrs['cn'][0])) {
547 return $attrs['cn'][0];
548 }
549 }
550 if ($this->getAccountContainer()->getAccountModule('groupOfNames') != null) {
551 $posix = $this->getAccountContainer()->getAccountModule('groupOfNames');
552 $attrs = $posix->getAttributes();
553 if (!empty($attrs['cn'][0])) {
554 return $attrs['cn'][0];
555 }
556 }
557 if ($this->getAccountContainer()->getAccountModule('groupOfUniqueNames') != null) {
558 $posix = $this->getAccountContainer()->getAccountModule('groupOfUniqueNames');
559 $attrs = $posix->getAttributes();
560 if (!empty($attrs['cn'][0])) {
561 return $attrs['cn'][0];
562 }
563 }
564 return '';
565 }
566
567 /**
568 * @inheritDoc
569 */
570 public function getListAttributeDescriptions(ConfiguredType $type): array {
571 return [
572 'cn' => _('Group name'),
573 'description' => _('Description'),
574 'pykotagroupname' => _('PyKota group name'),
575 'pykotalimitby' => _('Limit type'),
576 ];
577 }
578
579 }