Debian Codegraph @

lib/modules.inc

raw
1 <?php
2
3 use LAM\PDF\PDFEntry;
4 use LAM\PDF\PDFLabelValue;
5 use LAM\PDF\PdfStructurePersistenceManager;
6 use LAM\PROFILES\AccountProfilePersistenceManager;
7 use LAM\TYPES\ConfiguredType;
8 use \LAM\TYPES\TypeManager;
9 use function LAM\TYPES\getScopeFromTypeId;
10
11 /*
12
13 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
14 Copyright (C) 2003 - 2026 Roland Gruber
15
16 This program is free software; you can redistribute it and/or modify
17 it under the terms of the GNU General Public License as published by
18 the Free Software Foundation; either version 2 of the License, or
19 (at your option) any later version.
20
21 This program is distributed in the hope that it will be useful,
22 but WITHOUT ANY WARRANTY; without even the implied warranty of
23 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 GNU General Public License for more details.
25
26 You should have received a copy of the GNU General Public License
27 along with this program; if not, write to the Free Software
28 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29
30
31 */
32
33 /**
34 * Interface between modules and other parts of LAM.
35 *
36 * @package modules
37 * @author Tilo Lutz
38 * @author Michael Duergner
39 * @author Roland Gruber
40 */
41
42 /** self-service functions */
43 include_once(__DIR__ . "/selfService.inc");
44 if (isLAMProVersion()) {
45 /** job interface */
46 include_once(__DIR__ . "/jobs.inc");
47 }
48 /** some helper functions */
49 include_once(__DIR__ . "/account.inc");
50 /** parent class of account modules */
51 include_once(__DIR__ . "/baseModule.inc");
52 /** access to LDAP server */
53 include_once(__DIR__ . "/ldap.inc");
54 /** remote functions */
55 include_once(__DIR__ . "/remote.inc");
56 /** security functions */
57 include_once(__DIR__ . "/security.inc");
58 /** meta HTML classes */
59 include_once(__DIR__ . "/html.inc");
60
61 /**
62 * This includes all module files.
63 */
64 $modulesINC_dirname = substr(__FILE__, 0, strlen(__FILE__) - 12) . "/modules";
65 $modulesINC_dir = dir($modulesINC_dirname);
66 // get module names.
67 while ($entry = $modulesINC_dir->read()) {
68 if ((substr($entry, strlen($entry) - 4, 4) === '.inc') && is_file($modulesINC_dirname . '/' . $entry)) {
69 include_once($modulesINC_dirname . '/' . $entry);
70 }
71 }
72
73 /**
74 * Returns the alias name of a module
75 *
76 * @param string $name the module name
77 * @param string $scope the account type ("user", "group", "host")
78 * @return string|null alias name
79 */
80 function getModuleAlias(string $name, string $scope): ?string {
81 $module = moduleCache::getModule($name, $scope);
82 return $module?->get_alias();
83 }
84
85 /**
86 * Returns true if the module is a base module
87 *
88 * @param string $name the module name
89 * @param string $scope the account type ("user", "group", "host")
90 * @return boolean true if base module
91 */
92 function is_base_module($name, $scope) {
93 $module = moduleCache::getModule($name, $scope);
94 return $module->is_base_module();
95 }
96
97 /**
98 * Returns the LDAP filter used by the account lists
99 *
100 * @param string $typeId the account type ("user", "group", "host")
101 * @return string LDAP filter
102 */
103 function get_ldap_filter($typeId) {
104 $typeManager = new \LAM\TYPES\TypeManager();
105 $type = $typeManager->getConfiguredType($typeId);
106 $mods = $_SESSION['config']->get_AccountModules($typeId);
107 $filters = ['or' => [], 'and' => []];
108 $orFilter = '';
109 for ($i = 0; $i < count($mods); $i++) {
110 $module = moduleCache::getModule($mods[$i], $type->getScope());
111 $modinfo = $module->get_ldap_filter($typeId);
112 if (isset($modinfo['or'])) {
113 $filters['or'][] = $modinfo['or'];
114 }
115 if (isset($modinfo['and'])) {
116 $filters['and'][] = $modinfo['and'];
117 }
118 }
119 // build OR filter
120 if (count($filters['or']) === 1) {
121 $orFilter = $filters['or'][0];
122 }
123 elseif (count($filters['or']) > 1) {
124 $orFilter = "(|" . implode("", $filters['or']) . ")";
125 }
126 // add built OR filter to AND filters
127 if (!empty($orFilter)) {
128 $filters['and'][] = $orFilter;
129 }
130 // add type filter
131 $typeSettings = $_SESSION['config']->get_typeSettings();
132 if (isset($typeSettings['filter_' . $typeId]) && ($typeSettings['filter_' . $typeId] != '')) {
133 if (str_starts_with($typeSettings['filter_' . $typeId], '(')) {
134 $filters['and'][] = $typeSettings['filter_' . $typeId];
135 }
136 else {
137 $filters['and'][] = '(' . $typeSettings['filter_' . $typeId] . ')';
138 }
139 }
140 $finalFilter = (count($filters['and']) < 2) ? $filters['and'][0] : "(&" . implode("", $filters['and']) . ")";
141 $loginData = $_SESSION['ldap']->getUserName();
142 return str_replace('@@LOGIN_DN@@', $loginData, $finalFilter);
143 }
144
145 /**
146 * Returns a list of LDAP attributes which can be used to form the RDN.
147 *
148 * The list is already sorted by the priority given by the modules.
149 *
150 * @param string $typeId account type (user, group, host)
151 * @param string[] $selectedModules return only RDN attributes of these modules
152 * @return string[] list of LDAP attributes
153 */
154 function getRDNAttributes($typeId, $selectedModules = null) {
155 $mods = $_SESSION['config']->get_AccountModules($typeId);
156 if ($selectedModules != null) {
157 $mods = $selectedModules;
158 }
159 $attrs_low = [];
160 $attrs_normal = [];
161 $attrs_high = [];
162 for ($i = 0; $i < count($mods); $i++) {
163 // get list of attributes
164 $module = moduleCache::getModule($mods[$i], \LAM\TYPES\getScopeFromTypeId($typeId));
165 $attrs = $module->get_RDNAttributes($typeId);
166 $keys = array_keys($attrs);
167 // sort attributes
168 for ($k = 0; $k < count($keys); $k++) {
169 switch ($attrs[$keys[$k]]) {
170 case "normal":
171 $attrs_normal[] = $keys[$k];
172 break;
173 case "high":
174 $attrs_high[] = $keys[$k];
175 break;
176 case "low":
177 default:
178 $attrs_low[] = $keys[$k];
179 break;
180 }
181 }
182 }
183 // merge arrays
184 $return = array_values(array_unique($attrs_high));
185 for ($i = 0; $i < count($attrs_normal); $i++) {
186 if (!in_array($attrs_normal[$i], $return)) {
187 $return[] = $attrs_normal[$i];
188 }
189 }
190 for ($i = 0; $i < count($attrs_low); $i++) {
191 if (!in_array($attrs_low[$i], $return)) {
192 $return[] = $attrs_low[$i];
193 }
194 }
195 return $return;
196 }
197
198 /**
199 * Returns a hash array (module name => dependencies) of all module dependencies
200 *
201 * "dependencies" contains an array with two sub arrays: depends, conflicts
202 * <br>The elements of "depends" are either module names or an array of module names (OR-case).
203 * <br>The elements of conflicts are module names.
204 *
205 * @param string $scope the account type (user, group, host)
206 * @return array<string, array<string, array<string|string[]>>> dependencies
207 */
208 function getModulesDependencies($scope) {
209 $return = [];
210 $mods = getAvailableModules($scope);
211 for ($i = 0; $i < count($mods); $i++) {
212 $module = moduleCache::getModule($mods[$i], $scope);
213 $return[$mods[$i]] = $module->get_dependencies();
214 }
215 return $return;
216 }
217
218
219 /**
220 * Checks if there are missing dependencies between modules.
221 *
222 * @param string[] $selected selected module names
223 * @param array<string, array<string, array<string|string[]>>> $deps module dependencies
224 * @return false|string[][] false if no missing dependency was found,
225 * otherwise an array of array(selected module, depending module) if missing dependencies were found
226 */
227 function check_module_depends($selected, $deps) {
228 $ret = [];
229 for ($m = 0; $m < count($selected); $m++) { // check selected modules
230 for ($i = 0; $i < count($deps[$selected[$m]]['depends']); $i++) { // check dependencies of module
231 // check if we have OR-combined modules
232 if (is_array($deps[$selected[$m]]['depends'][$i])) {
233 // one of the elements is needed
234 $found = false;
235 $depends = $deps[$selected[$m]]['depends'][$i];
236 for ($d = 0; $d < count($depends); $d++) {
237 if (in_array($depends[$d], $selected)) {
238 $found = true;
239 break;
240 }
241 }
242 if (!$found) {
243 // missing dependency, add to return value
244 $ret[] = [$selected[$m], implode(" || ", $depends)];
245 }
246 }
247 elseif (!in_array($deps[$selected[$m]]['depends'][$i], $selected)) {
248 // single dependency
249 // missing dependency, add to return value
250 $ret[] = [$selected[$m], $deps[$selected[$m]]['depends'][$i]];
251 }
252 }
253 }
254 if ($ret !== []) {
255 return $ret;
256 }
257 return false;
258 }
259
260 /**
261 * Checks if there are conflicts between modules
262 *
263 * @param string[] $selected selected module names
264 * @param array<string, array<string, array<string|string[]>>> $deps module dependencies
265 * @return false|array<int, string[]> false if no conflict was found,
266 * otherwise an array of array(selected module, conflicting module) if conflicts were found
267 */
268 function check_module_conflicts($selected, $deps) {
269 $ret = [];
270 for ($m = 0; $m < count($selected); $m++) {
271 for ($i = 0; $i < count($deps[$selected[$m]]['conflicts']); $i++) {
272 if (in_array($deps[$selected[$m]]['conflicts'][$i], $selected)) {
273 $ret[] = [$selected[$m], $deps[$selected[$m]]['conflicts'][$i]];
274 }
275 }
276 }
277 if ($ret !== []) {
278 return $ret;
279 }
280 return false;
281 }
282
283 /**
284 * Returns an array with all available user module names
285 *
286 * @param string $scope account type (user, group, host)
287 * @param bool $mustSupportAdminInterface module must support LAM admin interface (default: false)
288 * @return string[] list of possible modules
289 */
290 function getAvailableModules($scope, bool $mustSupportAdminInterface = false): array {
291 $dirname = substr(__FILE__, 0, strlen(__FILE__) - 12) . "/modules";
292 $dir = dir($dirname);
293 $return = [];
294 // get module names.
295 while ($entry = $dir->read()) {
296 if ((substr($entry, strlen($entry) - 4, 4) === '.inc') && is_file($dirname . '/' . $entry)) {
297 $entry = substr($entry, 0, strpos($entry, '.'));
298 $temp = moduleCache::getModule($entry, $scope);
299 if ($temp === null) {
300 continue;
301 }
302 if ($mustSupportAdminInterface && !$temp->supportsAdminInterface()) {
303 continue;
304 }
305 if ($temp->can_manage()) {
306 $return[] = $entry;
307 }
308 }
309 }
310 return $return;
311 }
312
313 /**
314 * Returns an array with all modules.
315 *
316 * @return baseModule[] list of modules
317 */
318 function getAllModules(): array {
319 $dirname = substr(__FILE__, 0, strlen(__FILE__) - 12) . "/modules";
320 $dir = dir($dirname);
321 $return = [];
322 // get module names.
323 while ($entry = $dir->read()) {
324 if ((substr($entry, strlen($entry) - 4, 4) === '.inc') && is_file($dirname . '/' . $entry)) {
325 $entry = substr($entry, 0, strpos($entry, '.'));
326 $return[] = new $entry(null);
327 }
328 }
329 return $return;
330 }
331
332 /**
333 * Returns the elements for the profile page.
334 *
335 * @param string $typeId account type (user, group, host)
336 * @return array<string, htmlResponsiveRow> profile elements
337 */
338 function getProfileOptions(string $typeId): array {
339 $typeManager = new TypeManager();
340 $type = $typeManager->getConfiguredType($typeId);
341 $mods = $type->getModules();
342 $return = [];
343 for ($i = 0; $i < count($mods); $i++) {
344 $module = moduleCache::getModule($mods[$i], $type->getScope());
345 $moduleOptions = $module->get_profileOptions($typeId);
346 if ($moduleOptions !== null) {
347 $return[$mods[$i]] = $moduleOptions;
348 }
349 }
350 return $return;
351 }
352
353 /**
354 * Checks if the profile options are valid
355 *
356 * @param string $typeId account type (user, group, host)
357 * @param array<string, string[]> $options hash array containing all options (name => array(...))
358 * @return array<string|string[]>[] list of error messages
359 */
360 function checkProfileOptions($typeId, $options) {
361 $typeManager = new TypeManager();
362 $type = $typeManager->getConfiguredType($typeId);
363 $mods = $type->getModules();
364 $return = [];
365 for ($i = 0; $i < count($mods); $i++) {
366 $module = moduleCache::getModule($mods[$i], $type->getScope());
367 $temp = $module->check_profileOptions($options, $type->getId());
368 $return = array_merge($return, $temp);
369 }
370 return $return;
371 }
372
373 /**
374 * Returns a hash array (module name => elements) of all module options for the configuration page.
375 *
376 * @param array<string, string[]> $moduleToScopes hash array (module name => array(account types))
377 * @return array<class-string<baseModule>, htmlElement|htmlElement[]> configuration options
378 */
379 function getConfigOptions(array $moduleToScopes): array {
380 $return = [];
381 foreach ($moduleToScopes as $module => $typeIds) {
382 $m = moduleCache::getModule($module, getScopeFromTypeId($typeIds[0]));
383 $return[$module] = $m->get_configOptions($typeIds, $moduleToScopes);
384 }
385 return $return;
386 }
387
388 /**
389 * Checks if the configuration options are valid
390 *
391 * @param array<string, string[]> $moduleToTypeIds hash array (module name => array(account type ids))
392 * @param array<string, string[]> $options hash array containing all options (name => array(...))
393 * @return array<string|string[]>[] list of error messages
394 */
395 function checkConfigOptions($moduleToTypeIds, &$options) {
396 $return = [];
397 foreach ($moduleToTypeIds as $module => $typeIds) {
398 $m = moduleCache::getModule($module, getScopeFromTypeId($typeIds[0]));
399 $errors = $m->check_configOptions($typeIds, $options);
400 $return = array_merge($return, $errors);
401 }
402 return $return;
403 }
404
405 /**
406 * Returns a help entry from an account module.
407 *
408 * @param string|null $module module name
409 * @param string $helpID help identifier
410 * @return array<string, string>|null help entry
411 */
412 function getHelp($module, $helpID): ?array {
413 global $helpArray;
414 if (in_array($module, [null, '', 'main'], true)) {
415 if (!isset($helpArray)) {
416 include_once(__DIR__ . '/../help/help.inc');
417 }
418 return $helpArray[$helpID];
419 }
420 $moduleObject = moduleCache::getModule($module, null);
421 return $moduleObject->get_help($helpID);
422 }
423
424 /**
425 * Returns a list of available PDF entries.
426 *
427 * @param string $typeId account type (user, group, host)
428 * @return array<string, array<string, string>> PDF entries (field ID => field label)
429 */
430 function getAvailablePDFFields(string $typeId): array {
431 $typeManager = new TypeManager();
432 $_SESSION['pdfContainer'] = new accountContainer($typeManager->getConfiguredType($typeId), 'pdfContainer');
433 $_SESSION['pdfContainer']->initModules();
434 $mods = $_SESSION['pdfContainer']->getAccountModules();
435 $return = [];
436 foreach ($mods as $module) {
437 $fields = $module->get_pdfFields($typeId);
438 $moduleName = $module::class;
439 $return[$moduleName] = [];
440 foreach ($fields as $fieldID => $fieldLabel) {
441 $return[$moduleName][$fieldID] = $fieldLabel;
442 }
443 }
444 $return['main'] = ['dn' => _('DN')];
445 unset($_SESSION['pdfContainer']);
446 return $return;
447 }
448
449 /**
450 * Returns an array containing all input columns for the file upload.
451 *
452 * Syntax:
453 * <br> array(
454 * <br> string: name, // fixed non-translated name which is used as column name (should be of format: <module name>_<column name>)
455 * <br> string: description, // short descriptive name
456 * <br> string: help, // help ID
457 * <br> string: example, // example value
458 * <br> boolean: required // true, if user must set a value for this column
459 * <br> )
460 *
461 * @param ConfiguredType $type account type
462 * @param string[] $selectedModules selected account modules
463 * @return array<string, array<string, string|bool>[]> column list
464 */
465 function getUploadColumns(&$type, $selectedModules): array {
466 $return = [];
467 for ($i = 0; $i < count($selectedModules); $i++) {
468 $module = moduleCache::getModule($selectedModules[$i], $type->getScope());
469 $return[$selectedModules[$i]] = $module->get_uploadColumns($selectedModules, $type);
470 }
471 return $return;
472 }
473
474 /**
475 * This function builds the LDAP accounts for the file upload.
476 *
477 * If there are problems status messages will be printed automatically.
478 *
479 * @param ConfiguredType $type account type
480 * @param array<int, string>[] $data array containing one account in each element
481 * @param array<string, int> $ids array(<column_name> => <column number>)
482 * @param string[] $selectedModules selected account modules
483 * @param htmlResponsiveRow $container HTML container
484 * @return mixed array including accounts or false if there were errors
485 */
486 function buildUploadAccounts($type, $data, $ids, $selectedModules, htmlResponsiveRow $container) {
487 // build module order
488 $unOrdered = $selectedModules;
489 $ordered = [];
490 $predepends = [];
491 // get dependencies
492 for ($i = 0; $i < count($unOrdered); $i++) {
493 $mod = moduleCache::getModule($unOrdered[$i], $type->getScope());
494 logNewMessage(LOG_DEBUG, 'Checking dependencies for ' . $unOrdered[$i]);
495 $predepends[$unOrdered[$i]] = $mod->get_uploadPreDepends();
496 }
497 // first all modules without predepends can be ordered
498 for ($i = 0; $i < count($unOrdered); $i++) {
499 if (count($predepends[$unOrdered[$i]]) === 0) {
500 $ordered[] = $unOrdered[$i];
501 unset($unOrdered[$i]);
502 $unOrdered = array_values($unOrdered);
503 $i--;
504 }
505 }
506 $unOrdered = array_values($unOrdered); // fix indexes
507 // now add all modules with fulfilled dependencies until all are in order
508 while ($unOrdered !== []) {
509 $newRound = false;
510 for ($i = 0; $i < count($unOrdered); $i++) {
511 $deps = $predepends[$unOrdered[$i]];
512 $depends = false;
513 for ($d = 0; $d < count($deps); $d++) {
514 if (in_array($deps[$d], $unOrdered)) {
515 $depends = true;
516 break;
517 }
518 }
519 if (!$depends) { // add to order if dependencies are fulfilled
520 $ordered[] = $unOrdered[$i];
521 unset($unOrdered[$i]);
522 $unOrdered = array_values($unOrdered);
523 $newRound = true;
524 break;
525 }
526 }
527 if ($newRound) {
528 continue;
529 }
530 // this point should never be reached, LAM was unable to find a correct module order
531 $container->add(new htmlStatusMessage("ERROR", "Internal Error: Unable to find correct module order."), 12);
532 return false;
533 }
534 // give raw data to modules
535 $errors = [];
536 $partialAccounts = [];
537 foreach ($data as $i => $dataRow) {
538 $partialAccounts[$i]['objectClass'] = [];
539 }
540 $stopUpload = false;
541 for ($i = 0; $i < count($ordered); $i++) {
542 if (!in_array(baseModule::class, class_parents($ordered[$i]))) {
543 logNewMessage(LOG_WARNING, 'Invalid module name: ' . $ordered[$i]);
544 continue;
545 }
546 $module = new $ordered[$i]($type->getScope());
547 logNewMessage(LOG_DEBUG, 'Building data for ' . $ordered[$i]);
548 $moduleErrors = $module->build_uploadAccounts($data, $ids, $partialAccounts, $selectedModules, $type);
549 if (count($moduleErrors) > 0) {
550 $errors = array_merge($errors, $moduleErrors);
551 foreach ($moduleErrors as $error) {
552 if ($error[0] == 'ERROR') {
553 array_unshift($errors, ["INFO", _("Displayed account numbers start at \"0\". Add 2 to get the row in your spreadsheet."), ""]);
554 $errors[] = ["ERROR", _("Upload was stopped after errors in %s module!"), "", [$module->get_alias()]];
555 // skip other modules if error was found
556 $stopUpload = true;
557 break;
558 }
559 }
560 }
561 if ($stopUpload) {
562 break;
563 }
564 }
565 if ($errors !== []) {
566 for ($i = 0; (($i < count($errors)) && ($i < 50)); $i++) {
567 $text = empty($errors[$i][2]) ? null : $errors[$i][2];
568 $values = empty($errors[$i][3]) ? null : $errors[$i][3];
569 $container->add(new htmlStatusMessage($errors[$i][0], $errors[$i][1], $text, $values), 12);
570 }
571 }
572 if ($stopUpload) {
573 return false;
574 }
575 logNewMessage(LOG_DEBUG, 'Data built');
576 return $partialAccounts;
577 }
578
579 /**
580 * Runs any actions that need to be done before an LDAP entry is created.
581 *
582 * @param ConfiguredType $type account type
583 * @param string[] $selectedModules list of selected account modules
584 * @param array<string, string[]|string> $attributes LDAP attributes of this entry (attributes are provided as reference, handle modifications of $attributes with care)
585 * @return array<string|string[]>[] array which contains status messages. Each entry is an array containing the status message parameters.
586 */
587 function doUploadPreActions($type, $selectedModules, $attributes) {
588 $messages = [];
589 for ($i = 0; $i < count($selectedModules); $i++) {
590 $activeModule = $selectedModules[$i];
591 $module = moduleCache::getModule($activeModule, $type->getScope());
592 $messages = array_merge($messages, $module->doUploadPreActions($attributes, $type));
593 }
594 return $messages;
595 }
596
597 /**
598 * This function executes one post upload action.
599 *
600 * @param ConfiguredType $type account type
601 * @param array<int, string>[] $data array containing one account in each element
602 * @param array<string, int> $ids array(<column_name> => <column number>)
603 * @param int[] $failed list of accounts which were not created successfully
604 * @param string[] $selectedModules list of selected account modules
605 * @param array<string, string[]|string>[] $accounts list of LDAP entries
606 * @return array<string, string|int|string[]> current status
607 * <br>array (
608 * <br> 'status' => 'finished' | 'inProgress'
609 * <br> 'module' => <name of active module>
610 * <br> 'progress' => 0..100
611 * <br> 'errors' => array (<array of parameters for StatusMessage>)
612 * <br>)
613 */
614 function doUploadPostActions($type, &$data, $ids, $failed, $selectedModules, &$accounts) {
615 // check if function is called the first time
616 if (!isset($_SESSION['mass_postActions']['remainingModules'])) {
617 // make list of remaining modules
618 $moduleList = $selectedModules;
619 $_SESSION['mass_postActions']['remainingModules'] = $moduleList;
620 }
621 $activeModule = $_SESSION['mass_postActions']['remainingModules'][0];
622 // initialize temporary variable
623 if (!isset($_SESSION['mass_postActions'][$activeModule])) {
624 $_SESSION['mass_postActions'][$activeModule] = [];
625 }
626 // let first module do one post action
627 $module = moduleCache::getModule($activeModule, $type->getScope());
628 $return = $module->doUploadPostActions($data, $ids, $failed, $_SESSION['mass_postActions'][$activeModule], $accounts, $selectedModules, $type);
629 // remove active module from list if already finished
630 if ($return['status'] == 'finished') {
631 unset($_SESSION['mass_postActions']['remainingModules'][0]);
632 $_SESSION['mass_postActions']['remainingModules'] = array_values($_SESSION['mass_postActions']['remainingModules']);
633 }
634 // update status and return back to upload page
635 $return['module'] = $activeModule;
636 $return['status'] = (count($_SESSION['mass_postActions']['remainingModules']) > 0) ? 'inProgress' : 'finished';
637 return $return;
638 }
639
640 /**
641 * Takes a list of meta-HTML elements and prints the equivalent HTML output.
642 *
643 * The modules are not allowed to display HTML code directly but return
644 * meta HTML code. This allows to have a common design for all module pages.
645 *
646 * @param string|null $module Name of account module
647 * @param htmlElement|htmlElement[]|null $input htmlElement or array of htmlElement elements
648 * @param array<string, string[]> $values List of values which override the defaults in $input (name => value)
649 * @param bool $restricted If true then no buttons will be displayed
650 * @return array<string, string> list of input field names and their type (name => type)
651 */
652 function parseHtml($module, $input, $values, $restricted) {
653 if ($input === null) {
654 return [];
655 }
656 if ($input instanceof htmlElement) {
657 return $input->generateHTML($module, [$input], $values, $restricted);
658 }
659 if ($input !== []) {
660 $return = [];
661 for ($i = 0; $i < count($input); $i++) {
662 $return = array_merge($return, $input[$i]->generateHTML($module, $input, $values, $restricted));
663 }
664 return $return;
665 }
666 return [];
667 }
668
669 /**
670 * Prints a LAM help link.
671 *
672 * @param array<string, string> $entry help entry
673 * @param string $number help number
674 * @param string $module module name
675 * @param string[] $classes CSS classes
676 */
677 function printHelpLink($entry, $number, $module = '', $classes = []): void {
678 $helpPath = "../";
679 if (is_file("./help.php")) {
680 $helpPath = "";
681 }
682 $title = htmlspecialchars($entry['Headline']);
683 $message = $entry['Text'];
684 if (isset($entry['attr'])) {
685 $message .= '<br><br><hr class="dotted">' . _('Technical name') . ': <i>' . htmlspecialchars($entry['attr']) . '</i>';
686 }
687 // replace special characters
688 $selfServiceOption = '';
689 if (isSelfService()) {
690 $selfServiceOption = '&amp;selfService=1';
691 }
692 echo "<a class=\"margin2 " . implode(" ", $classes) . "\" href=\"" . $helpPath . "help.php?module=$module&amp;HelpNumber=" . $number . $selfServiceOption . "\" ";
693 echo "target=\"help\" tabindex=\"-1\" onmouseenter='window.lam.tooltip.show(this);' onmouseleave='window.lam.tooltip.hide(this);'>";
694 echo "<img class=\"align-middle help-icon\" src=\"../{$helpPath}graphics/help.svg\" alt=\"" . _('Help') . "\" width=\"16\" height=\"16\">";
695 echo "</a>";
696 echo "<div class='lam-help hidden " . implode(" ", $classes) . "'><h4>$title</h4>$message</div>";
697 }
698
699
700 /**
701 * This class includes all modules and attributes of an account.
702 *
703 * @package modules
704 */
705 class accountContainer {
706
707 /**
708 * Constructor
709 *
710 * @param ConfiguredType $type account type
711 * @param string $base key in $_SESSION where this object is saved
712 */
713 public function __construct(ConfiguredType $type, string $base) {
714 $this->type = $type;
715 $this->base = $base;
716 }
717
718 /**
719 * @var array<string, string[]|string>|null $attributes Array of all used attributes
720 * Syntax is attribute => array ( objectClass => MUST or MAY, ...)
721 */
722 public array|null $attributes = null;
723
724 /**
725 * This variable stores the account type.
726 */
727 private ConfiguredType $type;
728
729 /** This is an array with all module objects
730 *
731 * @var baseModule[] modules
732 */
733 private array $module = [];
734
735 /** DN suffix of the account */
736 public ?string $dnSuffix = null;
737
738 /** @var string|null DN of account when it was loaded */
739 public ?string $dn_orig = null;
740
741 /** RDN attribute of this account */
742 public ?string $rdn = null;
743
744 /** DN of saved account */
745 public ?string $finalDN = null;
746
747 /** @var array<string, string[]|string>|null $attributes_orig original LDAP attributes when account was loaded from LDAP */
748 public array|null $attributes_orig = null;
749
750 /** @var string[]|null $order module order */
751 private ?array $order = null;
752
753 /** Name of accountContainer variable in session */
754 private string $base;
755
756 /** This variable stores the page number of the currently displayed page */
757 private int $current_page = 0;
758
759 /** This variable is set to the pagename of a subpage if it should be displayed */
760 private string $subpage = 'attributes';
761
762 /** True if this is a newly created account */
763 public bool $isNewAccount = false;
764
765 /** name of last loaded account profile */
766 private string $lastLoadedProfile = '';
767
768 /** @var string[]|null cache for existing OUs */
769 private ?array $cachedOUs = null;
770
771 /** icon in title bar */
772 private ?htmlElement $titleBarIcon = null;
773 /** main title in title bar */
774 private ?string $titleBarTitle = null;
775 /** subtitle in title bar */
776 private string $titleBarSubtitle = '';
777 /** password to send via mail */
778 private ?string $sendPasswordViaMail = null;
779 /** password to send via SMS */
780 private ?string $sendPasswordViaSms = null;
781 /** send password via mail to this alternate address */
782 private ?string $sendPasswordViaMailAlternateAddress = null;
783
784 /**
785 * @var array<string, string> additional attributes for pre/post actions
786 */
787 private array $extraInfoAttributes = [];
788
789 /**
790 * @var bool errors occurred after saving LDAP data (postModify scripts)
791 */
792 private bool $postSaveErrorsOccurred = false;
793
794
795 /**
796 * Returns the account module with the given class name
797 *
798 * @template T of baseModule
799 * @param class-string<T> $name class name (e.g. posixAccount)
800 * @return T|null account module
801 */
802 public function getAccountModule(string $name): ?baseModule {
803 return $this->module[$name] ?? null;
804 }
805
806 /**
807 * Returns the included account modules.
808 *
809 * @return baseModule[] modules
810 */
811 public function getAccountModules() {
812 return $this->module;
813 }
814
815 /**
816 * Returns the account type of this object (e.g. user, group, host).
817 *
818 * @return ConfiguredType account type
819 */
820 public function get_type() {
821 return $this->type;
822 }
823
824 /**
825 * Returns the session edit key for this container.
826 *
827 * @return string key
828 */
829 public function getEditKey() {
830 return $this->base;
831 }
832
833 /**
834 * This function is called when the user clicks on any button on the account pages.
835 * It prints the HTML code of each account page.
836 */
837 public function continue_main(): void {
838 $oldPage = $this->current_page;
839 $oldSubpage = $this->subpage;
840 $result = [];
841 $errorsOccurred = false;
842 $typeObject = $this->type->getBaseType();
843 $profileLoaded = $this->loadProfileIfRequested();
844 if ($this->subpage === '') {
845 $this->subpage = 'attributes';
846 }
847 if (isset($_POST['accountContainerReset'])) {
848 $result = $this->load_account($this->dn_orig);
849 }
850 elseif (isset($_POST['accountContainerDelete'])) {
851 metaRefresh("../lists/deletelink.php?type=" . $this->type->getId() . "&DN='" . rawurlencode($this->dn_orig) . "'");
852 unset($_SESSION[$this->base]);
853 exit();
854 }
855 elseif (!$profileLoaded) {
856 // change dn suffix
857 $possibleOUs = $this->getOUs();
858 if (($this->dnSuffix === null) && !empty($_GET['suffix']) && in_array($_GET['suffix'], $possibleOUs)) {
859 $this->dnSuffix = $_GET['suffix'];
860 }
861 if (!empty($_POST['accountContainerSuffix']) && in_array($_POST['accountContainerSuffix'], $possibleOUs)) {
862 $this->dnSuffix = $_POST['accountContainerSuffix'];
863 }
864 // change RDN
865 $rdnList = getRDNAttributes($this->type->getId());
866 if (!empty($_POST['accountContainerRDN']) && in_array($_POST['accountContainerRDN'], $rdnList)) {
867 $this->rdn = $_POST['accountContainerRDN'];
868 }
869 // create another account
870 if (isset($_POST['accountContainerCreateAgain'])) {
871 // open a fresh account page
872 unset($_SESSION[$this->base]);
873 metaRefresh("edit.php?type=" . $this->type->getId() . "&suffix=" . $this->dnSuffix);
874 exit();
875 }
876 // reedit account
877 if (isset($_POST['accountContainerBackToEdit'])) {
878 // open a fresh account page
879 unset($_SESSION[$this->base]);
880 metaRefresh("edit.php?type=" . $this->type->getId() . "&DN=" . urlencode($this->finalDN));
881 exit();
882 }
883 // back to account list
884 if (isset($_POST['accountContainerBackToList'])) {
885 // Return to the account list
886 unset($_SESSION[$this->base]);
887 metaRefresh("../lists/list.php?type=" . $this->type->getId() . '&accountEditBack=true');
888 exit;
889 }
890 // create the PDF file
891 if (isset($_POST['accountContainerCreatePDF'])) {
892 metaRefresh('../lists/list.php?printPDF=1&type=' . $this->type->getId() . "&refresh=true&PDFSessionID=" . $this->base);
893 exit;
894 }
895 // module actions
896 if (($_POST !== []) && checkIfWriteAccessIsAllowed($this->type->getId())) {
897 $result = call_user_func([&$this->module[$this->order[$this->current_page]], 'process_' . $this->subpage]);
898 if (is_array($result)) { // messages were returned, check for errors
899 for ($i = 0; $i < count($result); $i++) {
900 if ($result[$i][0] == 'ERROR') {
901 $errorsOccurred = true;
902 break;
903 }
904 }
905 }
906 $this->sortModules();
907 }
908 // run type post actions
909 $typeObject->runEditPagePostAction($this);
910 // save account
911 if (!$errorsOccurred && isset($_POST['accountContainerSaveAccount'])) {
912 // check if all modules are complete
913 $modules = array_keys($this->module);
914 $incompleteModules = [];
915 foreach ($modules as $module) {
916 if (!$this->module[$module]->module_complete()) {
917 $incompleteModules[] = $this->module[$module]->get_alias();
918 }
919 }
920 if ($incompleteModules !== []) {
921 $result[] = ['INFO', _('Some required information is missing'),
922 sprintf(_('Please set up all required attributes on page: %s'), implode(", ", $incompleteModules))];
923 }
924 else {
925 // save account
926 $saveMessages = $this->save_account();
927 $saveOk = true;
928 for ($i = 0; $i < count($saveMessages); $i++) {
929 if ($saveMessages[$i][0] == 'ERROR') {
930 $saveOk = false;
931 }
932 }
933 if (!$saveOk) {
934 $result = $saveMessages;
935 }
936 else {
937 $this->printSuccessPage($saveMessages);
938 return;
939 }
940 }
941 }
942 }
943 // change to the next page
944 if (is_array($result)) { // messages were returned, check for errors
945 for ($i = 0; $i < count($result); $i++) {
946 if ($result[$i][0] == 'ERROR') {
947 $errorsOccurred = true;
948 break;
949 }
950 }
951 }
952 if (!$errorsOccurred) {
953 // go to subpage of current module
954 $postKeys = array_keys($_POST);
955 for ($p = 0; $p < count($postKeys); $p++) {
956 if (is_string($postKeys[$p]) && (str_starts_with($postKeys[$p], 'form_subpage_' . $this->order[$this->current_page]))) {
957 $temp = substr($postKeys[$p], strlen($this->order[$this->current_page]) + 14);
958 $temp = explode('_', $temp);
959 if (count($temp) === 2) {
960 $this->subpage = $temp[0];
961 }
962 }
963 }
964 for ($i = 0; $i < count($this->order); $i++) {
965 if (isset($_POST['form_main_' . $this->order[$i]])) {
966 if ($this->module[$this->order[$i]]->module_ready()) {
967 $this->current_page = $i;
968 $this->subpage = 'attributes';
969 }
970 else {
971 StatusMessage('ERROR', _('The module %s is not yet ready.'),
972 _('Please enter the account information on the other pages first.'),
973 [$this->module[$this->order[$i]]->get_alias()]);
974 }
975 }
976 }
977 }
978 if ($profileLoaded) {
979 $profileName = $_POST['accountContainerSelectLoadProfile'];
980 $result[] = ['INFO', _('Profile "%s" loaded.'), '<div class="hidden lam-dialog-msg" id="lam-make-default-profile-dlg">' . _('Setting saved') . '</div>' .
981 '<a href="#" id="lam-make-default-profile" data-name="%s" data-typeid="%s" data-ok="%s">' . _('Click here to make this your default profile.') . '</a>', [$profileName, $profileName, $this->get_type()->getId(), _('Ok')]];
982 }
983 // update titles
984 $this->titleBarIcon = $typeObject->buildAccountStatusIcon($this);
985 $this->titleBarTitle = $typeObject->getTitleBarTitle($this);
986 $this->titleBarSubtitle = $typeObject->getTitleBarSubtitle($this);
987 // prints a module content page
988 $this->printModuleContent($result);
989 if (!$errorsOccurred && ($oldPage === $this->current_page) && ($oldSubpage === $this->subpage)
990 && isset($_POST['scrollPositionTop']) && get_preg($_POST['scrollPositionTop'], 'digit')
991 && isset($_POST['scrollPositionLeft']) && get_preg($_POST['scrollPositionLeft'], 'digit')) {
992 // scroll to last position
993 $scrollJs = new htmlJavaScript('window.lam.utility.restoreScrollPosition(' . $_POST['scrollPositionTop'] . ', ' . $_POST['scrollPositionLeft'] . ')');
994 parseHtml(null, $scrollJs, [], false);
995 }
996 $this->printPageFooter();
997 }
998
999 /**
1000 * Prints the content part provided by the current module.
1001 *
1002 * @param array<string|string[]>[] $result list of messages
1003 */
1004 private function printModuleContent(array $result): void {
1005 $this->printPageHeader();
1006 $this->printPasswordPromt();
1007 // display error messages
1008 for ($i = 0; $i < count($result); $i++) {
1009 call_user_func_array(StatusMessage(...), $result[$i]);
1010 }
1011 echo '<div id="passwordMessageArea"></div>';
1012 echo "<table class=\"lam-account-edit-table\">\n";
1013 echo "<tr><td style=\"padding: 5px 0px 0px 0px;\">\n";
1014 $this->printCommonControls();
1015 echo "</td></tr>\n";
1016 echo "<tr valign=\"top\"><td style=\"padding: 15px;\">";
1017 // print title bar
1018 $titleBarContainer = new htmlResponsiveRow();
1019 $titleBarContainer->setCSSClasses(['maxrow']);
1020 $titleGroup = new htmlGroup();
1021 if ($this->titleBarIcon !== null) {
1022 $titleGroup->addElement($this->titleBarIcon);
1023 $titleGroup->addElement(new htmlSpacer('1rem', null));
1024 }
1025 $titleBarTitleText = new htmlOutputText($this->titleBarTitle, false);
1026 $titleGroup->addElement($titleBarTitleText);
1027 $titleBarContainer->add(new htmlDiv(null, $titleGroup, ['titleBarTitle', 'text-left']), 12, 12, 4);
1028 $titleBarSubtitleText = new htmlOutputText($this->titleBarSubtitle, false);
1029 $titleBarContainer->add(new htmlDiv(null, $titleBarSubtitleText, ['titleBarSubtitle', 'responsiveLabel']), 12, 12, 8);
1030 $titleBarSuffixRdn = new htmlResponsiveRow();
1031 $titleBarSuffixRdn->add(new htmlHorizontalLine(), 12);
1032 // suffix
1033 $suffixList = [];
1034 foreach ($this->getOUs() as $suffix) {
1035 $suffixList[getAbstractDN($suffix)] = $suffix;
1036 }
1037 if (($this->dnSuffix != '') && !in_array_ignore_case($this->dnSuffix, $this->getOUs())) {
1038 $suffixList[getAbstractDN($this->dnSuffix)] = $this->dnSuffix;
1039 }
1040 $selectedSuffix = [$this->dnSuffix];
1041 $suffixSelect = new htmlResponsiveSelect('accountContainerSuffix', $suffixList, $selectedSuffix, _('Suffix'));
1042 $suffixSelect->setHasDescriptiveElements(true);
1043 $suffixSelect->setRightToLeftTextDirection(true);
1044 $suffixSelect->setShortLabel();
1045 $suffixSelect->setSortElements(false);
1046 $titleBarSuffixRdn->add($suffixSelect, 12, 12, 7);
1047 // RDN selection
1048 $rdnlist = getRDNAttributes($this->type->getId());
1049 $rdnSelect = new htmlResponsiveSelect('accountContainerRDN', $rdnlist, [$this->rdn], _('RDN identifier'), '400');
1050 $rdnSelect->setShortLabel();
1051 $rdnSelect->setSortElements(false);
1052 $titleBarSuffixRdn->add($rdnSelect, 12, 12, 5);
1053 $titleBarContainer->add($titleBarSuffixRdn);
1054
1055 $titleBarDiv = new htmlDiv(null, $titleBarContainer, ['titleBar']);
1056 parseHtml(null, $titleBarDiv, [], false);
1057
1058 echo '<div id="lamVerticalTabs" class="lam-vertical-tab-container">';
1059 echo '<table class="lam-vertical-tabs fullwidth">';
1060 echo '<tr><td class="lam-vertical-tabs-navigation">';
1061 // tab menu
1062 $this->printModuleTabs();
1063 echo '</td><td style="vertical-align: top; width: 100%;">';
1064 echo "<div class=\"lam-vertical-tab-content fullwidth module-content-row\">\n";
1065 // content area
1066 // display html-code from modules
1067 try {
1068 $return = call_user_func([$this->module[$this->order[$this->current_page]], 'display_html_' . $this->subpage]);
1069 }
1070 catch (LAMException $e) {
1071 $return = new htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage());
1072 }
1073 parseHtml($this->order[$this->current_page], $return, [], false);
1074 echo "</div>\n";
1075 echo '</td>';
1076 echo '</tr>';
1077 echo '</table>';
1078 echo "</div>\n";
1079 echo "</td></tr>\n";
1080 // Display rest of html-page
1081 echo "</table>\n";
1082 }
1083
1084 /**
1085 * Prints the input fields of the central password service.
1086 */
1087 private function printPasswordPromt(): void {
1088 echo "<div id=\"passwordDialogOuter\" class=\"modal modal-pwd-options\">\n";
1089 echo "<div id=\"passwordDialog\" class=\"modal-content\">\n";
1090 $printContainer = false;
1091 $container = new htmlResponsiveRow();
1092 $container->setCSSClasses(['text-left']);
1093 $title = new htmlTitle(_('Set password'));
1094 $container->add($title);
1095 // password fields
1096 $pwdInput1 = new htmlResponsiveInputField(_('Password'), 'newPassword1', null, '404');
1097 $pwdInput1->setIsPassword(true, true);
1098 $container->add($pwdInput1);
1099 $pwdInput2 = new htmlResponsiveInputField(_('Repeat password'), 'newPassword2');
1100 $pwdInput2->setIsPassword(true);
1101 $pwdInput2->setSameValueFieldID('newPassword1');
1102 $container->add($pwdInput2);
1103 // print force password change option
1104 $forceChangeSupported = [];
1105 foreach ($this->module as $module) {
1106 if (($module instanceof passwordService) && $module->supportsForcePasswordChange()) {
1107 $forceChangeSupported[] = $module;
1108 }
1109 }
1110 if (!empty($forceChangeSupported)) {
1111 $container->addLabel(new htmlLabel('lamForcePasswordChange', _('Force password change')));
1112 $forcePwdGroup = new htmlGroup();
1113 $forcePwdGroup->addElement(new htmlInputCheckbox('lamForcePasswordChange', false));
1114 $forcePwdGroup->addElement(new htmlSpacer('1rem', null));
1115 foreach ($forceChangeSupported as $module) {
1116 $forcePwdGroup->addElement(new htmlImage('../../graphics/' . $module->getIcon(), '16px', '16px', $module->get_alias(), $module->get_alias()));
1117 $forcePwdGroup->addElement(new htmlSpacer('0.1rem', null));
1118 }
1119 $forcePwdGroup->addElement(new htmlHelpLink('406'));
1120 $container->addField($forcePwdGroup);
1121 $container->addVerticalSpacer('0.25rem');
1122 }
1123 if (isLAMProVersion() && (isset($this->attributes_orig['mail'][0]) || $this->anyModuleManagesMail())) {
1124 $pwdMailCheckbox = new htmlResponsiveInputCheckbox('lamPasswordChangeSendMail', false, _('Send via mail'), '407');
1125 $pwdMailCheckbox->setTableRowsToShow(['lamPasswordChangeMailAddress']);
1126 $container->add($pwdMailCheckbox);
1127 if ($_SESSION['config']->getLamProMailAllowAlternateAddress() != 'false') {
1128 $alternateMail = '';
1129 $pwdResetModule = $this->getAccountModule('passwordSelfReset');
1130 if ($pwdResetModule !== null) {
1131 $backupMail = $pwdResetModule->getBackupEmail();
1132 if (!empty($backupMail)) {
1133 $alternateMail = $pwdResetModule->getBackupEmail();
1134 }
1135 }
1136 $alternateMailInput = new htmlResponsiveInputField(_('Alternate recipient'), 'lamPasswordChangeMailAddress', $alternateMail, '410');
1137 $container->add($alternateMailInput);
1138 }
1139 }
1140 if (isLAMProVersion() && ($this->attributes_orig !== null) && (getSmsPhoneNumber($this->attributes_orig) !== null)) {
1141 $container->add(new htmlResponsiveInputCheckbox('lamPasswordChangeSendSms', false, _('Send via SMS'), '412'));
1142 }
1143 $container->addVerticalSpacer('0.25rem');
1144 // password modules
1145 $moduleContainer = new htmlGroup();
1146 foreach ($this->module as $name => $module) {
1147 if (($module instanceof passwordService) && $module->managesPasswordAttributes()) {
1148 $printContainer = true;
1149 $buttonImage = $module->getIcon();
1150 if ($buttonImage != null) {
1151 if (!(str_starts_with($buttonImage, 'http')) && !(str_starts_with($buttonImage, '/'))) {
1152 $buttonImage = '../../graphics/' . $buttonImage;
1153 }
1154 $moduleContainer->addElement(new htmlImage($buttonImage, '16px', '16px', getModuleAlias($name, $this->type->getScope())));
1155 }
1156 $moduleContainer->addElement(new htmlInputCheckbox('password_cb_' . $name, true));
1157 $moduleContainer->addElement(new htmlLabel('password_cb_' . $name, getModuleAlias($name, $this->type->getScope())));
1158 $moduleContainer->addElement(new htmlSpacer('10px', null));
1159 }
1160 }
1161 $container->add($moduleContainer);
1162 // buttons
1163 $container->addVerticalSpacer('1rem');
1164 $buttonGroup = new htmlGroup();
1165 $okButton = new htmlButton('changePwdOk', _('Ok'));
1166 $okButton->setCSSClasses(['lam-primary']);
1167 $okButton->setOnClick("passwordHandleInput('false', '../misc/ajax.php?function=passwordChange&editKey="
1168 . htmlspecialchars($this->base) . "', '" . getSecurityTokenName() . "', '" . getSecurityTokenValue()
1169 . "', '" . _('Ok') . "'); return false;");
1170 $buttonGroup->addElement($okButton);
1171 $randomButton = new htmlButton('changePwdRandom', _('Set random password'));
1172 $randomButton->setCSSClasses(['lam-secondary']);
1173 $randomButton->setOnClick("passwordHandleInput('true', '../misc/ajax.php?function=passwordChange&editKey="
1174 . htmlspecialchars($this->base) . "', '" . getSecurityTokenName() . "', '" . getSecurityTokenValue()
1175 . "', '" . _('Ok') . "'); return false;");
1176 $buttonGroup->addElement($randomButton);
1177 $cancelButton = new htmlButton('changePwdCancel', _('Cancel'));
1178 $cancelButton->setOnClick("document.querySelector('.modal-pwd-options').classList.remove('show-modal'); return false;");
1179 $buttonGroup->addElement($cancelButton);
1180 $container->add($buttonGroup);
1181 // generate HTML
1182 if ($printContainer) {
1183 parseHtml(null, $container, [], false);
1184 }
1185 echo "</div>\n";
1186 echo "</div>\n";
1187 }
1188
1189 /**
1190 * Sets the new password in all selected account modules.
1191 *
1192 * @param array<string, string|string[]> $input input parameters
1193 * @return array<string, bool|string> result
1194 */
1195 public function setNewPassword($input): array {
1196 $password1 = $input['password1'];
1197 $password2 = $input['password2'];
1198 $random = $input['random'] === 'true';
1199 $modules = [];
1200 foreach ($input['modules'] as $moduleName) {
1201 $moduleName = str_replace('password_cb_', '', $moduleName);
1202 if (array_key_exists($moduleName, $this->module)) {
1203 $modules[] = $moduleName;
1204 }
1205 }
1206 $return = [
1207 'messages' => '',
1208 'errorsOccurred' => 'false'
1209 ];
1210 $sendMail = isset($input['sendMail']) && ($input['sendMail'] == 'true');
1211 $sendSms = isset($input['sendSms']) && ($input['sendSms'] == 'true');
1212 if ($random) {
1213 $password1 = generateRandomPassword();
1214 if (!$sendMail && !$sendSms) {
1215 $return['messages'] .= StatusMessage('INFO', _('The password was set to:') . ' ' . htmlspecialchars($password1), '', [], true);
1216 }
1217 }
1218 else {
1219 // check if passwords match
1220 if ($password1 != $password2) {
1221 $return['messages'] .= StatusMessage('ERROR', _('Passwords are different!'), '', [], true);
1222 $return['errorsOccurred'] = 'true';
1223 }
1224 // check password strength
1225 $pwdPolicyResult = checkPasswordStrength($password1, null, []);
1226 if (!$pwdPolicyResult->isValid()) {
1227 $return['messages'] .= StatusMessage('ERROR', $pwdPolicyResult->getTextMessage(), '', [], true);
1228 $return['errorsOccurred'] = 'true';
1229 }
1230 }
1231 $forcePasswordChange = false;
1232 if (isset($input['forcePasswordChange']) && ($input['forcePasswordChange'] == 'true')) {
1233 $forcePasswordChange = true;
1234 }
1235 $return['forcePasswordChange'] = $forcePasswordChange;
1236 if ($return['errorsOccurred'] === 'false') {
1237 // set new password
1238 foreach ($this->module as $module) {
1239 if ($module instanceof passwordService) {
1240 $messages = $module->passwordChangeRequested($password1, $modules, $forcePasswordChange);
1241 for ($m = 0; $m < count($messages); $m++) {
1242 if ($messages[$m][0] == 'ERROR') {
1243 $return['errorsOccurred'] = 'true';
1244 }
1245 if (count($messages[$m]) === 2) {
1246 $return['messages'] .= StatusMessage($messages[$m][0], $messages[$m][1], '', [], true);
1247 }
1248 elseif (count($messages[$m]) === 3) {
1249 $return['messages'] .= StatusMessage($messages[$m][0], $messages[$m][1], $messages[$m][2], [], true);
1250 }
1251 elseif (count($messages[$m]) === 4) {
1252 $return['messages'] .= StatusMessage($messages[$m][0], $messages[$m][1], $messages[$m][2], $messages[$m][3], true);
1253 }
1254 }
1255 }
1256 }
1257 }
1258 if (isLAMProVersion() && $sendMail) {
1259 $this->sendPasswordViaMail = $password1;
1260 if (($_SESSION['config']->getLamProMailAllowAlternateAddress() != 'false') && !empty($input['sendMailAlternateAddress'])) {
1261 if (!get_preg($input['sendMailAlternateAddress'], 'email')) {
1262 $return['messages'] .= StatusMessage('ERROR', _('Alternate recipient'), _('Please enter a valid email address!'), [], true);
1263 $return['errorsOccurred'] = 'true';
1264 }
1265 $this->sendPasswordViaMailAlternateAddress = $input['sendMailAlternateAddress'];
1266 }
1267 }
1268 if (isLAMProVersion() && $sendSms) {
1269 $this->sendPasswordViaSms = $password1;
1270 }
1271 if ($return['errorsOccurred'] === 'false') {
1272 $return['messages'] .= StatusMessage('INFO', _('The new password will be stored in the directory after you save this account.'), '', [], true);
1273 $this->extraInfoAttributes['INFO.passwordUpdated'] = 'yes';
1274 $this->extraInfoAttributes['INFO.forcePasswordChange'] = $forcePasswordChange ? 'yes' : 'no';
1275 $this->extraInfoAttributes['INFO.passwordChangeModules'] = implode(', ', $modules);
1276 $this->extraInfoAttributes['INFO.passwordChangeType'] = $random ? 'random' : 'manual';
1277 $this->extraInfoAttributes['INFO.sendPasswordViaEmail'] = $sendMail ? 'yes' : 'no';
1278 $this->extraInfoAttributes['INFO.sendPasswordViaSms'] = $sendSms ? 'yes' : 'no';
1279 if (!empty($input['sendMailAlternateAddress'])) {
1280 $this->extraInfoAttributes['INFO.sendPasswordAlternateAddress'] = $input['sendMailAlternateAddress'];
1281 }
1282 }
1283 return $return;
1284 }
1285
1286 /**
1287 * Returns if any module manages the mail attribute.
1288 *
1289 * @return boolean mail is managed
1290 */
1291 private function anyModuleManagesMail() {
1292 foreach ($this->module as $mod) {
1293 if (in_array('mail', $mod->getManagedAttributes($this->get_type()->getId()))) {
1294 return true;
1295 }
1296 }
1297 return false;
1298 }
1299
1300 /**
1301 * Prints common controls like the save button and the ou selection.
1302 */
1303 private function printCommonControls(): void {
1304 $row = new htmlResponsiveRow();
1305 $row->setCSSClasses(['maxrow']);
1306 $leftButtonGroup = new htmlGroup();
1307 $leftButtonGroup->alignment = htmlElement::ALIGN_LEFT;
1308 if (checkIfWriteAccessIsAllowed($this->type->getId()) && !$this->postSaveErrorsOccurred) {
1309 // save button
1310 $saveButton = new htmlButton('accountContainerSaveAccount', _('Save'));
1311 $saveButton->setCSSClasses(['fullwidth-mobile-only lam-primary']);
1312 $leftButtonGroup->addElement($saveButton);
1313 // set password button
1314 if ($this->showSetPasswordButton()) {
1315 $leftButtonGroup->addElement(new htmlSpacer('15px', null, ['hide-on-mobile']));
1316 $passwordButton = new htmlButton('accountContainerPassword', _('Set password'));
1317 $passwordButton->setCSSClasses(['fullwidth-mobile-only lam-secondary']);
1318 $passwordButton->setOnClick("window.lam.dialog.showModal('.modal-pwd-options');");
1319 $leftButtonGroup->addElement($passwordButton);
1320 }
1321 // delete button
1322 if (!$this->isNewAccount && checkIfDeleteEntriesIsAllowed($this->get_type()->getId())) {
1323 $leftButtonGroup->addElement(new htmlSpacer('15px', null, ['hide-on-mobile']));
1324 $deleteButton = new htmlButton('accountContainerDelete', _('Delete'));
1325 $deleteButton->setCSSClasses(['fullwidth-mobile-only lam-danger']);
1326 $leftButtonGroup->addElement($deleteButton);
1327 }
1328 $leftButtonGroup->addElement(new htmlSpacer('15px', null, ['hide-on-mobile']));
1329 // reset button
1330 if (!$this->isNewAccount) {
1331 $resetButton = new htmlButton('accountContainerReset', _('Reset changes'));
1332 $resetButton->setCSSClasses(['fullwidth-mobile-only']);
1333 $leftButtonGroup->addElement($resetButton);
1334 }
1335 }
1336 $type = $this->type->getBaseType();
1337 $backToListButton = new htmlButton('accountContainerBackToList', $type->LABEL_BACK_TO_ACCOUNT_LIST);
1338 $backToListButton->setCSSClasses(['fullwidth-mobile-only']);
1339 $leftButtonGroup->addElement($backToListButton);
1340 $row->add($leftButtonGroup, 12, 9);
1341
1342 $rightGroup = new htmlGroup();
1343 if (checkIfWriteAccessIsAllowed($this->type->getId()) && !$this->postSaveErrorsOccurred) {
1344 // profile selection
1345 $accountProfilePersistenceManager = new AccountProfilePersistenceManager();
1346 $profilelist = $accountProfilePersistenceManager->getAccountProfileNames($this->type->getId(), $_SESSION['config']->getName());
1347 if (count($profilelist) > 0) {
1348 $profileButton = new htmlButton('accountContainerLoadProfileButton', _('Load profile'));
1349 $profileButton->setOnClick('confirmLoadProfile(\'' . _('Load profile') . '\', \'' . _('This may overwrite existing values with profile data. Continue?') . '\','
1350 . ' \'' . _('Ok') . '\', \'' . _('Cancel') . '\', event); return false;');
1351 $profileButton->addDataAttribute('lastprofile', $this->lastLoadedProfile);
1352 $profileListOptions = [];
1353 foreach ($profilelist as $profileName) {
1354 $profileListOptions[$profileName] = $profileName;
1355 }
1356 $profileButton->addDataAttribute('profiles', json_encode($profileListOptions));
1357 $rightGroup->addElement($profileButton);
1358 $rightGroup->addElement(new htmlSpacer('1px', null));
1359 $rightGroup->addElement(new htmlHelpLink('401'));
1360 }
1361 }
1362 $row->add($rightGroup, 12, 3, 3, 'text-right');
1363
1364 parseHtml(null, $row, [], false);
1365 }
1366
1367 /**
1368 * Returns if the page should show a button to set the password.
1369 *
1370 * @return bool show or hide button
1371 */
1372 private function showSetPasswordButton(): bool {
1373 foreach ($this->module as $module) {
1374 if (($module instanceof passwordService) && $module->managesPasswordAttributes()) {
1375 return true;
1376 }
1377 }
1378 return false;
1379 }
1380
1381 /**
1382 * Prints the header of the account pages.
1383 */
1384 private function printPageHeader(): void {
1385 if (!empty($_POST)) {
1386 validateSecurityToken();
1387 }
1388 include_once __DIR__ . '/adminHeader.inc';
1389 echo "<form id=\"inputForm\" enctype=\"multipart/form-data\" action=\"edit.php?editKey=" . htmlspecialchars($this->base) . "\" method=\"post\" onSubmit=\"window.lam.utility.saveScrollPosition('inputForm')\" autocomplete=\"off\" novalidate=\"novalidate\">\n";
1390 echo '<input type="hidden" name="' . getSecurityTokenName() . '" value="' . getSecurityTokenValue() . '">';
1391 }
1392
1393 /**
1394 * Prints the footer of the account pages.
1395 */
1396 private function printPageFooter(): void {
1397 echo "</form>\n";
1398 include_once __DIR__ . '/adminFooter.inc';
1399 }
1400
1401 /**
1402 * Prints the HTML code to notify the user about the successful saving.
1403 *
1404 * @param array<string|string[]>[] $messages array which contains status messages. Each entry is an array containing the status message parameters.
1405 */
1406 private function printSuccessPage($messages): void {
1407 $this->printPageHeader();
1408 // Show success message
1409 $text = ($this->dn_orig == '') ? _("Account was created successfully.") : _("Account was modified successfully.");
1410 echo "<div smallPaddingContent\">";
1411
1412 $container = new htmlResponsiveRow();
1413 $container->addVerticalSpacer('2rem');
1414 // show messages
1415 for ($i = 0; $i < count($messages); $i++) {
1416 if (count($messages[$i]) === 2) {
1417 $message = new htmlStatusMessage($messages[$i][0], $messages[$i][1]);
1418 $container->add($message);
1419 }
1420 else {
1421 $message = new htmlStatusMessage($messages[$i][0], $messages[$i][1], $messages[$i][2]);
1422 $container->add($message);
1423 }
1424 }
1425 $message = new htmlStatusMessage('INFO', _('LDAP operation successful.'), $text);
1426 $container->add($message);
1427 $container->addVerticalSpacer('2rem');
1428
1429 $type = $this->type->getBaseType();
1430 $buttonGroup = new htmlGroup();
1431 $backToListButton = new htmlButton('accountContainerBackToList', $type->LABEL_BACK_TO_ACCOUNT_LIST);
1432 $backToListButton->setCSSClasses(['lam-primary fullwidth-mobile-only']);
1433 $buttonGroup->addElement($backToListButton);
1434 $buttonGroup->addElement(new htmlSpacer('1rem', null));
1435 if (checkIfNewEntriesAreAllowed($this->type->getId())) {
1436 $createButton = new htmlButton('accountContainerCreateAgain', $type->LABEL_CREATE_ANOTHER_ACCOUNT);
1437 $createButton->setCSSClasses(['lam-secondary fullwidth-mobile-only']);
1438 $buttonGroup->addElement($createButton);
1439 $buttonGroup->addElement(new htmlSpacer('0.5rem', null));
1440 }
1441 $pdfStructurePersistenceManager = new PdfStructurePersistenceManager();
1442 $pdfStructures = $pdfStructurePersistenceManager->getPDFStructures($_SESSION['config']->getName(), $this->type->getId());
1443 if ($pdfStructures) {
1444 $pdfButton = new htmlButton('accountContainerCreatePDF', _('Create PDF file'));
1445 $pdfButton->setCSSClasses(['lam-secondary fullwidth-mobile-only']);
1446 $buttonGroup->addElement($pdfButton);
1447 $buttonGroup->addElement(new htmlSpacer('1rem', null));
1448 }
1449 $backToEditButton = new htmlButton('accountContainerBackToEdit', _('Edit again'));
1450 $backToEditButton->setCSSClasses(['fullwidth-mobile-only']);
1451 $buttonGroup->addElement($backToEditButton);
1452 $container->add($buttonGroup);
1453
1454 parseHtml(null, $container, [], false);
1455
1456 echo "</div>\n";
1457 $this->printPageFooter();
1458 }
1459
1460 /**
1461 * Checks if the user requested to load a profile.
1462 *
1463 * @return bool true, if profile was loaded
1464 */
1465 private function loadProfileIfRequested(): bool {
1466 if (isset($_POST['accountContainerLoadProfile']) && isset($_POST['accountContainerSelectLoadProfile'])) {
1467 $accountProfilePersistenceManager = new AccountProfilePersistenceManager();
1468 $profile = $accountProfilePersistenceManager->loadAccountProfile($this->type->getId(), $_POST['accountContainerSelectLoadProfile'], $_SESSION['config']->getName());
1469 $this->lastLoadedProfile = $_POST['accountContainerSelectLoadProfile'];
1470 // pass profile to each module
1471 $modules = array_keys($this->module);
1472 foreach ($modules as $module) {
1473 $this->module[$module]->load_profile($profile);
1474 }
1475 if (isset($profile['ldap_rdn'][0])
1476 && in_array($profile['ldap_rdn'][0], getRDNAttributes($this->type->getId()))) {
1477 $this->rdn = $profile['ldap_rdn'][0];
1478 }
1479 if (isset($profile['ldap_suffix'][0]) && ($profile['ldap_suffix'][0] != '-')) {
1480 $this->dnSuffix = $profile['ldap_suffix'][0];
1481 }
1482 return true;
1483 }
1484 return false;
1485 }
1486
1487 /**
1488 * Prints the HTML code of the module tabs.
1489 */
1490 private function printModuleTabs(): void {
1491 echo '<ul class="lam-vertical-tabs-navigation">';
1492 // Loop for each module
1493 for ($i = 0; $i < count($this->order); $i++) {
1494 $buttonStatus = $this->module[$this->order[$i]]->getButtonStatus();
1495 $alias = $this->module[$this->order[$i]]->get_alias();
1496 // skip hidden buttons
1497 if ($buttonStatus == 'hidden') {
1498 continue;
1499 }
1500 $buttonImage = $this->module[$this->order[$i]]->getIcon();
1501 $activatedClass = '';
1502 if ($this->order[$this->current_page] == $this->order[$i]) {
1503 $activatedClass = ' lam-vertical-tabs-selected';
1504 }
1505 // print button
1506 echo '<li class="lam-vertical-tabs ' . $activatedClass . '">';
1507 echo "<button class=\"lam-account-type " . $activatedClass . "\" name=\"form_main_" . $this->order[$i] . "\"";
1508 if ($buttonStatus == 'disabled') {
1509 echo " disabled";
1510 }
1511 echo ' >';
1512 if ($buttonImage != null) {
1513 if (!(str_starts_with($buttonImage, 'http')) && !(str_starts_with($buttonImage, '/'))) {
1514 $buttonImage = '../../graphics/' . $buttonImage;
1515 }
1516 echo "<img height=32 width=32 class=\"align-middle\" style=\"padding: 3px;\" alt=\"\" src=\"$buttonImage\">&nbsp;";
1517 }
1518 echo '<span class="hide-on-mobile">';
1519 echo $alias;
1520 echo '<span>';
1521 echo "</button>\n";
1522 echo "</li>\n";
1523 }
1524 echo '</ul>';
1525 }
1526
1527 /**
1528 * This function checks which LDAP attributes have changed while the account was edited.
1529 *
1530 * @param array<string, string[]|string> $attributes list of current LDAP attributes
1531 * @param array<string, string[]|string> $orig list of old attributes when account was loaded
1532 * @return array<string, array<string, array<string, string[]>>> an array which can be passed to $this->saveAccount()
1533 */
1534 public function save_module_attributes($attributes, $orig): array {
1535 $return = [];
1536 $toModify = [];
1537 $notChanged = [];
1538 // cleanup
1539 foreach ($attributes as $name => &$values) {
1540 // remove empty values
1541 $values = array_values($values);
1542 for ($i = 0; $i < count($values); $i++) {
1543 if ($values[$i] === '') {
1544 unset($values[$i]);
1545 }
1546 }
1547 $values = array_values($values);
1548 // remove empty list of values
1549 if (count($values) === 0) {
1550 unset($attributes[$name]);
1551 }
1552 }
1553 // find deleted attributes (in $orig but no longer in $attributes)
1554 foreach ($orig as $name => $value) {
1555 if (count($value) === 0) {
1556 continue;
1557 }
1558 if (!isset($attributes[$name]) || (count($attributes[$name]) === 0)) {
1559 $toModify[$name] = [];
1560 }
1561 }
1562 // find changed attributes
1563 foreach ($attributes as $name => $value) {
1564 // new/changed attributes
1565 if ((!isset($orig[$name]) && (count($value) !== 0))
1566 || (isset($orig[$name]) && !areArrayContentsEqual($value, $orig[$name]))) {
1567 $toModify[$name] = $value;
1568 }
1569 // unchanged attributes
1570 else {
1571 $notChanged[$name] = $value;
1572 }
1573 }
1574 if ($toModify !== []) {
1575 $return[$this->dn_orig]['modify'] = $toModify;
1576 }
1577 if ($notChanged !== []) {
1578 $return[$this->dn_orig]['notchanged'] = $notChanged;
1579 }
1580 return $return;
1581 }
1582
1583 /**
1584 * Loads an LDAP account with the given DN.
1585 *
1586 * @param string $dn the DN of the account
1587 * @param array<string, string> $infoAttributes list of additional informational attributes that are added to the LDAP attributes
1588 * E.g. this is used to inject the clear text password in the file upload. Informational attribute names must start with "INFO.".
1589 * @return array<string|string[]>[] error messages
1590 */
1591 public function load_account($dn, $infoAttributes = []): array {
1592 if (!str_ends_with(strtolower($dn), strtolower($this->type->getSuffix()))) {
1593 logNewMessage(LOG_ERR, 'User tried to access entry of type ' . $this->type->getId() . ' outside suffix ' . $this->type->getSuffix());
1594 die();
1595 }
1596 logNewMessage(LOG_DEBUG, "Edit account " . $dn);
1597 $this->extraInfoAttributes['INFO.isNewAccount'] = 'no';
1598 $this->extraInfoAttributes['INFO.passwordUpdated'] = 'no';
1599 $this->extraInfoAttributes['INFO.passwordChangeType'] = 'none';
1600 $this->module = [];
1601 $modules = $_SESSION['config']->get_AccountModules($this->type->getId());
1602 $filter = empty($this->type->getAdditionalLdapFilter()) ? '(objectClass=*)' : $this->type->getAdditionalLdapFilter();
1603 $searchAttrs = ['*', '+'];
1604 foreach ($modules as $module) {
1605 $modTmp = new $module($this->type->getScope());
1606 $searchAttrs = array_merge($searchAttrs, $modTmp->getManagedHiddenAttributes($this->type->getId()));
1607 }
1608 $result = @ldap_read($_SESSION['ldap']->server(), $dn, $filter, $searchAttrs, 0, 0, 0, LDAP_DEREF_NEVER);
1609 if (!$result) {
1610 return [["ERROR", _("Unable to load LDAP entry:") . " " . htmlspecialchars($dn), getDefaultLDAPErrorString($_SESSION['ldap']->server())]];
1611 }
1612 $entry = @ldap_first_entry($_SESSION['ldap']->server(), $result);
1613 if (!$entry) {
1614 return [["ERROR", _("Unable to load LDAP entry:") . " " . htmlspecialchars($dn), getDefaultLDAPErrorString($_SESSION['ldap']->server())]];
1615 }
1616 $this->dnSuffix = extractDNSuffix($dn);
1617 $this->dn_orig = $dn;
1618 // extract RDN
1619 $this->rdn = extractRDNAttribute($dn);
1620 $attr = ldap_get_attributes($_SESSION['ldap']->server(), $entry);
1621 $attr = [$attr];
1622 cleanLDAPResult($attr);
1623 $attr = $attr[0];
1624 // fix spelling errors
1625 $attr = $this->fixLDAPAttributes($attr, $modules);
1626 // get binary attributes
1627 $binaryAttr = ['jpegPhoto'];
1628 for ($i = 0; $i < count($binaryAttr); $i++) {
1629 if (isset($attr[$binaryAttr[$i]][0])) {
1630 $binData = ldap_get_values_len($_SESSION['ldap']->server(), $entry, $binaryAttr[$i]);
1631 unset($binData['count']);
1632 $attr[$binaryAttr[$i]] = $binData;
1633 }
1634 }
1635 // add informational attributes
1636 $attr = array_merge($attr, $infoAttributes);
1637 // save original attributes
1638 $this->attributes_orig = $attr;
1639
1640 foreach ($modules as $module) {
1641 if (!isset($this->module[$module])) {
1642 $this->module[$module] = new $module($this->type->getScope());
1643 $this->module[$module]->init($this->base);
1644 }
1645 $this->module[$module]->load_attributes($attr);
1646 }
1647
1648 // sort module buttons
1649 $this->sortModules();
1650 // get titles
1651 $typeObject = $this->type->getBaseType();
1652 $this->titleBarIcon = $typeObject->buildAccountStatusIcon($this);
1653 $this->titleBarTitle = $typeObject->getTitleBarTitle($this);
1654 $this->titleBarSubtitle = $typeObject->getTitleBarSubtitle($this);
1655 // change the initial page if needed
1656 if (!empty($_GET['initialTab']) && in_array($_GET['initialTab'], $this->order)) {
1657 $this->current_page = array_search($_GET['initialTab'], $this->order);
1658 if (!empty($_GET['initialSubpage'])
1659 && method_exists($this->module[$this->order[$this->current_page]], 'display_html_' . $_GET['initialSubpage'])) {
1660 $this->subpage = $_GET['initialSubpage'];
1661 }
1662 }
1663 return [];
1664 }
1665
1666 /**
1667 * Fixes spelling errors in the attribute names.
1668 *
1669 * @param array<string, string[]|string>|null $attributes LDAP attributes
1670 * @param string[] $modules list of active modules
1671 * @return array<string, string[]|string> fixed attributes
1672 */
1673 public function fixLDAPAttributes($attributes, $modules): array {
1674 if (!is_array($attributes)) {
1675 return [];
1676 }
1677 $keys = array_keys($attributes);
1678 // get correct object class names, aliases and attributes
1679 $objectClasses = [];
1680 $aliases = [];
1681 $ldapAttributesTemp = [];
1682 foreach ($modules as $module) {
1683 $moduleObj = moduleCache::getModule($module, $this->type->getScope());
1684 $objectClasses = array_merge($objectClasses, $moduleObj->getManagedObjectClasses($this->type->getId()));
1685 $aliases = array_merge($aliases, $moduleObj->getLDAPAliases($this->type->getId()));
1686 $ldapAttributesTemp = array_merge($ldapAttributesTemp,
1687 $moduleObj->getManagedAttributes($this->type->getId()),
1688 $moduleObj->getManagedHiddenAttributes($this->type->getId()));
1689 }
1690 // build lower-case attribute names
1691 $ldapAttributes = [];
1692 for ($i = 0; $i < count($ldapAttributesTemp); $i++) {
1693 $ldapAttributes[strtolower($ldapAttributesTemp[$i])] = $ldapAttributesTemp[$i];
1694 }
1695 $ldapAttributesKeys = array_keys($ldapAttributes);
1696 // convert alias names to lower-case (for easier comparison)
1697 $aliasKeys = array_keys($aliases);
1698 for ($i = 0; $i < count($aliasKeys); $i++) {
1699 if ($aliasKeys[$i] != strtolower($aliasKeys[$i])) {
1700 $aliases[strtolower($aliasKeys[$i])] = $aliases[$aliasKeys[$i]];
1701 unset($aliases[$aliasKeys[$i]]);
1702 $aliasKeys[$i] = strtolower($aliasKeys[$i]);
1703 }
1704 }
1705 // fix object classes and attributes
1706 for ($i = 0; $i < count($keys); $i++) {
1707 // check object classes
1708 if (strtolower($keys[$i]) === 'objectclass') {
1709 // fix object class attribute
1710 if ($keys[$i] != 'objectClass') {
1711 $temp = $attributes[$keys[$i]];
1712 unset($attributes[$keys[$i]]);
1713 $attributes['objectClass'] = $temp;
1714 }
1715 // fix object classes
1716 for ($attrClass = 0; $attrClass < count($attributes['objectClass']); $attrClass++) {
1717 for ($modClass = 0; $modClass < count($objectClasses); $modClass++) {
1718 if (strtolower($attributes['objectClass'][$attrClass]) === strtolower($objectClasses[$modClass])) {
1719 if ($attributes['objectClass'][$attrClass] != $objectClasses[$modClass]) {
1720 unset($attributes['objectClass'][$attrClass]);
1721 $attributes['objectClass'][] = $objectClasses[$modClass];
1722 }
1723 break;
1724 }
1725 }
1726 }
1727 }
1728 elseif (in_array(strtolower($keys[$i]), $aliasKeys)) {
1729 // fix aliases
1730 $attributes[$aliases[strtolower($keys[$i])]] = $attributes[$keys[$i]];
1731 unset($attributes[$keys[$i]]);
1732 }
1733 elseif (in_array(strtolower($keys[$i]), $ldapAttributesKeys)) {
1734 if ($keys[$i] != $ldapAttributes[strtolower($keys[$i])]) {
1735 $attributes[$ldapAttributes[strtolower($keys[$i])]] = $attributes[$keys[$i]];
1736 unset($attributes[$keys[$i]]);
1737 }
1738 }
1739 }
1740 return $attributes;
1741 }
1742
1743 /**
1744 * This function will prepare the object for a new account.
1745 */
1746 public function new_account(): void {
1747 logNewMessage(LOG_DEBUG, "New account with type " . $this->type->getId());
1748 $this->isNewAccount = true;
1749 $this->lastLoadedProfile = 'default';
1750 $this->initModules();
1751 $this->extraInfoAttributes['INFO.isNewAccount'] = 'yes';
1752 $this->extraInfoAttributes['INFO.passwordUpdated'] = 'no';
1753 // sort module buttons
1754 $this->sortModules();
1755 $profileName = 'default';
1756 $profileCookieKey = 'defaultProfile_' . $this->get_type()->getId();
1757 try {
1758 $accountProfilePersistenceManager = new AccountProfilePersistenceManager();
1759 if (!empty($_COOKIE[$profileCookieKey])) {
1760 $cookieProfileName = $_COOKIE[$profileCookieKey];
1761 if ($accountProfilePersistenceManager->isAccountProfileExisting($this->get_type()->getId(), $cookieProfileName, $_SESSION['config']->getName())) {
1762 $profileName = $cookieProfileName;
1763 $this->lastLoadedProfile = $cookieProfileName;
1764 }
1765 }
1766 $profile = $accountProfilePersistenceManager->loadAccountProfile($this->type->getId(), $profileName, $_SESSION['config']->getName());
1767 // pass profile to each module
1768 $modules = array_keys($this->module);
1769 foreach ($modules as $module) {
1770 $this->module[$module]->load_profile($profile);
1771 }
1772 if (isset($profile['ldap_rdn'][0]) && in_array($profile['ldap_rdn'][0], getRDNAttributes($this->type->getId()))) {
1773 $this->rdn = $profile['ldap_rdn'][0];
1774 }
1775 if (isset($profile['ldap_suffix'][0]) && ($profile['ldap_suffix'][0] != '-')) {
1776 $this->dnSuffix = $profile['ldap_suffix'][0];
1777 }
1778 }
1779 catch (LAMException $e) {
1780 logNewMessage(LOG_ERR, $e->getTitle());
1781 }
1782 // get titles
1783 $typeObject = $this->type->getBaseType();
1784 $this->titleBarIcon = $typeObject->buildAccountStatusIcon($this);
1785 $this->titleBarTitle = $typeObject->getTitleBarTitle($this);
1786 $this->titleBarSubtitle = $typeObject->getTitleBarSubtitle($this);
1787 }
1788
1789 /**
1790 * Copies the data from the given account to this one.
1791 *
1792 * @param string $copyDn DN to copy from
1793 */
1794 public function copyFromExistingAccount(string $copyDn): void {
1795 $copyData = ldapGetDN($copyDn, ['*', '+']);
1796 $modules = $_SESSION['config']->get_AccountModules($this->type->getId());
1797 $copyData = $this->fixLDAPAttributes($copyData, $modules);
1798 foreach ($this->module as $accountModule) {
1799 $accountModule->loadAttributesFromAccountCopy($copyData);
1800 }
1801 }
1802
1803 /**
1804 * Creates the account modules and initializes them.
1805 */
1806 public function initModules(): void {
1807 $modules = $_SESSION['config']->get_AccountModules($this->type->getId());
1808 foreach ($modules as $module) {
1809 $this->module[$module] = new $module($this->type->getScope());
1810 $this->module[$module]->init($this->base);
1811 }
1812 }
1813
1814 /**
1815 * This function will save an account to the LDAP database.
1816 *
1817 * @return array<string|string[]>[] list of status messages
1818 */
1819 private function save_account(): array {
1820 if (!checkIfWriteAccessIsAllowed($this->type->getId())) {
1821 die();
1822 }
1823 $this->finalDN = $this->dn_orig;
1824 $errors = [];
1825 $module = array_keys($this->module);
1826 $attributes = [];
1827 // load attributes
1828 foreach ($module as $singlemodule) {
1829 // load changes
1830 $temp = $this->module[$singlemodule]->save_attributes();
1831 // merge changes
1832 $DNs = array_keys($temp);
1833 $attributes = array_merge_recursive($temp, $attributes);
1834 for ($i = 0; $i < count($DNs); $i++) {
1835 $ops = array_keys($temp[$DNs[$i]]);
1836 for ($j = 0; $j < count($ops); $j++) {
1837 $attrs = array_keys($temp[$DNs[$i]][$ops[$j]]);
1838 for ($k = 0; $k < count($attrs); $k++) {
1839 $attributes[$DNs[$i]][$ops[$j]][$attrs[$k]] = array_values(array_unique($attributes[$DNs[$i]][$ops[$j]][$attrs[$k]]));
1840 }
1841 }
1842 }
1843 }
1844 // build DN for new accounts and change it for existing ones if needed
1845 if (isset($attributes[$this->dn_orig]['modify'][$this->rdn][0])) {
1846 $this->finalDN = $this->rdn . '=' . ldap_escape($attributes[$this->dn_orig]['modify'][$this->rdn][0], '', LDAP_ESCAPE_DN) . ',' . $this->dnSuffix;
1847 if ($this->dn_orig != $this->finalDN) {
1848 $attributes[$this->finalDN] = $attributes[$this->dn_orig];
1849 unset($attributes[$this->dn_orig]);
1850 }
1851 }
1852 elseif (isset($attributes[$this->dn_orig]['add'][$this->rdn][0])) {
1853 $this->finalDN = $this->rdn . '=' . ldap_escape($attributes[$this->dn_orig]['add'][$this->rdn][0], '', LDAP_ESCAPE_DN) . ',' . $this->dnSuffix;
1854 if ($this->dn_orig != $this->finalDN) {
1855 $attributes[$this->finalDN] = $attributes[$this->dn_orig];
1856 unset($attributes[$this->dn_orig]);
1857 }
1858 }
1859 elseif (isset($attributes[$this->dn_orig]['remove'][$this->rdn][0]) && isset($attributes[$this->dn_orig]['notchanged'][$this->rdn][0])) {
1860 $this->finalDN = $this->rdn . '=' . ldap_escape($attributes[$this->dn_orig]['notchanged'][$this->rdn][0], '', LDAP_ESCAPE_DN) . ',' . $this->dnSuffix;
1861 if ($this->dn_orig != $this->finalDN) {
1862 $attributes[$this->finalDN] = $attributes[$this->dn_orig];
1863 unset($attributes[$this->dn_orig]);
1864 }
1865 }
1866 elseif (!$this->isNewAccount && (($this->dnSuffix != extractDNSuffix($this->dn_orig)) || ($this->rdn != extractRDNAttribute($this->dn_orig)))) {
1867 $this->finalDN = $this->rdn . '=' . ldap_escape($attributes[$this->dn_orig]['notchanged'][$this->rdn][0], '', LDAP_ESCAPE_DN) . ',' . $this->dnSuffix;
1868 $attributes[$this->finalDN] = $attributes[$this->dn_orig];
1869 unset($attributes[$this->dn_orig]);
1870 }
1871 // remove pwdAccountLockedTime attribute change if also userPassword is changed (PPolicy will remove this attribute itself)
1872 if (isset($attributes[$this->finalDN]['modify']['userpassword']) || isset($attributes[$this->finalDN]['remove']['userpassword'])) {
1873 if (isset($attributes[$this->finalDN]['modify']['pwdAccountLockedTime'])) {
1874 unset($attributes[$this->finalDN]['modify']['pwdAccountLockedTime']);
1875 }
1876 if (isset($attributes[$this->finalDN]['remove']['pwdAccountLockedTime'])) {
1877 unset($attributes[$this->finalDN]['remove']['pwdAccountLockedTime']);
1878 }
1879 }
1880 // pre modify actions
1881 $prePostModifyAttributes = $this->extraInfoAttributes;
1882 if (isset($attributes[$this->finalDN]) && is_array($attributes[$this->finalDN])) {
1883 if (isset($attributes[$this->finalDN]['notchanged'])) {
1884 $prePostModifyAttributes = array_merge($prePostModifyAttributes, $attributes[$this->finalDN]['notchanged']);
1885 }
1886 if (isset($attributes[$this->finalDN]['modify'])) {
1887 foreach ($attributes[$this->finalDN]['modify'] as $key => $value) {
1888 $prePostModifyAttributes[$key] = $value;
1889 $prePostModifyAttributes['MOD.' . $key] = $value;
1890 }
1891 }
1892 if (isset($attributes[$this->finalDN]['add'])) {
1893 foreach ($attributes[$this->finalDN]['add'] as $key => $value) {
1894 $prePostModifyAttributes['NEW.' . $key] = $value;
1895 if (isset($prePostModifyAttributes[$key])) {
1896 $prePostModifyAttributes[$key] = array_merge($prePostModifyAttributes[$key], $value);
1897 }
1898 else {
1899 $prePostModifyAttributes[$key] = $value;
1900 }
1901 }
1902 }
1903 if (isset($attributes[$this->finalDN]['remove'])) {
1904 foreach ($attributes[$this->finalDN]['remove'] as $key => $value) {
1905 $prePostModifyAttributes['DEL.' . $key] = $value;
1906 }
1907 }
1908 if (isset($attributes[$this->finalDN]['info'])) {
1909 foreach ($attributes[$this->finalDN]['info'] as $key => $value) {
1910 $prePostModifyAttributes['INFO.' . $key] = $value;
1911 }
1912 }
1913 }
1914 if (!$this->isNewAccount) {
1915 foreach ($this->attributes_orig as $key => $value) {
1916 $prePostModifyAttributes['ORIG.' . $key] = $value;
1917 }
1918 $prePostModifyAttributes['ORIG.dn'][0] = $this->dn_orig;
1919 }
1920 $prePostModifyAttributes['dn'][0] = $this->finalDN;
1921 if (!$this->isNewAccount && ($this->finalDN !== $this->dn_orig)) {
1922 $prePostModifyAttributes['MOD.dn'][0] = $this->finalDN;
1923 }
1924 logNewMessage(LOG_DEBUG, 'Edit page pre/postModify attributes: ' . print_r($prePostModifyAttributes, true));
1925 $preModifyOk = true;
1926 foreach ($module as $singlemodule) {
1927 $preModifyMessages = $this->module[$singlemodule]->preModifyActions($this->isNewAccount, $prePostModifyAttributes);
1928 $errors = array_merge($errors, $preModifyMessages);
1929 for ($i = 0; $i < count($preModifyMessages); $i++) {
1930 if ($preModifyMessages[$i][0] == 'ERROR') {
1931 $preModifyOk = false;
1932 break;
1933 }
1934 }
1935 }
1936 if (!$preModifyOk) {
1937 $errors[] = ['ERROR', _('The operation was stopped because of the above errors.')];
1938 return $errors;
1939 }
1940 // Set to true if a real error has happened
1941 $stopprocessing = false;
1942 $finalDnLower = strtolower($this->finalDN);
1943 $dnOrigLower = ($this->dn_orig !== null) ? strtolower($this->dn_orig) : '';
1944 if (($finalDnLower !== $dnOrigLower) && (unescapeLdapSpecialCharacters($finalDnLower) !== unescapeLdapSpecialCharacters($dnOrigLower))) {
1945 // move existing DN
1946 if ($this->dn_orig != '') {
1947 $removeOldRDN = $_SESSION['ldap']->isActiveDirectory();
1948 if (isset($attributes[$this->finalDN]['modify'])) {
1949 $attributes[$this->finalDN]['modify'] = array_change_key_case($attributes[$this->finalDN]['modify'], CASE_LOWER);
1950 }
1951 $rdnAttr = strtolower(extractRDNAttribute($this->finalDN));
1952 if (isset($attributes[$this->finalDN]['modify'][$rdnAttr])
1953 && (count($attributes[$this->finalDN]['modify'][$rdnAttr]) === 1)
1954 && (($attributes[$this->finalDN]['modify'][$rdnAttr][0] == extractRDNValue($this->finalDN))
1955 || (unescapeLdapSpecialCharacters($attributes[$this->finalDN]['modify'][$rdnAttr][0]) == unescapeLdapSpecialCharacters(extractRDNValue($this->finalDN))))) {
1956 // remove old RDN if attribute is single valued
1957 $removeOldRDN = true;
1958 unset($attributes[$this->finalDN]['modify'][extractRDNAttribute($this->finalDN)]);
1959 }
1960 logNewMessage(LOG_DEBUG, 'Rename ' . $this->dn_orig . ' to ' . $this->finalDN);
1961 $success = ldap_rename($_SESSION['ldap']->server(), $this->dn_orig, $this->getRDN($this->finalDN), $this->getParentDN($this->finalDN), $removeOldRDN);
1962 if ($success) {
1963 logNewMessage(LOG_NOTICE, 'Renamed DN ' . $this->dn_orig . " to " . $this->finalDN);
1964 // do not add attribute value as new one if added via rename operation
1965 if (!empty($attributes[$this->finalDN]['add'][$rdnAttr]) && in_array(extractRDNValue($this->finalDN), $attributes[$this->finalDN]['add'][$rdnAttr])) {
1966 $attributes[$this->finalDN]['add'][$rdnAttr] = array_delete([extractRDNValue($this->finalDN)], $attributes[$this->finalDN]['add'][$rdnAttr]);
1967 if (empty($attributes[$this->finalDN]['add'][$rdnAttr])) {
1968 unset($attributes[$this->finalDN]['add'][$rdnAttr]);
1969 }
1970 }
1971 }
1972 else {
1973 logNewMessage(LOG_ERR, 'Unable to rename DN: ' . $this->dn_orig . ' (' . ldap_error($_SESSION['ldap']->server()) . '). '
1974 . getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
1975 $errors[] = ['ERROR', sprintf(_('Was unable to rename DN: %s.'), $this->dn_orig), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
1976 $stopprocessing = true;
1977 }
1978 }
1979 // create complete new dn
1980 else {
1981 $attr = [];
1982 if (isset($attributes[$this->finalDN]['add']) && is_array($attributes[$this->finalDN]['add'])) {
1983 $attr = array_merge_recursive($attr, $attributes[$this->finalDN]['add']);
1984 }
1985 if (isset($attributes[$this->finalDN]['notchanged']) && is_array($attributes[$this->finalDN]['notchanged'])) {
1986 $attr = array_merge_recursive($attr, $attributes[$this->finalDN]['notchanged']);
1987 }
1988 if (isset($attributes[$this->finalDN]['modify']) && is_array($attributes[$this->finalDN]['modify'])) {
1989 $attr = array_merge_recursive($attr, $attributes[$this->finalDN]['modify']);
1990 }
1991 $success = @ldap_add($_SESSION['ldap']->server(), $this->finalDN, $attr);
1992 if (!$success) {
1993 logNewMessage(LOG_ERR, 'Unable to create DN: ' . $this->finalDN . ' (' . ldap_error($_SESSION['ldap']->server()) . '). '
1994 . getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
1995 $errors[] = ['ERROR', sprintf(_('Was unable to create DN: %s.'), $this->finalDN), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
1996 $stopprocessing = true;
1997 }
1998 else {
1999 logNewMessage(LOG_NOTICE, 'Created DN: ' . $this->finalDN);
2000 }
2001 unset($attributes[$this->finalDN]);
2002 }
2003 }
2004 $DNs = array_keys($attributes);
2005 for ($i = 0; $i < count($DNs); $i++) {
2006 if (!$stopprocessing) {
2007 logNewMessage(LOG_DEBUG, 'Attribute changes for ' . $DNs[$i] . ":\n" . print_r($attributes[$DNs[$i]], true));
2008 // modify attributes
2009 if (!empty($attributes[$DNs[$i]]['modify'])) {
2010 $success = @ldap_mod_replace($_SESSION['ldap']->server(), $DNs[$i], $attributes[$DNs[$i]]['modify']);
2011 if (!$success) {
2012 logNewMessage(LOG_ERR, 'Unable to modify attributes of DN: ' . $DNs[$i] . ' (' . ldap_error($_SESSION['ldap']->server()) . '). '
2013 . getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
2014 logNewMessage(LOG_DEBUG, print_r($attributes[$DNs[$i]]['modify'], true));
2015 $errors[] = ['ERROR', sprintf(_('Was unable to modify attributes of DN: %s.'), $DNs[$i]), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
2016 $stopprocessing = true;
2017 }
2018 else {
2019 logNewMessage(LOG_NOTICE, 'Modified DN: ' . $DNs[$i]);
2020 // check if the password of the currently logged in user was changed
2021 $lamAdmin = $_SESSION['ldap']->getUserName();
2022 if ((strtolower($DNs[$i]) === strtolower($lamAdmin)) && isset($attributes[$DNs[$i]]['info']['userPasswordClearText'][0])) {
2023 $_SESSION['ldap']->tryAndApplyNewPassword($attributes[$DNs[$i]]['info']['userPasswordClearText'][0]);
2024 }
2025 }
2026 }
2027 // add attributes
2028 if (!empty($attributes[$DNs[$i]]['add']) && !$stopprocessing) {
2029 $success = @ldap_mod_add($_SESSION['ldap']->server(), $DNs[$i], $attributes[$DNs[$i]]['add']);
2030 if (!$success) {
2031 logNewMessage(LOG_ERR, 'Unable to add attributes to DN: ' . $DNs[$i] . ' (' . ldap_error($_SESSION['ldap']->server()) . '). '
2032 . getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
2033 $errors[] = ['ERROR', sprintf(_('Was unable to add attributes to DN: %s.'), $DNs[$i]), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
2034 $stopprocessing = true;
2035 }
2036 else {
2037 logNewMessage(LOG_NOTICE, 'Modified DN: ' . $DNs[$i]);
2038 }
2039 }
2040 // remove attributes
2041 if (!empty($attributes[$DNs[$i]]['remove']) && !$stopprocessing) {
2042 $success = @ldap_mod_del($_SESSION['ldap']->server(), $DNs[$i], $attributes[$DNs[$i]]['remove']);
2043 if (!$success) {
2044 logNewMessage(LOG_ERR, 'Unable to delete attributes from DN: ' . $DNs[$i] . ' (' . ldap_error($_SESSION['ldap']->server()) . '). '
2045 . getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
2046 $errors[] = ['ERROR', sprintf(_('Was unable to remove attributes from DN: %s.'), $DNs[$i]), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
2047 $stopprocessing = true;
2048 }
2049 else {
2050 logNewMessage(LOG_NOTICE, 'Modified DN: ' . $DNs[$i]);
2051 }
2052 }
2053 }
2054 }
2055 // send password mail
2056 if (!$stopprocessing && isLAMProVersion() && ($this->sendPasswordViaMail != null)) {
2057 $mailMessages = sendPasswordMail($this->sendPasswordViaMail, $prePostModifyAttributes, $this->sendPasswordViaMailAlternateAddress);
2058 if (count($mailMessages) > 0) {
2059 $errors = array_merge($errors, $mailMessages);
2060 }
2061 $this->sendPasswordViaMail = null;
2062 $this->sendPasswordViaMailAlternateAddress = null;
2063 }
2064 // send password SMS
2065 if (!$stopprocessing && isLAMProVersion() && ($this->sendPasswordViaSms != null)) {
2066 $smsMessages = sendPasswordSms($this->sendPasswordViaSms, $prePostModifyAttributes);
2067 if (count($smsMessages) > 0) {
2068 $errors = array_merge($errors, $smsMessages);
2069 }
2070 $this->sendPasswordViaSms = null;
2071 }
2072 if (!$stopprocessing) {
2073 // post modify actions
2074 foreach ($module as $singlemodule) {
2075 $postMessages = $this->module[$singlemodule]->postModifyActions($this->isNewAccount, $prePostModifyAttributes);
2076 foreach ($postMessages as $postMessage) {
2077 if ($postMessage[0] == 'ERROR') {
2078 $this->postSaveErrorsOccurred = true;
2079 }
2080 }
2081 $errors = array_merge($errors, $postMessages);
2082 }
2083 }
2084 return $errors;
2085 }
2086
2087 /**
2088 * Defines if the LDAP entry has only virtual child entries. This is the case for e.g. LDAP views.
2089 *
2090 * @return bool has only virtual children
2091 */
2092 public function hasOnlyVirtualChildren(): bool {
2093 foreach ($this->module as $module) {
2094 if ($module->hasOnlyVirtualChildren()) {
2095 return true;
2096 }
2097 }
2098 return false;
2099 }
2100
2101 /**
2102 * Returns a list of possible PDF entries for this account.
2103 *
2104 * @param string[] $pdfKeys list of PDF keys that are included in document
2105 * @param string $typeId type id (user, group, host)
2106 * @return array<string, PDFEntry[]> list of key => PDFEntry
2107 */
2108 public function get_pdfEntries($pdfKeys, $typeId): array {
2109 $return = [];
2110 while (($current = current($this->module)) != null) {
2111 $return = array_merge($return, $current->get_pdfEntries($pdfKeys, $typeId));
2112 next($this->module);
2113 }
2114 $dn = $this->dn_orig;
2115 if ($this->finalDN !== null) {
2116 $dn = $this->finalDN;
2117 }
2118 return array_merge($return, ['main_dn' => [new PDFLabelValue(_('DN'), $dn)]]);
2119 }
2120
2121 /**
2122 * Sorts the module buttons for the account page.
2123 */
2124 private function sortModules(): void {
2125 $order = [];
2126 $modules = array_keys($this->module);
2127 $depModules = [];
2128 if ($this->order !== null) {
2129 $currentPage = $this->order[$this->current_page];
2130 }
2131 for ($i = 0; $i < count($modules); $i++) {
2132 // insert waiting modules
2133 for ($w = 0; $w < count($depModules); $w++) {
2134 $dependencies = $this->module[$depModules[$w]]->get_dependencies();
2135 $dependencies = $dependencies['depends'];
2136 $everything_found = true;
2137 for ($d = 0; $d < count($dependencies); $d++) {
2138 if (!in_array($dependencies[$d], $order)) {
2139 $everything_found = false;
2140 break;
2141 }
2142 }
2143 // insert after depending module
2144 if ($everything_found) {
2145 $order[] = $depModules[$w];
2146 unset($depModules[$w]);
2147 $depModules = array_values($depModules);
2148 $w--;
2149 }
2150 }
2151 // check next module
2152 $dependencies = $this->module[$modules[$i]]->get_dependencies();
2153 if (isset($dependencies['depends'])) {
2154 $everything_found = true;
2155 $dependencies = $dependencies['depends'];
2156 for ($d = 0; $d < count($dependencies); $d++) {
2157 if (is_array($dependencies[$d])) { // or-combined dependencies
2158 $noneFound = true;
2159 foreach ($dependencies[$d] as $or) {
2160 if (in_array($or, $order)) {
2161 $noneFound = false;
2162 break;
2163 }
2164 }
2165 if ($noneFound) {
2166 $everything_found = false;
2167 break;
2168 }
2169 }
2170 elseif (!in_array($dependencies[$d], $order)) { // single dependency
2171 $everything_found = false;
2172 break;
2173 }
2174 }
2175 // remove module if dependencies are not satisfied
2176 if (!$everything_found) {
2177 $depModules[] = $modules[$i];
2178 unset($modules[$i]);
2179 $modules = array_values($modules);
2180 $i--;
2181 }
2182 else {
2183 $order[] = $modules[$i];
2184 }
2185 }
2186 else {
2187 $order[] = $modules[$i];
2188 }
2189 }
2190 // add modules which could not be sorted (e.g. because of cyclic dependencies)
2191 if ($depModules !== []) {
2192 for ($i = 0; $i < count($depModules); $i++) {
2193 $order[] = $depModules[$i];
2194 }
2195 }
2196 // move disabled modules to end
2197 $activeModules = [];
2198 $passiveModules = [];
2199 for ($i = 0; $i < count($order); $i++) {
2200 if ($this->module[$order[$i]]->getButtonStatus() == 'enabled') {
2201 $activeModules[] = $order[$i];
2202 }
2203 else {
2204 $passiveModules[] = $order[$i];
2205 }
2206 }
2207 $this->order = array_merge($activeModules, $passiveModules);
2208 // check if ordering changed and current page number must be updated
2209 if (isset($currentPage) && ($currentPage != $this->order[$this->current_page])) {
2210 $this->current_page = array_search($currentPage, $this->order);
2211 }
2212 }
2213
2214 /**
2215 * Returns the RDN part of a given DN.
2216 *
2217 * @param string|null $dn DN
2218 * @return string RDN
2219 */
2220 public function getRDN(?string $dn): string {
2221 if (($dn === "") || ($dn === null)) {
2222 return "";
2223 }
2224 return substr($dn, 0, strpos($dn, ","));
2225 }
2226
2227 /**
2228 * Returns the parent DN of a given DN.
2229 *
2230 * @param string|null $dn DN
2231 * @return string DN
2232 */
2233 private function getParentDN(?string $dn): string {
2234 if (($dn === "") || ($dn === null)) {
2235 return "";
2236 }
2237 return substr($dn, strpos($dn, ",") + 1);
2238 }
2239
2240 /**
2241 * Returns a list of OUs that exist for this account type.
2242 *
2243 * @return string[] OU list
2244 */
2245 public function getOUs(): array {
2246 if ($this->cachedOUs !== null) {
2247 return $this->cachedOUs;
2248 }
2249 $this->cachedOUs = $this->type->getSuffixList();
2250 return $this->cachedOUs;
2251 }
2252
2253 /**
2254 * Replaces POST data with wildcard values from modules.
2255 *
2256 * @param string[] $keyPrefixes POST keys as full name or prefix (e.g. "key" matches "key1")
2257 */
2258 public function replaceWildcardsInPOST($keyPrefixes): void {
2259 $this->replaceWildcardsInArray($keyPrefixes, $_POST);
2260 }
2261
2262 /**
2263 * Replaces data with wildcard values from modules.
2264 *
2265 * @param string[] $keyPrefixes POST keys as full name or prefix (e.g. "key" matches "key1")
2266 * @param array<string, array<int, string>|string> $data list of values that need replacement
2267 */
2268 public function replaceWildcardsInArray($keyPrefixes, &$data): void {
2269 $replacements = [];
2270 foreach ($this->module as $module) {
2271 $replacements = array_merge($replacements, $module->getWildCardReplacements());
2272 }
2273 while (true) {
2274 if (!$this->replaceWildcards($replacements, $keyPrefixes, $data)) {
2275 break;
2276 }
2277 }
2278 }
2279
2280 /**
2281 * Replaces wildcards in an array.
2282 *
2283 * @param array<string, string> $replacements replacements (key => value)
2284 * @param string[] $keyPrefixes prefixes of $data array keys that should be replaced
2285 * @param array<string, array<int, string>|string> $data data array
2286 * @return bool replacement done
2287 */
2288 private function replaceWildcards($replacements, $keyPrefixes, &$data): bool {
2289 $found = false;
2290 foreach ($data as $key => $value) {
2291 foreach ($keyPrefixes as $keyPrefix) {
2292 if (str_starts_with($key, $keyPrefix)) {
2293 if (!is_array($value)) {
2294 $found = $this->doReplace($replacements, $data[$key]) || $found;
2295 }
2296 else {
2297 foreach (array_keys($value) as $valueIndex) {
2298 $found = $this->doReplace($replacements, $data[$key][$valueIndex]) || $found;
2299 }
2300 }
2301 }
2302 }
2303 }
2304 return $found;
2305 }
2306
2307 /**
2308 * Replaces wildcards in a value.
2309 *
2310 * @param array<string, string> $replacements replacements (key => value)
2311 * @param string $value value to perform replacements
2312 * @return bool replacement done
2313 */
2314 private function doReplace($replacements, &$value): bool {
2315 $found = false;
2316 foreach ($replacements as $replKey => $replValue) {
2317 $searchString = '$' . $replKey;
2318 if (str_contains($value, $searchString)) {
2319 $found = true;
2320 $value = str_replace($searchString, $replValue, $value);
2321 }
2322 $searchString = '$_' . $replKey;
2323 if (str_contains($value, $searchString)) {
2324 $found = true;
2325 $value = str_replace($searchString, strtolower($replValue), $value);
2326 }
2327 }
2328 return $found;
2329 }
2330
2331 /**
2332 * Encrypts sensitive data before storing in session.
2333 *
2334 * @return array<string, mixed> data
2335 */
2336 public function __serialize(): array {
2337 $data = get_object_vars($this);
2338 // encrypt data
2339 $data['attributes'] = lamEncrypt(json_encode($data['attributes'], JSON_INVALID_UTF8_IGNORE));
2340 $data['attributes_orig'] = lamEncrypt(json_encode($data['attributes_orig'], JSON_INVALID_UTF8_IGNORE));
2341 $data['module'] = lamEncrypt(serialize($data['module']));
2342 // save all attributes
2343 return $data;
2344 }
2345
2346 /**
2347 * Decrypts sensitive data after accountContainer was loaded from session.
2348 *
2349 * @param array<string, mixed> $data data
2350 */
2351 public function __unserialize(array $data): void {
2352 // decrypt data
2353 $data['attributes'] = json_decode(lamDecrypt($data['attributes']), true, 512, JSON_INVALID_UTF8_IGNORE);
2354 $data['attributes_orig'] = json_decode(lamDecrypt($data['attributes_orig']), true, 512, JSON_INVALID_UTF8_IGNORE);
2355 $data['module'] = unserialize(lamDecrypt($data['module']));
2356 foreach ($data as $key => $value) {
2357 $this->$key = $value;
2358 }
2359 }
2360
2361 }
2362
2363 /**
2364 * This interface needs to be implemented by all account modules which manage passwords.
2365 * It allows LAM to provide central password changes.
2366 *
2367 * @package modules
2368 */
2369 interface passwordService {
2370
2371 /**
2372 * This method specifies if a module manages password attributes. The module alias will
2373 * then appear as option in the GUI.
2374 * <br>If the module only wants to get notified about password changes then return false.
2375 *
2376 * @return bool true if this module manages password attributes
2377 */
2378 public function managesPasswordAttributes(): bool;
2379
2380 /**
2381 * Specifies if this module supports to force that a user must change his password on next login.
2382 *
2383 * @return bool force password change supported
2384 */
2385 public function supportsForcePasswordChange(): bool;
2386
2387 /**
2388 * This function is called whenever the password should be changed. Account modules
2389 * must change their password attributes only if the modules list contains their module name.
2390 *
2391 * @param string $password new password
2392 * @param string[] $modules list of modules for which the password should be changed
2393 * @param bool $forcePasswordChange force the user to change his password at next login
2394 * @return string[][] list of error messages if any as parameter array for StatusMessage
2395 * e.g. return array(array('ERROR', 'Password change failed.'))
2396 */
2397 public function passwordChangeRequested(string $password, array $modules, bool $forcePasswordChange): array;
2398
2399 /**
2400 * Specifies if the module support password quick change for the current account.
2401 *
2402 * @return bool password quick change page supported
2403 */
2404 public function supportsPasswordQuickChangePage(): bool;
2405
2406 /**
2407 * Adds account details such as first/last name for the current account.
2408 *
2409 * @param htmlResponsiveRow $row row where to add content
2410 */
2411 public function addPasswordQuickChangeAccountDetails(htmlResponsiveRow $row): void;
2412
2413 /**
2414 * Returns a list of password quick change options.
2415 *
2416 * @param bool $forcePasswordChangeByDefault password change should be preselected
2417 * @return PasswordQuickChangeOption[] options
2418 */
2419 public function getPasswordQuickChangeOptions(bool $forcePasswordChangeByDefault): array;
2420
2421 /**
2422 * Returns a list of LDAP attribute changes to perform.
2423 *
2424 * @param string $password new password
2425 * @return array<string, string[]|string> LDAP attribute values (attr_name => array(attr_value))
2426 * @throws LAMException error getting changes
2427 */
2428 public function getPasswordQuickChangeChanges(string $password): array;
2429
2430 /**
2431 * Returns the username if known to be validated for password strength.
2432 *
2433 * @return string|null user name
2434 */
2435 public function getPasswordQuickChangePasswordStrengthUserName(): ?string;
2436
2437 /**
2438 * Returns additional attribute values to check when password strength is validated.
2439 *
2440 * @return string[] attribute values
2441 */
2442 public function getPasswordQuickChangePasswordStrengthAttributes(): array;
2443
2444 /**
2445 * Returns if the password is not same as an old password from history.
2446 *
2447 * @param string $password new password
2448 * @return bool is in history
2449 */
2450 public function getPasswordQuickChangeIsPasswordInHistory(string $password): bool;
2451
2452 }
2453
2454 /**
2455 * Option for the password quick change page.
2456 */
2457 class PasswordQuickChangeOption {
2458
2459 public string $label;
2460
2461 public string $id;
2462
2463 public bool $preSelected;
2464
2465 /**
2466 * PasswordQuickChangeOption constructor.
2467 *
2468 * @param string $id unique id for this option
2469 * @param string $label descriptive label
2470 * @param bool $preSelected is preselected
2471 */
2472 public function __construct(string $id, string $label, bool $preSelected = true) {
2473 $this->label = $label;
2474 $this->id = $id;
2475 $this->preSelected = $preSelected;
2476 }
2477
2478 }
2479
2480 /**
2481 * Provides module information about the status of an LDAP account.
2482 */
2483 interface AccountStatusProvider {
2484
2485 /**
2486 * Returns the list of account status detail lines.
2487 *
2488 * @param ConfiguredType $type account type
2489 * @param array<string, string[]|string>|null $attributes LDAP attributes (use account container attributes if not provided)
2490 * @return AccountStatusDetails[] status details
2491 */
2492 public function getAccountStatusDetails(ConfiguredType $type, ?array &$attributes): array;
2493
2494 /**
2495 * Returns the list of LDAP attributes that must be read to get the account status.
2496 *
2497 * @param ConfiguredType $type type
2498 * @return string[] attribute names
2499 */
2500 public function getAccountStatusRequiredAttributes(ConfiguredType $type): array;
2501
2502 /**
2503 * Returns a list of options how the account could be locked.
2504 *
2505 * @param ConfiguredType $type type
2506 * @param array<string, string[]|string>|null $attributes LDAP attributes
2507 * @return AccountStatusDetails[] lock options
2508 */
2509 public function getAccountStatusPossibleLockOptions(ConfiguredType $type, ?array &$attributes): array;
2510
2511 /**
2512 * Locks the account with the given lock IDs.
2513 *
2514 * @param ConfiguredType $type type
2515 * @param array<string, string[]|string>|null $attributes LDAP attributes
2516 * @param string[] $lockIds IDs from AccountStatusDetails
2517 * @throws LAMException error during locking
2518 */
2519 public function accountStatusPerformLock(ConfiguredType $type, ?array &$attributes, array $lockIds): void;
2520
2521 /**
2522 * Unlocks the account with the given lock IDs.
2523 *
2524 * @param ConfiguredType $type type
2525 * @param array<string, string[]|string>|null $attributes LDAP attributes
2526 * @param string[] $lockIds IDs from AccountStatusDetails
2527 */
2528 public function accountStatusPerformUnlock(ConfiguredType $type, ?array &$attributes, array $lockIds): void;
2529
2530 }
2531
2532 /**
2533 * Provides the complete information about the status of an LDAP account.
2534 */
2535 class AccountStatus {
2536
2537 /** @var AccountStatusDetails[] list of details */
2538 private array $details;
2539
2540 /**
2541 * Constructor.
2542 *
2543 * @param AccountStatusDetails[] $details details
2544 */
2545 public function __construct(array $details) {
2546 $this->details = $details;
2547 }
2548
2549 /**
2550 * Creates the account status from the given type and LDAP attributes.
2551 *
2552 * @param ConfiguredType $type type
2553 * @param array<string, string[]|string> $attributes LDAP attributes
2554 * @return AccountStatus status
2555 */
2556 public static function fromAttributes(ConfiguredType $type, array $attributes): AccountStatus {
2557 $modules = $_SESSION['config']->get_AccountModules($type->getId());
2558 $details = [];
2559 foreach ($modules as $module) {
2560 $moduleObject = moduleCache::getModule($module, $type->getScope());
2561 if (!($moduleObject instanceof AccountStatusProvider)) {
2562 continue;
2563 }
2564 $details = array_merge($details, $moduleObject->getAccountStatusDetails($type, $attributes));
2565 }
2566 return new AccountStatus($details);
2567 }
2568
2569 /**
2570 * Creates the lockable account status from the given type and LDAP attributes.
2571 *
2572 * @param ConfiguredType $type type
2573 * @param array<string, string[]|string> $attributes LDAP attributes
2574 * @return AccountStatus lockable status
2575 */
2576 public static function lockableFromAttributes(ConfiguredType $type, array $attributes): AccountStatus {
2577 $modules = $_SESSION['config']->get_AccountModules($type->getId());
2578 $details = [];
2579 foreach ($modules as $module) {
2580 $moduleObject = moduleCache::getModule($module, $type->getScope());
2581 if (!($moduleObject instanceof AccountStatusProvider)) {
2582 continue;
2583 }
2584 $details = array_merge($details, $moduleObject->getAccountStatusPossibleLockOptions($type, $attributes));
2585 }
2586 return new AccountStatus($details);
2587 }
2588
2589 /**
2590 * Returns the account details.
2591 *
2592 * @return AccountStatusDetails[] details
2593 */
2594 public function getDetails(): array {
2595 return $this->details;
2596 }
2597
2598 /**
2599 * Returns if the account/password is fully expired (e.g. login no longer possible without password change).
2600 *
2601 * @return bool is expired
2602 */
2603 public function isExpired(): bool {
2604 foreach ($this->details as $detail) {
2605 if ($detail->isExpired()) {
2606 return true;
2607 }
2608 }
2609 return false;
2610 }
2611
2612 /**
2613 * Returns if the account/password is partially expired (e.g. a single application is expired).
2614 *
2615 * @return bool is expired
2616 */
2617 public function isPartiallyExpired(): bool {
2618 foreach ($this->details as $detail) {
2619 if ($detail->isPartiallyExpired()) {
2620 return true;
2621 }
2622 }
2623 return false;
2624 }
2625
2626 /**
2627 * Returns if the account is fully locked (login no longer possible).
2628 *
2629 * @return bool is locked
2630 */
2631 public function isLocked(): bool {
2632 foreach ($this->details as $detail) {
2633 if ($detail->isLocked()) {
2634 return true;
2635 }
2636 }
2637 return false;
2638 }
2639
2640 /**
2641 * Returns if the account is partially locked (e.g. a single application is locked).
2642 *
2643 * @return bool is locked
2644 */
2645 public function isPartiallyLocked(): bool {
2646 foreach ($this->details as $detail) {
2647 if ($detail->isPartiallyLocked()) {
2648 return true;
2649 }
2650 }
2651 return false;
2652 }
2653
2654 }
2655
2656 class AccountStatusDetails {
2657
2658 private string $details;
2659 private string $id;
2660 private bool $expired = false;
2661 private bool $partiallyExpired = false;
2662 private bool $locked = false;
2663 private bool $partiallyLocked = false;
2664 private string $icon;
2665
2666 /**
2667 * Constructor.
2668 *
2669 * @param string $details details message
2670 * @param string $id ID for reference
2671 * @param string $icon icon name
2672 */
2673 public function __construct(string $details, string $id, string $icon) {
2674 $this->details = $details;
2675 $this->id = $id;
2676 $this->icon = $icon;
2677 }
2678
2679 /**
2680 * Creates a new expired status entry.
2681 *
2682 * @param string $details details message
2683 * @param string $id ID for reference
2684 * @param string $icon icon name
2685 * @return AccountStatusDetails status entry
2686 */
2687 public static function newExpired(string $details, string $id, ?string $icon = null): AccountStatusDetails {
2688 if ($icon === null) {
2689 $icon = 'expired.svg';
2690 }
2691 $details = new AccountStatusDetails($details, $id, $icon);
2692 $details->expired = true;
2693 return $details;
2694 }
2695
2696 /**
2697 * Creates a new partially expired status entry.
2698 *
2699 * @param string $details details message
2700 * @param string $id ID for reference
2701 * @param string $icon icon name
2702 * @return AccountStatusDetails status entry
2703 */
2704 public static function newPartiallyExpired(string $details, string $id, ?string $icon = null): AccountStatusDetails {
2705 if ($icon === null) {
2706 $icon = 'expired.svg';
2707 }
2708 $details = new AccountStatusDetails($details, $id, $icon);
2709 $details->partiallyExpired = true;
2710 return $details;
2711 }
2712
2713 /**
2714 * Creates a new locked status entry.
2715 *
2716 * @param string $details details message
2717 * @param string $id ID for reference
2718 * @param string $icon icon name
2719 * @return AccountStatusDetails status entry
2720 */
2721 public static function newLocked(string $details, string $id, ?string $icon = null): AccountStatusDetails {
2722 if ($icon === null) {
2723 $icon = 'locked.svg';
2724 }
2725 $details = new AccountStatusDetails($details, $id, $icon);
2726 $details->locked = true;
2727 return $details;
2728 }
2729
2730 /**
2731 * Creates a new partially locked status entry.
2732 *
2733 * @param string $details details message
2734 * @param string $id ID for reference
2735 * @param string $icon icon name
2736 * @return AccountStatusDetails status entry
2737 */
2738 public static function newPartiallyLocked(string $details, string $id, ?string $icon = null): AccountStatusDetails {
2739 if ($icon === null) {
2740 $icon = 'partiallyLocked.svg';
2741 }
2742 $details = new AccountStatusDetails($details, $id, $icon);
2743 $details->partiallyLocked = true;
2744 return $details;
2745 }
2746
2747 /**
2748 * Returns if the account/password is fully expired (e.g. login no longer possible without password change).
2749 *
2750 * @return bool is expired
2751 */
2752 public function isExpired(): bool {
2753 return $this->expired;
2754 }
2755
2756 /**
2757 * Returns if the account/password is partially expired (e.g. a single application is expired).
2758 *
2759 * @return bool is expired
2760 */
2761 public function isPartiallyExpired(): bool {
2762 return $this->partiallyExpired;
2763 }
2764
2765 /**
2766 * Returns if the account is fully locked (login no longer possible).
2767 *
2768 * @return bool is locked
2769 */
2770 public function isLocked(): bool {
2771 return $this->locked;
2772 }
2773
2774 /**
2775 * Returns if the account is partially locked (e.g. a single application is locked).
2776 *
2777 * @return bool is locked
2778 */
2779 public function isPartiallyLocked(): bool {
2780 return $this->partiallyLocked;
2781 }
2782
2783 /**
2784 * Returns the icon name.
2785 *
2786 * @return string icon name
2787 */
2788 public function getIcon(): string {
2789 return $this->icon;
2790 }
2791
2792 /**
2793 * Returns the details.
2794 *
2795 * @return string details
2796 */
2797 public function getDetails(): string {
2798 return $this->details;
2799 }
2800
2801 /**
2802 * Returns the id.
2803 *
2804 * @return string id
2805 */
2806 public function getId(): string {
2807 return $this->id;
2808 }
2809
2810 }
2811
2812 /**
2813 * Validation of scope and module names.
2814 */
2815 class ScopeAndModuleValidation {
2816
2817 /** @var string[]|null $cachedModuleNames names */
2818 private static ?array $cachedModuleNames = null;
2819
2820 /** @var string[]|null $cachedScopeNames names */
2821 private static ?array $cachedScopeNames = null;
2822
2823 private const REGEX_SCOPE = "/^[a-z0-9_-]+$/i";
2824 private const REGEX_MODULE = "/^[a-z0-9_-]+$/i";
2825
2826 /**
2827 * Checks if the provided scope name is valid.
2828 *
2829 * @param string $scope scope name
2830 * @return bool is existing
2831 */
2832 public static function isValidScopeName(string $scope): bool {
2833 if (!preg_match(self::REGEX_SCOPE, $scope)) {
2834 return false;
2835 }
2836 if (self::$cachedScopeNames === null) {
2837 $dirname = __DIR__ . "/types";
2838 $dir = dir($dirname);
2839 $scopeNames = [];
2840 while ($entry = $dir->read()) {
2841 if ((substr($entry, strlen($entry) - 4, 4) === '.inc')
2842 && (is_file($dirname . '/' . $entry) || is_link($dirname . '/' . $entry))) {
2843 $entry = substr($entry, 0, -4);
2844 if (preg_match(self::REGEX_SCOPE, $entry)) {
2845 $scopeNames[] = $entry;
2846 }
2847 }
2848 }
2849 self::$cachedScopeNames = $scopeNames;
2850 }
2851 return in_array($scope, self::$cachedScopeNames);
2852 }
2853
2854 /**
2855 * Checks if the provided module name is valid.
2856 *
2857 * @param string $moduleName module name
2858 * @return bool is existing
2859 */
2860 public static function isValidModuleName(string $moduleName): bool {
2861 if (!preg_match(self::REGEX_MODULE, $moduleName)) {
2862 return false;
2863 }
2864 if (self::$cachedModuleNames === null) {
2865 $dirname = __DIR__ . "/modules";
2866 $dir = dir($dirname);
2867 $moduleNames = [];
2868 while ($entry = $dir->read()) {
2869 if ((substr($entry, strlen($entry) - 4, 4) === '.inc')
2870 && (is_file($dirname . '/' . $entry) || is_link($dirname . '/' . $entry))) {
2871 $entry = substr($entry, 0, -4);
2872 if (preg_match(self::REGEX_MODULE, $entry)) {
2873 $moduleNames[] = $entry;
2874 }
2875 }
2876 }
2877 self::$cachedModuleNames = $moduleNames;
2878 }
2879 return in_array($moduleName, self::$cachedModuleNames);
2880 }
2881
2882 }