Debian Codegraph @

lib/config.inc

raw
1 <?php
2
3 use LAM\LIB\TWO_FACTOR\TwoFactorProviderService;
4 use LAM\PDF\PdfStructurePersistenceManager;
5 use LAM\PERSISTENCE\ConfigurationDatabase;
6 use LAM\PROFILES\AccountProfilePersistenceManager;
7 use LAM\REMOTE\RemoteServerConfiguration;
8 use LAM\TYPES\TypeManager;
9 use function LAM\PERSISTENCE\dbTableExists;
10 use function LAM\TYPES\getScopeFromTypeId;
11
12 /*
13
14 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
15 Copyright (C) 2003 - 2026 Roland Gruber
16
17 This program is free software; you can redistribute it and/or modify
18 it under the terms of the GNU General Public License as published by
19 the Free Software Foundation; either version 2 of the License, or
20 (at your option) any later version.
21
22 This program is distributed in the hope that it will be useful,
23 but WITHOUT ANY WARRANTY; without even the implied warranty of
24 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 GNU General Public License for more details.
26
27 You should have received a copy of the GNU General Public License
28 along with this program; if not, write to the Free Software
29 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30
31
32 */
33
34 /**
35 * This file includes functions to manage the configuration files.
36 *
37 * @package configuration
38 * @author Roland Gruber
39 * @author Thomas Manninger
40 */
41
42 /**
43 * Defines the possible LAM user interfaces.
44 */
45 enum LAM_INTERFACE {
46 /** admin pages to manage any type aof entry */
47 case ADMIN;
48 /** user self-service to manage own data */
49 case SELF_SERVICE;
50 /** white-pages to display users */
51 case WHITE_PAGES;
52 }
53
54 /** persistence */
55 include_once __DIR__ . '/persistence.inc';
56 /** Used to print messages. */
57 include_once __DIR__ . "/status.inc";
58 /** Used to get module information. */
59 include_once __DIR__ . "/modules.inc";
60 /** Used to get type information. */
61 include_once __DIR__ . "/types.inc";
62 /** 2-factor */
63 include_once __DIR__ . '/2factor.inc';
64
65 /**
66 * Checks if the configuration password is secure.
67 *
68 * @param string $password password
69 * @return bool is secure
70 */
71 function isValidConfigurationPassword(string $password): bool {
72 return preg_match('/[a-zA-Z]/', $password)
73 && preg_match('/\d/', $password)
74 && preg_match('/[^a-zA-Z0-9]/', $password)
75 && (strlen($password) >= 8);
76 }
77
78 /**
79 * Sets the environment variables for custom SSL CA certificates.
80 */
81 function setSSLCaCert(): void {
82 $config = $_SESSION['cfgMain'] ?? new LAMCfgMain();
83 // set SSL certificate if set
84 $sslCaPath = $config->getSSLCaCertPath();
85 if ($sslCaPath != null) {
86 putenv('LDAPTLS_CACERT=' . $sslCaPath);
87 putenv('TLS_CACERT=' . $sslCaPath);
88 }
89 }
90
91 /**
92 * Sets language settings for automatic translation
93 */
94 function setlanguage(): void {
95 $code = 'en_GB.utf8';
96 $fallbackCode = 'en_GB.UTF-8';
97 $encoding = 'UTF-8';
98 if (!isset($_SESSION['language'])) {
99 $_SESSION['language'] = "en_GB.utf8";
100 }
101 $possibleLanguages = getLanguages();
102 foreach ($possibleLanguages as $lang) {
103 if ($lang->code == $_SESSION['language']) {
104 $code = $lang->code;
105 $fallbackCode = str_replace('utf8', 'UTF-8', $code);
106 $encoding = $lang->encoding;
107 break;
108 }
109 }
110 putenv("LANG=$code"); // e.g. LANG=de_DE
111 putenv("LC_ALL=$code");
112 putenv("LC_LANG=$code");
113 putenv("LC_LANGUAGE=$code");
114 $setLocaleResult = setlocale(LC_ALL, [$code, $fallbackCode]); // set LC_ALL
115 if ($setLocaleResult === false) {
116 logNewMessage(LOG_WARNING, "Unable to set locale, check if 'locale -a' returns $code");
117 }
118 $locdir = substr(__FILE__, 0, strlen(__FILE__) - 15) . "/locale"; // set path to translations
119 bindtextdomain("messages", $locdir);
120 $bindTextResult = bind_textdomain_codeset("messages", $encoding);
121 if (!is_string($bindTextResult)) {
122 logNewMessage(LOG_WARNING, "Unable to bind text domain, check if 'locale -a' returns $code");
123 }
124 textdomain("messages");
125 header("Content-type: text/html; charset=" . $encoding);
126 }
127
128 /**
129 * Checks whether a specific flag in the rights string is set.
130 *
131 * @param string $right read, write or execute
132 * @param string $target owner, group or other
133 * @param string $chmod the chmod rights
134 *
135 * @return bool true, if the chmod $right for $target were set
136 */
137 function checkChmod(string $right, string $target, string $chmod): bool {
138 $right_arr = ["read", "write", "execute"];
139 $target_arr = ["owner", "group", "other"];
140
141 // Check, if $right and $target has right parameters
142 if (!in_array($right, $right_arr) || !in_array($target, $target_arr)) {
143 return false;
144 }
145
146 $chmod_num = -1;
147 // owner:
148 if ($target === "owner") {
149 $chmod_num = 0;
150 }
151 if ($target === "group") {
152 $chmod_num = 1;
153 }
154 if ($target === "other") {
155 $chmod_num = 2;
156 }
157
158 // Cut the number from the chmod:
159 $chmod_num = $chmod[$chmod_num];
160
161 // Now check, if the chmod_num can be right with the $right
162 // What numbers allow "read"
163 $read = [4, 5, 6, 7];
164 // What numbers allow "write"
165 $write = [2, 3, 6, 7];
166 // What numbers allow "execute"
167 $execute = [1, 3, 5, 7];
168 return (($right === "read") && in_array($chmod_num, $read))
169 || (($right === "write") && in_array($chmod_num, $write))
170 || (($right === "execute") && in_array($chmod_num, $execute));
171 }
172
173 /**
174 * Returns the version number of this LAM installation.
175 * Format: <major version>.<minor version>.<patch level>
176 * <br> Major/minor version are always numbers, patch level may contain letters for unofficial releases only (e.g. 0.5.alpha1).
177 *
178 * @return string version number
179 */
180 function LAMVersion(): string {
181 $file = substr(__FILE__, 0, strlen(__FILE__) - 15) . "/VERSION";
182 if (is_readable($file)) {
183 $handle = fopen($file, "r");
184 if (!feof($handle)) {
185 return trim(fgets($handle, 20));
186 }
187 }
188 // file was not readable
189 return '0.0.unknown';
190 }
191
192 /**
193 * Extracts config options from HTTP POST data.
194 *
195 * @param array<string, string> $confTypes array (option name => type (e.g. multiselect))
196 * @return array<string, string[]> list of config options (name =>[values])
197 */
198 function extractConfigOptionsFromPOST(array $confTypes): array {
199 $options = [];
200 foreach ($confTypes as $element => $type) {
201 // text fields
202 if ($type == "text") {
203 $options[$element] = [$_POST[$element]];
204 }
205 // text fields
206 elseif ($type == "text_obfuscated") {
207 $options[$element] = [obfuscateText($_POST[$element])];
208 }
209 // hidden fields
210 elseif ($type == "hidden") {
211 $options[$element] = [$_POST[$element]];
212 }
213 // checkboxes
214 elseif ($type == "checkbox") {
215 $options[$element] = isset($_POST[$element]) && ($_POST[$element] == "on") ? ['true'] : ['false'];
216 }
217 // dropdownbox
218 elseif ($type == "select") {
219 $options[$element] = [$_POST[$element]];
220 }
221 // multiselect
222 elseif ($type == "multiselect") {
223 $options[$element] = $_POST[$element]; // value is already an array
224 }
225 // textarea
226 elseif ($type == "textarea") {
227 $options[$element] = explode("\r\n", $_POST[$element]);
228 }
229 }
230 return $options;
231 }
232
233
234 /**
235 * Prints a meta refresh page
236 *
237 * @param string $page the URL of the target page
238 */
239 function metaRefresh(string $page): void {
240 if (!headers_sent()) {
241 header('Location: ' . $page);
242 return;
243 }
244 if (isset($_SESSION['header'])) {
245 echo $_SESSION['header'];
246 }
247 else {
248 echo '<!DOCTYPE html>';
249 echo "<html><head>\n";
250 }
251 echo "<meta http-equiv=\"refresh\" content=\"0; URL=" . $page . "\">\n";
252 echo "<title></title>\n";
253 echo "</head>\n";
254 echo "<body>\n";
255 // print link if refresh does not work
256 echo "<p>\n";
257 echo "<a href=\"" . $page . "\">" . _("Click here if you are not directed to the next page.") . "</a>\n";
258 echo "</p>\n";
259 echo "</body>\n";
260 echo "</html>\n";
261 }
262
263 /**
264 * Checks if the given account type is hidden.
265 *
266 * @param string $typeId account type (e.g. user)
267 * @return bool is hidden
268 */
269 function isAccountTypeHidden(string $typeId): bool {
270 $typeSettings = $_SESSION['config']->get_typeSettings();
271 return isset($typeSettings['hidden_' . $typeId]) && ($typeSettings['hidden_' . $typeId]);
272 }
273
274 /**
275 * Returns a list of all supported languages.
276 *
277 * @return LAMLanguage[] languages
278 */
279 function getLanguages(): array {
280 $languages = [];
281 // loading available languages from language.conf file
282 $languagefile = __DIR__ . "/../config/language";
283 if (is_file($languagefile)) {
284 $file = fopen($languagefile, "r");
285 while (!feof($file)) {
286 $line = fgets($file, 1024);
287 if ($line == "" || $line === "\n" || $line[0] === "#") {
288 continue; // ignore comment and empty lines
289 }
290 $value = explode(":", $line);
291 $languages[] = new LAMLanguage($value[0], $value[1], $value[2]);
292 }
293 fclose($file);
294 }
295 return $languages;
296 }
297
298 /**
299 * Represents a supported language.
300 *
301 * @package configuration
302 */
303 class LAMLanguage {
304 /** language code (e.g. en_GB.utf8) */
305 public string $code;
306 /** character encoding (e.g. UTF-8) */
307 public string $encoding;
308 /** description for GUI */
309 public string $description;
310
311 /**
312 * Constructor
313 *
314 * @param string $code language code (e.g. en_GB.utf8)
315 * @param string $encoding character encoding (e.g. UTF-8)
316 * @param string $description description for GUI
317 */
318 public function __construct(string $code, string $encoding, string $description) {
319 $this->code = $code;
320 $this->encoding = $encoding;
321 $this->description = $description;
322 }
323
324 }
325
326 /**
327 * Manages the persistence of server profiles.
328 */
329 class ServerProfilePersistenceManager {
330
331 private ServerProfilePersistenceStrategy $strategy;
332
333 public function __construct() {
334 $configDb = new ConfigurationDatabase(new LAMCfgMain());
335 if ($configDb->useRemoteDb()) {
336 $this->strategy = new ServerProfilePersistenceStrategyPdo($configDb->getPdo());
337 }
338 else {
339 $this->strategy = new ServerProfilePersistenceStrategyFiles();
340 }
341 }
342
343 /**
344 * Returns a lis of available server profiles.
345 *
346 * @return string[] list of server profile names
347 * @throws LAMException error listing profiles
348 */
349 public function getProfiles(): array {
350 return $this->strategy->getProfiles();
351 }
352
353 /**
354 * Loads the given server profile
355 *
356 * @param string $name profile name
357 * @return LAMConfig profile
358 * @throws LAMException error loading profile
359 */
360 public function loadProfile(string $name): LAMConfig {
361 $config = $this->strategy->loadProfile($name);
362 $config->setName($name);
363 return $config;
364 }
365
366 /**
367 * Saves a server profile.
368 *
369 * @param LAMConfig $profile profile
370 * @param string $name profile name
371 * @throws LAMException error saving profile
372 */
373 public function saveProfile(LAMConfig $profile, string $name): void {
374 $this->strategy->saveProfile($profile, $name);
375 }
376
377 /**
378 * Returns an array of string with all available configuration templates (without .sample.conf)
379 *
380 * @return array<int, string> template names
381 */
382 public function getConfigTemplates(): array {
383 $dir = dir(__DIR__ . "/../config");
384 $ret = [];
385 $pos = 0;
386 while ($entry = $dir->read()) {
387 $ext = substr($entry, strlen($entry) - 12, 12);
388 $name = substr($entry, 0, strlen($entry) - 12);
389 // check if extension is right, add to profile list
390 if ($ext === ".sample.conf") {
391 $ret[$pos] = $name;
392 $pos++;
393 }
394 }
395 sort($ret);
396 return $ret;
397 }
398
399 /**
400 * Creates a new server profile using a template/existing profile.
401 *
402 * @param string $name profile name
403 * @param string $templateName template name
404 * @param string $password new profile password
405 * @throws LAMException error saving profile
406 */
407 public function createProfileFromTemplate(string $name, string $templateName, string $password): void {
408 if (!LAMConfig::isValidName($name) || !preg_match("/^[a-z0-9\\._-]+$/i", $templateName) || in_array($name, $this->getProfiles())) {
409 throw new LAMException(_("Profile name is invalid!"));
410 }
411 $copyFromTemplate = true;
412 $existingTemplateNames = $this->getConfigTemplates();
413 if (str_contains($templateName, '.sample')) {
414 $templateNameShort = str_replace('.sample', '', $templateName);
415 if (!in_array($templateNameShort, $existingTemplateNames)) {
416 throw new LAMException(_("Profile name is invalid!"));
417 }
418 // built-in templates are loaded via file system
419 $filesStrategy = new ServerProfilePersistenceStrategyFiles();
420 $config = $filesStrategy->loadProfile($templateName);
421 }
422 else {
423 $copyFromTemplate = false;
424 $config = $this->loadProfile($templateName);
425 }
426 $config->set_Passwd($password);
427 $this->saveProfile($config, $name);
428 $accountProfilePersistenceManager = new AccountProfilePersistenceManager();
429 $pdfStructurePersistenceManager = new PdfStructurePersistenceManager();
430 if (!$copyFromTemplate) {
431 $typeManager = new TypeManager($config);
432 foreach ($typeManager->getConfiguredTypes() as $type) {
433 $profilesToCopy = $accountProfilePersistenceManager->getAccountProfileNames($type->getId(), $templateName);
434 foreach ($profilesToCopy as $profileToCopy) {
435 $profile = $accountProfilePersistenceManager->loadAccountProfile($type->getId(), $profileToCopy, $templateName);
436 $accountProfilePersistenceManager->writeAccountProfile($type->getId(), $profileToCopy, $name, $profile);
437 }
438 $structuresToCopy = $pdfStructurePersistenceManager->getPDFStructures($templateName, $type->getId());
439 foreach ($structuresToCopy as $structureToCopy) {
440 $structure = $pdfStructurePersistenceManager->readPdfStructure($templateName, $type->getId(), $structureToCopy);
441 $pdfStructurePersistenceManager->savePdfStructure($name, $type->getId(), $structureToCopy, $structure);
442 }
443 $logosToCopy = $pdfStructurePersistenceManager->getPdfLogos($templateName);
444 foreach ($logosToCopy as $logoToCopy) {
445 $binary = $pdfStructurePersistenceManager->getPdfLogoBinary($templateName, $logoToCopy->getName());
446 $pdfStructurePersistenceManager->savePdfLogo($name, $logoToCopy->getName(), $binary);
447 }
448 }
449 }
450 $accountProfilePersistenceManager->installAccountProfileTemplates($name);
451 $pdfStructurePersistenceManager->installPDFTemplates($name);
452 }
453
454 /**
455 * Renames an existing server profile.
456 *
457 * @param string $oldName old profile name
458 * @param string $newName new profile name
459 * @throws LAMException error during rename
460 */
461 public function renameProfile(string $oldName, string $newName): void {
462 $this->strategy->renameProfile($oldName, $newName);
463 // update default profile setting if needed
464 $mainConfig = new LAMCfgMain();
465 if ($mainConfig->default == $oldName) {
466 $mainConfig->default = $newName;
467 $mainConfig->save();
468 }
469 }
470
471 /**
472 * Deletes a server profile.
473 *
474 * @param string $name profile name
475 * @throws LAMException error deleting profile
476 */
477 public function deleteProfile(string $name): void {
478 $this->strategy->deleteProfile($name);
479 }
480
481 /**
482 * Returns if the configuration is writable.
483 *
484 * @param string $name profile name
485 * @return bool is writable
486 */
487 public function isWritable(string $name): bool {
488 return $this->strategy->isWritable($name);
489 }
490
491 }
492
493 /**
494 * Interface to store server profiles.
495 */
496 interface ServerProfilePersistenceStrategy {
497
498 /**
499 * Returns a lis of available server profiles.
500 *
501 * @return string[] list of server profile names
502 * @throws LAMException error listing profiles
503 */
504 public function getProfiles(): array;
505
506 /**
507 * Loads the given server profile
508 *
509 * @param string $name profile name
510 * @return LAMConfig profile
511 * @throws LAMException error loading profile
512 */
513 public function loadProfile(string $name): LAMConfig;
514
515 /**
516 * Saves a server profile.
517 *
518 * @param LAMConfig $profile profile
519 * @param string $name profile name
520 * @throws LAMException error saving profile
521 */
522 public function saveProfile(LAMConfig $profile, string $name): void;
523
524 /**
525 * Renames an existing server profile.
526 *
527 * @param string $oldName old profile name
528 * @param string $newName new profile name
529 * @throws LAMException error saving profile
530 */
531 public function renameProfile(string $oldName, string $newName): void;
532
533 /**
534 * Deletes a server profile.
535 *
536 * @param string $name profile name
537 * @throws LAMException error deleting profile
538 */
539 public function deleteProfile(string $name): void;
540
541 /**
542 * Returns if the configuration is writable.
543 *
544 * @param string $name profile name
545 * @return bool is writable
546 */
547 public function isWritable(string $name): bool;
548
549 }
550
551 /**
552 * Uses local file system to store server profiles.
553 */
554 class ServerProfilePersistenceStrategyFiles implements ServerProfilePersistenceStrategy {
555
556 /**
557 * @inheritDoc
558 */
559 public function getProfiles(): array {
560 $dirName = __DIR__ . "/../config";
561 $dir = dir($dirName);
562 $ret = [];
563 while ($entry = $dir->read()) {
564 $ext = substr($entry, strlen($entry) - 5, 5);
565 $name = substr($entry, 0, strlen($entry) - 5);
566 // check if extension is right, add to profile list
567 if (($ext === ".conf") && (!str_contains($name, '.sample')) && is_readable($dirName . '/' . $entry)) {
568 $ret[] = $name;
569 }
570 }
571 sort($ret);
572 return $ret;
573 }
574
575 /**
576 * @inheritDoc
577 */
578 public function loadProfile(string $name): LAMConfig {
579 $config = new LAMConfig();
580 $confFilePath = $this->getPath($name);
581 if (!is_file($confFilePath)) {
582 logNewMessage(LOG_ERR, 'No such file ' . $confFilePath);
583 throw new LAMException(_('Unable to read file.'));
584 }
585 $file = @fopen($confFilePath, "r");
586 if (!$file) {
587 logNewMessage(LOG_ERR, 'Unable to open for reading: ' . $confFilePath);
588 throw new LAMException(_('Unable to read file.'));
589 }
590 $json = fread($file, 1000000);
591 $data = json_decode($json, true);
592 if ($data === null) {
593 logNewMessage(LOG_ERR, 'Unable to read JSON from ' . $confFilePath);
594 throw new LAMException(_('Unable to read file.'));
595 }
596 fclose($file);
597 $config->importData($data);
598 $config->removeInvalidTypes();
599 $config->removeInvalidModules();
600 return $config;
601 }
602
603 /**
604 * @inheritDoc
605 */
606 public function saveProfile(LAMConfig $profile, string $name): void {
607 $confFile = $this->getPath($name);
608 if (!file_exists($confFile)) {
609 $newFile = fopen($confFile, 'wb');
610 fclose($newFile);
611 }
612 if (is_file($confFile) && is_readable($confFile)) {
613 $file = @fopen($confFile, "w");
614 if ($file) {
615 fwrite($file, json_encode($profile->exportData(), JSON_PRETTY_PRINT));
616 fclose($file);
617 @chmod($confFile, 0600);
618 }
619 else {
620 throw new LAMException(_('Unable to save server profile.'), $name);
621 }
622 }
623 }
624
625 /**
626 * @inheritDoc
627 */
628 public function renameProfile(string $oldName, string $newName): void {
629 $existingProfileNames = $this->getProfiles();
630 if (!LAMConfig::isValidName($oldName)
631 || !LAMConfig::isValidName($newName)
632 || in_array($newName, $existingProfileNames)) {
633 throw new LAMException(_("Profile name is invalid!"));
634 }
635 if (rename("../../config/" . $oldName . ".conf", "../../config/" . $newName . ".conf")) {
636 // rename pdf and profiles folder
637 rename("../../config/profiles/" . $oldName, "../../config/profiles/" . $newName);
638 rename("../../config/pdf/" . $oldName, "../../config/pdf/" . $newName);
639 // rename sqlite database if any
640 if (file_exists("../../config/" . $oldName . ".sqlite")) {
641 rename("../../config/" . $oldName . ".sqlite", "../../config/" . $newName . ".sqlite");
642 }
643 }
644 else {
645 throw new LAMException(_("Could not rename file!"));
646 }
647 }
648
649 /**
650 * @inheritDoc
651 */
652 public function deleteProfile(string $name): void {
653 if (!LAMConfig::isValidName($name)) {
654 throw new LAMException(_("Unable to delete profile!"));
655 }
656 $dir = __DIR__ . "/../config/";
657 // delete account profiles and PDF structures
658 $subDirs = [
659 $dir . 'pdf/' . $name . '/logos',
660 $dir . 'pdf/' . $name,
661 $dir . 'profiles/' . $name
662 ];
663 for ($i = 0; $i < count($subDirs); $i++) {
664 if (is_dir($subDirs[$i]) && is_readable($subDirs[$i])) {
665 $dirHandle = @opendir($subDirs[$i]);
666 while (false !== ($path = readdir($dirHandle))) {
667 if (($path !== '.') && ($path !== '..') && !@unlink($subDirs[$i] . '/' . $path)) {
668 logNewMessage(LOG_ERR, 'Unable to delete ' . $subDirs[$i] . '/' . $path);
669 throw new LAMException(_("Unable to delete profile!"));
670 }
671 }
672 @closedir($dirHandle);
673 if (!@rmdir($subDirs[$i])) {
674 logNewMessage(LOG_ERR, 'Unable to delete ' . $subDirs[$i]);
675 throw new LAMException(_("Unable to delete profile!"));
676 }
677 }
678 }
679 // delete config file
680 $confFile = $dir . $name . ".conf";
681 if (!@unlink($confFile)) {
682 logNewMessage(LOG_ERR, 'Unable to delete ' . $confFile);
683 throw new LAMException(_("Unable to delete profile!"));
684 }
685 }
686
687 /**
688 * @inheritDoc
689 */
690 public function isWritable(string $name): bool {
691 return is_writable($this->getPath($name));
692 }
693
694 /**
695 * Returns the path to the config file.
696 *
697 * @param string $name profile name
698 * @return string path on filesystem
699 */
700 private function getPath(string $name): string {
701 return __DIR__ . "/../config/" . $name . ".conf";
702 }
703
704 }
705
706 /**
707 * Stores server profiles in a database.
708 */
709 class ServerProfilePersistenceStrategyPdo implements ServerProfilePersistenceStrategy {
710
711 public const TABLE_NAME = 'server_profiles';
712
713 /**
714 * @var PDO $pdo PDO
715 */
716 private PDO $pdo;
717
718 /**
719 * Constructor
720 *
721 * @param PDO $pdo PDO
722 */
723 public function __construct(PDO $pdo) {
724 $this->pdo = $pdo;
725 $this->checkSchema();
726 }
727
728 /**
729 * Checks if the schema has latest version.
730 */
731 private function checkSchema(): void {
732 if (!dbTableExists($this->pdo, self::TABLE_NAME)) {
733 $this->createInitialSchema();
734 }
735 }
736
737 /**
738 * Creates the initial schema.
739 */
740 public function createInitialSchema(): void {
741 logNewMessage(LOG_DEBUG, 'Creating database table ' . self::TABLE_NAME);
742 $sql = 'create table ' . self::TABLE_NAME . '('
743 . 'name VARCHAR(300) NOT NULL,'
744 . 'data TEXT NOT NULL,'
745 . 'PRIMARY KEY(name)'
746 . ');';
747 $this->pdo->exec($sql);
748 $sql = 'insert into ' . ConfigurationDatabase::TABLE_SCHEMA_VERSIONS . ' (name, version) VALUES ("server_profiles", 1);';
749 $this->pdo->exec($sql);
750 }
751
752 /**
753 * @inheritDoc
754 */
755 public function getProfiles(): array {
756 $statement = $this->pdo->prepare("SELECT name FROM " . self::TABLE_NAME);
757 $statement->execute();
758 $results = $statement->fetchAll();
759 $profiles = [];
760 foreach ($results as $result) {
761 $profiles[] = $result['name'];
762 }
763 return $profiles;
764 }
765
766 /**
767 * @inheritDoc
768 */
769 public function loadProfile(string $name): LAMConfig {
770 $statement = $this->pdo->prepare("SELECT data FROM " . self::TABLE_NAME . " WHERE name = ?");
771 $statement->execute([$name]);
772 $results = $statement->fetchAll();
773 if (empty($results)) {
774 logNewMessage(LOG_ERR, 'Server profile not found: ' . $name);
775 throw new LAMException(_("Unable to load profile!"), $name);
776 }
777 $data = json_decode($results[0]['data'], true);
778 $config = new LAMConfig();
779 $config->importData($data);
780 return $config;
781 }
782
783 /**
784 * @inheritDoc
785 */
786 public function saveProfile(LAMConfig $profile, string $name): void {
787 $data = json_encode($profile->exportData());
788 $statement = $this->pdo->prepare("SELECT data FROM " . self::TABLE_NAME . " WHERE name = ?");
789 $statement->execute([$name]);
790 $results = $statement->fetchAll();
791 if (empty($results)) {
792 $statement = $this->pdo->prepare("INSERT INTO " . self::TABLE_NAME . " (name, data) VALUES (?, ?)");
793 $statement->execute([$name, $data]);
794 }
795 else {
796 $statement = $this->pdo->prepare("UPDATE " . self::TABLE_NAME . " SET data = ? WHERE name = ?");
797 $statement->execute([$data, $name]);
798 }
799 }
800
801 /**
802 * @inheritDoc
803 */
804 public function renameProfile(string $oldName, string $newName): void {
805 $statement = $this->pdo->prepare("UPDATE " . self::TABLE_NAME . " SET name = ? WHERE name = ?");
806 $statement->execute([$newName, $oldName]);
807 }
808
809 /**
810 * @inheritDoc
811 */
812 public function deleteProfile(string $name): void {
813 $statement = $this->pdo->prepare("DELETE FROM " . self::TABLE_NAME . " WHERE name = ?");
814 $statement->execute([$name]);
815 }
816
817 /**
818 * @inheritDoc
819 */
820 public function isWritable(string $name): bool {
821 return true;
822 }
823 }
824
825 /**
826 * This class manages conf files.
827 *
828 * @package configuration
829 */
830 class LAMConfig {
831
832 /* access levels */
833 public const ACCESS_ALL = '100';
834 public const ACCESS_PASSWORD_CHANGE = '20';
835 public const ACCESS_READ_ONLY = '0';
836
837 /* login method: predefined list or LDAP search */
838 public const LOGIN_LIST = 'list';
839 public const LOGIN_SEARCH = 'search';
840
841 /** line separator */
842 public const LINE_SEPARATOR = '+::+';
843
844 /** show password on screen by default */
845 public const PWDRESET_DEFAULT_SCREEN = '1';
846 /** send password via email by default */
847 public const PWDRESET_DEFAULT_MAIL = '2';
848 /** send password via SMS by default */
849 public const PWDRESET_DEFAULT_SMS = '4';
850 /** show password on screen and send via email by default */
851 public const PWDRESET_DEFAULT_ALL = '3';
852
853 /** Server address (e.g. ldap://127.0.0.1:389) */
854 private string $ServerURL = '';
855
856 /** Display name of LDAP server */
857 private string $serverDisplayName = '';
858
859 /** enables/disables TLS encryption */
860 private string $useTLS = 'no';
861
862 /** automatically follow referrals */
863 private string $followReferrals = 'false';
864
865 /** use paged results */
866 private string $pagedResults = 'false';
867
868 /** Active Directory: show deleted entries */
869 private string $adShowDeleted = 'false';
870
871 /** overlay for referential integrity is activated */
872 private string $referentialIntegrityOverlay = 'false';
873
874 /** hide password prompt for expired passwords */
875 private string $hidePasswordPromptForExpiredPasswords = 'false';
876
877 /** list of users with admin rights, separated by semicolon */
878 private string $Admins = '';
879
880 /** Password to edit preferences */
881 private ?string $Passwd = null;
882
883 /** Default language */
884 private string $defaultLanguage = '';
885 /** time zone */
886 private string $timeZone = 'Europe/London';
887
888 /** @var array<string, string[]> $moduleSettings module settings */
889 private array $moduleSettings = [];
890
891 /** @var array<string, string> $typeSettings type settings */
892 private array $typeSettings = [];
893
894 /** @var array<string, string> $toolSettings tool settings */
895 private array $toolSettings = [];
896
897 /**
898 * Path to external lamdaemon script on server where it is executed
899 *
900 * This is used for managing quota and home directories.
901 * optional setting, may not be defined
902 */
903 private string $scriptPath = '';
904
905 /**
906 * The rights for the home directory
907 */
908 private string $scriptRights = '750';
909
910 /**
911 * Servers where lamdaemon script is executed
912 *
913 * This is used for managing quota and home directories.
914 * optional setting, may not be defined
915 */
916 private string $scriptServer = '';
917
918 /**
919 * user name for lamdaemon
920 */
921 private string $scriptUserName = '';
922
923 /**
924 * File name of SSH key for lamdaemon.
925 */
926 private string $scriptSSHKey = '';
927
928 /**
929 * Password for lamdaemon SSH key.
930 */
931 private string $scriptSSHKeyPassword = '';
932
933 /** LDAP search limit */
934 private int $searchLimit = 0;
935
936 /** Active account types */
937 private string $activeTypes = "";
938
939 /** Name of configuration file */
940 private string $name;
941
942 /** access level */
943 private string $accessLevel = LAMConfig::ACCESS_ALL;
944
945 /** login method */
946 private string $loginMethod = LAMConfig::LOGIN_LIST;
947
948 /** search suffix for login */
949 private string $loginSearchSuffix = 'dc=yourdomain,dc=org';
950
951 /** search filter for login */
952 private string $loginSearchFilter = 'uid=%USER%';
953
954 /** bind user for login search */
955 private string $loginSearchDN = '';
956
957 /** bind password for login search */
958 private string $loginSearchPassword = '';
959
960 /** specifies if HTTP authentication should be used */
961 private string $httpAuthentication = 'false';
962
963 /** email address for sender of password reset mails */
964 private string $lamProMailFrom = '';
965 /** reply-to email address for password reset mails */
966 private string $lamProMailReplyTo = '';
967 /** subject for password reset mails */
968 private string $lamProMailSubject = '';
969 /** treat password reset mail body as HTML */
970 private string $lamProMailIsHTML = 'false';
971 /** allow sending mails to an alternative address */
972 private string $lamProMailAllowAlternateAddress = 'true';
973 /** mail body for password reset mails */
974 private string $lamProMailText = '';
975
976 /** password reset page: allow to set a specific password */
977 private string $pwdResetAllowSpecificPassword = 'true';
978 /** password reset page: allow to show password on screen */
979 private string $pwdResetAllowScreenPassword = 'true';
980 /** password reset page: force password change by default */
981 private string $pwdResetForcePasswordChange = 'true';
982 /** password reset page: default selection for password output
983 * PWDRESET_DEFAULT_SCREEN, PWDRESET_DEFAULT_MAIL, PWDRESET_DEFAULT_BOTH */
984 private string $pwdResetDefaultPasswordOutput = LAMConfig::PWDRESET_DEFAULT_MAIL;
985
986 /** LDAP user for jobs */
987 private ?string $jobsBindUser = '';
988 /** LDAP password for jobs */
989 private ?string $jobsBindPassword = '';
990 /** database type for jobs */
991 private ?string $jobsDatabase = '';
992 /** host of job database */
993 private ?string $jobsDBHost = '';
994 /** port of job database */
995 private ?string $jobsDBPort = '';
996 /** CA path of job database */
997 private ?string $jobsDBCaPath = '';
998 /** user of job database */
999 private ?string $jobsDBUser = '';
1000 /** password of job database */
1001 private ?string $jobsDBPassword = '';
1002 /** name of job database */
1003 private ?string $jobsDBName = '';
1004 /** @var array<string, string[]> $jobSettings job configuration */
1005 private array $jobSettings = [];
1006
1007 private string $twoFactorAuthentication = TwoFactorProviderService::TWO_FACTOR_NONE;
1008 private string $twoFactorAuthenticationURL = 'https://localhost';
1009 private string $twoFactorAuthenticationClientId = '';
1010 private string $twoFactorAuthenticationSecretKey = '';
1011 private string $twoFactorAuthenticationDomain = '';
1012 private bool $twoFactorAuthenticationInsecure = false;
1013 private string $twoFactorAuthenticationLabel = '';
1014 private bool $twoFactorAuthenticationOptional = false;
1015 private string $twoFactorAuthenticationCaption = '';
1016 private string $twoFactorAuthenticationAttribute = '';
1017 private string $twoFactorAllowToRememberDevice = 'false';
1018 private string $twoFactorRememberDeviceDuration = '28800';
1019 private string $twoFactorRememberDevicePassword = '';
1020
1021 private string $hideDnPart = '';
1022
1023 private string $pwdPolicyMinLength = '';
1024 private string $pwdPolicyMinLowercase = '';
1025 private string $pwdPolicyMinUppercase = '';
1026 private string $pwdPolicyMinNumeric = '';
1027 private string $pwdPolicyMinSymbolic = '';
1028
1029 /** @var string[] $settings List of all settings in config file */
1030 private array $settings = ["ServerURL", "useTLS", "followReferrals", 'pagedResults', 'adShowDeleted', "Passwd", "Admins",
1031 "defaultLanguage", "scriptPath", "scriptServer", "scriptRights", 'serverDisplayName',
1032 "modules", "activeTypes", "types", "tools", "accessLevel", 'loginMethod', 'loginSearchSuffix',
1033 'loginSearchFilter', 'searchLimit', 'lamProMailFrom', 'lamProMailReplyTo', 'lamProMailSubject',
1034 'lamProMailText', 'lamProMailIsHTML', 'lamProMailAllowAlternateAddress', 'httpAuthentication', 'loginSearchDN',
1035 'loginSearchPassword', 'timeZone', 'jobsBindUser', 'jobsBindPassword', 'jobsDatabase', 'jobs',
1036 'jobsDBHost', 'jobsDBPort', 'jobsDBCaPath', 'jobsDBUser', 'jobsDBPassword', 'jobsDBName', 'pwdResetAllowSpecificPassword',
1037 'pwdResetAllowScreenPassword', 'pwdResetForcePasswordChange', 'pwdResetDefaultPasswordOutput',
1038 'scriptUserName', 'scriptSSHKey', 'scriptSSHKeyPassword', 'twoFactorAuthentication', 'twoFactorAuthenticationURL',
1039 'twoFactorAuthenticationInsecure', 'twoFactorAuthenticationLabel', 'twoFactorAuthenticationOptional',
1040 'twoFactorAuthenticationCaption', 'twoFactorAuthenticationClientId', 'twoFactorAuthenticationSecretKey',
1041 'twoFactorAuthenticationDomain', 'twoFactorAuthenticationAttribute', 'twoFactorAllowToRememberDevice',
1042 'twoFactorRememberDeviceDuration', 'twoFactorRememberDevicePassword', 'referentialIntegrityOverlay',
1043 'hidePasswordPromptForExpiredPasswords', 'hideDnPart', 'pwdPolicyMinLength', 'pwdPolicyMinLowercase',
1044 'pwdPolicyMinUppercase', 'pwdPolicyMinNumeric', 'pwdPolicyMinSymbolic'
1045 ];
1046
1047 /**
1048 * Returns the server profile data.
1049 *
1050 * @return array<string, string|int|bool|null|object|array<string, string|string[]>> data
1051 */
1052 public function exportData(): array {
1053 $data = [];
1054 $settingsToIgnore = ['modules', 'types', 'tools', 'jobs'];
1055 foreach ($this->settings as $setting) {
1056 if (in_array($setting, $settingsToIgnore)) {
1057 continue;
1058 }
1059 $data[$setting] = $this->$setting;
1060 }
1061 $data['typeSettings'] = $this->typeSettings;
1062 $data['moduleSettings'] = $this->moduleSettings;
1063 $data['toolSettings'] = $this->toolSettings;
1064 $data['jobSettings'] = $this->jobSettings;
1065 return $data;
1066 }
1067
1068 /**
1069 * Imports server profile data.
1070 *
1071 * @param array<string, string|int|bool|null|object|array<string, string|string[]>> $data config data
1072 * @throws LAMException import error
1073 */
1074 public function importData(array $data): void {
1075 $settingsToIgnore = ['modules', 'types', 'tools', 'jobs', 'typeSettings',
1076 'moduleSettings', 'toolSettings', 'jobSettings'];
1077 foreach ($data as $dataKey => $dataValue) {
1078 if (in_array($dataKey, $settingsToIgnore)) {
1079 continue;
1080 }
1081 if (!in_array($dataKey, $this->settings)) {
1082 logNewMessage(LOG_WARNING, 'Ignored setting during import: ' . $dataKey);
1083 continue;
1084 }
1085 if (!(($dataValue === null) || is_array($dataValue) || is_string($dataValue) || is_int($dataValue) || is_bool($dataValue))) {
1086 throw new LAMException('Invalid import data type for ' . htmlspecialchars($dataKey) . ': ' . gettype($dataValue));
1087 }
1088 if ($dataValue !== null) {
1089 $this->$dataKey = $dataValue;
1090 }
1091 else {
1092 logNewMessage(LOG_DEBUG, 'Ignored null value for ' . $dataKey);
1093 }
1094 }
1095 $typeSettingsData = !empty($data['typeSettings']) && is_array($data['typeSettings']) ? $data['typeSettings'] : [];
1096 $this->typeSettings = $typeSettingsData;
1097 $moduleSettingsData = !empty($data['moduleSettings']) && is_array($data['moduleSettings']) ? $data['moduleSettings'] : [];
1098 $this->moduleSettings = $moduleSettingsData;
1099 $toolSettingsData = !empty($data['toolSettings']) && is_array($data['toolSettings']) ? $data['toolSettings'] : [];
1100 $this->toolSettings = $toolSettingsData;
1101 $jobSettingsData = !empty($data['jobSettings']) && is_array($data['jobSettings']) ? $data['jobSettings'] : [];
1102 $this->jobSettings = $jobSettingsData;
1103 }
1104
1105 /**
1106 * Removes any non-existing types from the configuration.
1107 */
1108 public function removeInvalidTypes(): void {
1109 $allTypes = LAM\TYPES\getTypes();
1110 $activeTypes = $this->get_ActiveTypes();
1111 for ($i = 0; $i < count($activeTypes); $i++) {
1112 if (!in_array(getScopeFromTypeId($activeTypes[$i]), $allTypes)) {
1113 unset($activeTypes[$i]);
1114 }
1115 }
1116 $activeTypes = array_values($activeTypes);
1117 $this->set_ActiveTypes($activeTypes);
1118 }
1119
1120 /**
1121 * Removes any non-existing modules from the configuration.
1122 */
1123 public function removeInvalidModules(): void {
1124 $types = $this->get_ActiveTypes();
1125 $availableByScope = [];
1126 foreach ($types as $type) {
1127 $scope = getScopeFromTypeId($type);
1128 $moduleVar = "modules_" . $type;
1129 if (isset($this->typeSettings[$moduleVar])) {
1130 $modules = explode(",", $this->typeSettings[$moduleVar]);
1131 if (empty($availableByScope[$scope])) {
1132 $availableByScope[$scope] = getAvailableModules($scope);
1133 }
1134 $available = $availableByScope[$scope];
1135 // only return available modules
1136 $ret = [];
1137 for ($i = 0; $i < count($modules); $i++) {
1138 if (in_array($modules[$i], $available)) {
1139 $ret[] = $modules[$i];
1140 }
1141 }
1142 $this->typeSettings[$moduleVar] = implode(",", $ret);
1143 }
1144 }
1145 }
1146
1147 /**
1148 * Checks if the given server profile name is valid.
1149 *
1150 * @param string $name server profile name
1151 * @return bool is valid
1152 */
1153 public static function isValidName(string $name): bool {
1154 return preg_match("/^[a-z0-9_-]+$/i", $name);
1155 }
1156
1157 /**
1158 * Returns the name of the config file
1159 *
1160 * @return string name
1161 */
1162 public function getName(): string {
1163 return $this->name;
1164 }
1165
1166 /**
1167 * Sets the name of the config file
1168 *
1169 * @param string $name name
1170 */
1171 public function setName(string $name): void {
1172 $this->name = $name;
1173 }
1174
1175 // functions to read/write preferences
1176
1177 /**
1178 * Returns the server address as string
1179 *
1180 * @return string server address
1181 */
1182 public function get_ServerURL(): string {
1183 return $this->ServerURL;
1184 }
1185
1186 /**
1187 * Sets the server address
1188 *
1189 * @param string|null $value new server address
1190 * @return bool true if $value has correct format
1191 */
1192 public function set_ServerURL(?string $value): bool {
1193 if (is_string($value)) {
1194 $this->ServerURL = $value;
1195 return true;
1196 }
1197 return false;
1198 }
1199
1200 /**
1201 * Returns the server display name. Defaults to server URL if empty display name.
1202 *
1203 * @return string server display name
1204 */
1205 public function getServerDisplayNameGUI(): string {
1206 if (empty($this->serverDisplayName)) {
1207 return $this->ServerURL;
1208 }
1209 return $this->serverDisplayName;
1210 }
1211
1212 /**
1213 * Returns the server display name.
1214 *
1215 * @return string server display name
1216 */
1217 public function getServerDisplayName(): string {
1218 return $this->serverDisplayName;
1219 }
1220
1221 /**
1222 * Sets the server display name
1223 *
1224 * @param string|null $value new server display name
1225 * @return bool true if $value has correct format
1226 */
1227 public function setServerDisplayName(?string $value): bool {
1228 if (is_string($value)) {
1229 $this->serverDisplayName = $value;
1230 return true;
1231 }
1232 return false;
1233 }
1234
1235 /**
1236 * Returns if TLS is activated.
1237 *
1238 * @return string yes or no
1239 */
1240 public function getUseTLS(): string {
1241 return $this->useTLS;
1242 }
1243
1244 /**
1245 * Sets if TLS is activated.
1246 *
1247 * @param string $useTLS yes or no
1248 * @return bool true if $useTLS has correct format
1249 */
1250 public function setUseTLS(string $useTLS): bool {
1251 if (($useTLS === "yes") || ($useTLS === "no")) {
1252 $this->useTLS = $useTLS;
1253 return true;
1254 }
1255 return false;
1256 }
1257
1258 /**
1259 * Returns if referrals should be followed.
1260 *
1261 * @return string true or false
1262 */
1263 public function getFollowReferrals(): string {
1264 return $this->followReferrals;
1265 }
1266
1267 /**
1268 * Sets if referrals should be followed.
1269 *
1270 * @param string $followReferrals true or false
1271 */
1272 public function setFollowReferrals(string $followReferrals): void {
1273 $this->followReferrals = $followReferrals;
1274 }
1275
1276 /**
1277 * Returns if paged results should be used.
1278 *
1279 * @return string true or false
1280 */
1281 public function getPagedResults(): string {
1282 return $this->pagedResults;
1283 }
1284
1285 /**
1286 * Sets if paged results should be used.
1287 *
1288 * @param string $pagedResults true or false
1289 */
1290 public function setPagedResults(string $pagedResults): void {
1291 $this->pagedResults = $pagedResults;
1292 }
1293
1294 /**
1295 * Returns if deleted entries should be shown.
1296 *
1297 * @return string true or false
1298 */
1299 public function getAdShowDeleted(): string {
1300 return $this->adShowDeleted;
1301 }
1302
1303 /**
1304 * Sets if deleted entries should be shown.
1305 *
1306 * @param string $adShowDeleted true or false
1307 */
1308 public function setAdShowDeleted(string $adShowDeleted): void {
1309 $this->adShowDeleted = $adShowDeleted;
1310 }
1311
1312 /**
1313 * Returns if referential integrity overlay is in place.
1314 *
1315 * @return string true or false
1316 */
1317 public function getReferentialIntegrityOverlay(): string {
1318 return $this->referentialIntegrityOverlay;
1319 }
1320
1321 /**
1322 * Sets if referential integrity overlay is in place.
1323 *
1324 * @param string $referentialIntegrityOverlay true or false
1325 */
1326 public function setReferentialIntegrityOverlay(string $referentialIntegrityOverlay): void {
1327 $this->referentialIntegrityOverlay = $referentialIntegrityOverlay;
1328 }
1329
1330 /**
1331 * Returns if referential integrity overlay is in place.
1332 *
1333 * @return bool overlay in place
1334 */
1335 public function isReferentialIntegrityOverlayActive(): bool {
1336 return $this->referentialIntegrityOverlay === 'true';
1337 }
1338
1339 /**
1340 * Hide password prompt for expired passwords.
1341 *
1342 * @return string true or false
1343 */
1344 public function getHidePasswordPromptForExpiredPasswords(): string {
1345 return $this->hidePasswordPromptForExpiredPasswords;
1346 }
1347
1348 /**
1349 * Sets if password prompt for expired passwords is hidden.
1350 *
1351 * @param string $hidePasswordPromptForExpiredPasswords true or false
1352 */
1353 public function setHidePasswordPromptForExpiredPasswords(string $hidePasswordPromptForExpiredPasswords): void {
1354 $this->hidePasswordPromptForExpiredPasswords = $hidePasswordPromptForExpiredPasswords;
1355 }
1356
1357 /**
1358 * Hide password prompt for expired passwords.
1359 *
1360 * @return bool is hidden
1361 */
1362 public function isHidePasswordPromptForExpiredPasswords(): bool {
1363 return $this->hidePasswordPromptForExpiredPasswords === 'true';
1364 }
1365
1366 /**
1367 * Returns an array of string with all admin names
1368 *
1369 * @return string[] the admin names
1370 */
1371 public function get_Admins(): array {
1372 return explode(";", $this->Admins);
1373 }
1374
1375 /**
1376 * Returns all admin users separated by semicolons
1377 *
1378 * @return string the admin string
1379 */
1380 public function get_Adminstring(): string {
1381 return $this->Admins;
1382 }
1383
1384 /**
1385 * Sets the admin string
1386 *
1387 * @param string|null $value new admin string that contains all admin users separated by semicolons
1388 * @return bool true if $value has correct format
1389 */
1390 public function set_Adminstring(?string $value): bool {
1391 if (is_string($value) &&
1392 preg_match("/^[^;]+(;[^;]+)*$/", $value)) {
1393 $this->Admins = $value;
1394 return true;
1395 }
1396 return false;
1397 }
1398
1399 /**
1400 * Checks if the given password matches.
1401 *
1402 * @param string $password password
1403 * @return bool true, if matches
1404 */
1405 public function check_Passwd(string $password): bool {
1406 if (str_starts_with($this->Passwd, "{SSHA}")) {
1407 $value = substr($this->Passwd, strlen("{SSHA}"));
1408 $parts = explode(" ", $value);
1409 $salt = base64_decode($parts[1]);
1410 $hash = "{SSHA}" . base64_encode(hex2bin(sha1($password . $salt))) . " " . base64_encode($salt);
1411 return ($hash === $this->Passwd);
1412 }
1413 elseif (str_starts_with($this->Passwd, "{CRYPT-SHA512}")) {
1414 $value = substr($this->Passwd, strlen("{CRYPT-SHA512}"));
1415 $parts = explode(" ", $value);
1416 $salt = base64_decode($parts[1]);
1417 return ($this->hashPassword($password, $salt) === $this->Passwd);
1418 }
1419 else {
1420 // old nonhashed password
1421 return ($password === $this->Passwd);
1422 }
1423 }
1424
1425 /**
1426 * Sets the preferences wizard password
1427 *
1428 * @param string|null $value new password
1429 * @return bool true if $value has correct format
1430 */
1431 public function set_Passwd(?string $value): bool {
1432 if (is_string($value)) {
1433 $this->Passwd = $this->hashPassword($value, generateSalt(16));
1434 return true;
1435 }
1436 else {
1437 return false;
1438 }
1439 }
1440
1441 /**
1442 * Returns the password hash.
1443 *
1444 * @return string password hash
1445 */
1446 public function getPasswd(): string {
1447 return $this->Passwd;
1448 }
1449
1450 /**
1451 * Returns the hashed password.
1452 *
1453 * @param string $password password
1454 * @param string $salt salt
1455 * @return string hash value
1456 */
1457 private function hashPassword(string $password, string $salt): string {
1458 return "{CRYPT-SHA512}" . crypt($password, '$6$' . $salt) . " " . base64_encode($salt);
1459 }
1460
1461 /**
1462 * Returns if the server profile has a password set.
1463 *
1464 * @return bool password is set
1465 */
1466 public function hasPasswordSet(): bool {
1467 return ($this->Passwd !== null) && ($this->Passwd !== '');
1468 }
1469
1470 /**
1471 * Returns the LDAP suffix for the given account type
1472 *
1473 * @param string $typeId account type
1474 * @return string the LDAP suffix
1475 */
1476 public function get_Suffix(string $typeId): string {
1477 return $this->typeSettings['suffix_' . $typeId] ?? '';
1478 }
1479
1480 /**
1481 * Sets the LDAP suffix where accounts are saved
1482 *
1483 * @param string $typeId account type ID
1484 * @param string|null $value new LDAP suffix
1485 * @return bool true if $value has correct format
1486 */
1487 public function set_Suffix(string $typeId, ?string $value): bool {
1488 if ($value === null) {
1489 $value = "";
1490 }
1491 $this->typeSettings['suffix_' . $typeId] = $value;
1492 return true;
1493 }
1494
1495 /**
1496 * Returns the list of attributes to show in given list.
1497 *
1498 * @param string $typeId account type ID
1499 * @return string the attribute list
1500 */
1501 public function get_listAttributes(string $typeId): string {
1502 return $this->typeSettings['attr_' . $typeId] ?? '';
1503 }
1504
1505 /**
1506 * Sets the list of attributes to show in user list
1507 *
1508 * @param string|null $value new attribute string
1509 * @param string $typeId account type ID
1510 * @return bool true if $value has correct format
1511 */
1512 public function set_listAttributes(?string $value, string $typeId): bool {
1513 if (is_string($value) && preg_match("/^((#[^:;]+)|([^:;]*:[^:;]+))(;((#[^:;]+)|([^:;]*:[^:;]+)))*$/", $value)) {
1514 $this->typeSettings['attr_' . $typeId] = $value;
1515 return true;
1516 }
1517 else {
1518 return false;
1519 }
1520 }
1521
1522 /**
1523 * Returns the default language string
1524 *
1525 * @return string default language
1526 */
1527 public function get_defaultLanguage(): string {
1528 return $this->defaultLanguage;
1529 }
1530
1531 /**
1532 * Sets the default language string
1533 *
1534 * @param string|null $value new default language
1535 * @return bool true if $value has correct format
1536 */
1537 public function set_defaultLanguage(?string $value): bool {
1538 if (is_string($value)) {
1539 $this->defaultLanguage = $value;
1540 }
1541 else {
1542 return false;
1543 }
1544 return true;
1545 }
1546
1547 /**
1548 * Returns the time zone name.
1549 *
1550 * @return string time zone
1551 */
1552 public function getTimeZone(): string {
1553 return ($this->timeZone == null) ? 'Europe/London' : $this->timeZone;
1554 }
1555
1556 /**
1557 * Sets the time zone name.
1558 *
1559 * @param string|null $value new time zone
1560 * @return bool true if $value has correct format
1561 */
1562 public function setTimeZone(?string $value): bool {
1563 if (is_string($value)) {
1564 $this->timeZone = $value;
1565 return true;
1566 }
1567 return false;
1568 }
1569
1570 /**
1571 * Returns the path to the external script
1572 *
1573 * @return string script path
1574 */
1575 public function get_scriptPath(): string {
1576 return $this->scriptPath;
1577 }
1578
1579 /**
1580 * Sets the path to the external script
1581 *
1582 * @param string|null $value new script path
1583 * @return bool true if $value has correct format
1584 */
1585 public function set_scriptPath(?string $value): bool {
1586 if (empty($value)) {
1587 $this->scriptPath = ""; // optional parameter
1588 }
1589 elseif (preg_match("/^\\/([a-z0-9_-])+(\\/([a-z0-9_\\.-])+)+$/i", $value)) {
1590 $this->scriptPath = $value;
1591 }
1592 else {
1593 return false;
1594 }
1595 return true;
1596 }
1597
1598 /**
1599 * Returns the servers of the external script as a Array
1600 *
1601 * @return string script servers
1602 */
1603 public function get_scriptServers(): string {
1604 return $this->scriptServer;
1605 }
1606
1607 /**
1608 * Returns the list of configured servers.
1609 *
1610 * @return RemoteServerConfiguration[] servers
1611 */
1612 public function getConfiguredScriptServers(): array {
1613 return LAMConfig::parseConfiguredScriptServers($this->scriptServer, $this->get_scriptPath(),
1614 $this->getScriptUserName(), $this->getScriptSSHKey(), $this->getScriptSSHKeyPassword());
1615 }
1616
1617 /**
1618 * Parses the configured server config.
1619 *
1620 * @param string $value configured value
1621 * @param string $scriptPath script path
1622 * @param string $userName user name
1623 * @param string $sshKey SSH key path
1624 * @param string $sshKeyPassword SSH key password
1625 * @return RemoteServerConfiguration[] configurations
1626 */
1627 public static function parseConfiguredScriptServers(string $value, string $scriptPath, string $userName, string $sshKey, string $sshKeyPassword): array {
1628 $servers = [];
1629 if (empty($value)) {
1630 return $servers;
1631 }
1632 $serverChunks = explode(';', $value);
1633 foreach ($serverChunks as $serverChunk) {
1634 if (empty($serverChunk)) {
1635 continue;
1636 }
1637 $serverSettings = explode(':', $serverChunk);
1638 $serverName = $serverSettings[0];
1639 $serverLabel = $serverSettings[1] ?? '';
1640 $serverHomedirPrefix = $serverSettings[2] ?? '';
1641 $servers[] = new RemoteServerConfiguration($serverName, $serverLabel, $serverHomedirPrefix, $scriptPath, $userName, $sshKey, $sshKeyPassword);
1642 }
1643 return $servers;
1644 }
1645
1646 /**
1647 * Returns the script server object for the given name.
1648 *
1649 * @param string $serverName server name
1650 * @return RemoteServerConfiguration|null server
1651 */
1652 public function getScriptServerByName(string $serverName): ?RemoteServerConfiguration {
1653 $serverList = $this->getConfiguredScriptServers();
1654 foreach ($serverList as $server) {
1655 if ($serverName === $server->getServer()) {
1656 return $server;
1657 }
1658 }
1659 return null;
1660 }
1661
1662 /**
1663 * Sets the servers of the external script
1664 *
1665 * @param string $value new script servers
1666 * @return bool true if $value has correct format
1667 */
1668 public function set_scriptServers(string $value): bool {
1669 $parsedValue = LAMConfig::parseScriptServerValue($value);
1670 if ($parsedValue === false) {
1671 return false;
1672 }
1673 $this->scriptServer = $parsedValue;
1674 return true;
1675 }
1676
1677 /**
1678 * Parses the script server value from input field.
1679 *
1680 * @param string $value input field value
1681 * @return string|false value to store in configuration
1682 */
1683 public static function parseScriptServerValue(string $value): false|string {
1684 if (empty($value)) {
1685 return ""; // optional parameter
1686 }
1687 // Explode the value to an array
1688 $array_string = explode(";", $value);
1689 // Check all IPs in the exploded Array
1690 $valid_ips = [];
1691 foreach ($array_string as $arr_value) {
1692 // Explode name and IP, if a name exists
1693 if (str_contains($arr_value, ":")) {
1694 $arr_value_explode = explode(":", $arr_value);
1695 $servername = $arr_value_explode[0];
1696 $label = $arr_value_explode[1];
1697 $homedirPrefix = $arr_value_explode[2] ?? '';
1698 }
1699 else {
1700 $servername = $arr_value;
1701 $label = '';
1702 $homedirPrefix = '';
1703 }
1704 if (preg_match("/^[a-z0-9-]+(\\.[a-z0-9-]+)*(,[0-9]+)?$/i", $servername)) {
1705 $serverData = [$servername];
1706 if (!empty($label)) {
1707 $serverData[] = $label;
1708 }
1709 if (!empty($homedirPrefix)) {
1710 $serverData[] = $homedirPrefix;
1711 }
1712 $serverChunk = implode(':', $serverData);
1713 $valid_ips[] = $serverChunk;
1714 }
1715 else {
1716 // wrong format
1717 return false;
1718 }
1719 }
1720 // Check that the array is not empty
1721 if ($valid_ips !== []) {
1722 return implode(";", $valid_ips);
1723 }
1724 else {
1725 // The array is empty, there was no valid IP
1726 return false;
1727 }
1728 }
1729
1730 /**
1731 * Returns the chmod value for new home directories.
1732 *
1733 * @return string rights
1734 */
1735 public function get_scriptRights() {
1736 if (empty($this->scriptRights)) {
1737 return '750';
1738 }
1739 return $this->scriptRights;
1740 }
1741
1742 /**
1743 * Sets the rights for the home directory.
1744 *
1745 * @param string $chmod the rights
1746 * @return bool true if values has correct format
1747 */
1748 public function set_scriptRights(string $chmod): bool {
1749 // check if the chmod is correct:
1750 if ($chmod > 0 && $chmod <= 777) {
1751 $this->scriptRights = $chmod;
1752 return true;
1753 }
1754 else {
1755 return false;
1756 }
1757 }
1758
1759 /**
1760 * Returns the path to lamdamon SSH key.
1761 *
1762 * @return string key path
1763 */
1764 public function getScriptSSHKey(): string {
1765 return $this->scriptSSHKey;
1766 }
1767
1768 /**
1769 * Sets the path to lamdamon SSH key.
1770 *
1771 * @param string $value key path
1772 */
1773 public function setScriptSSHKey(string $value): void {
1774 $this->scriptSSHKey = $value;
1775 }
1776
1777 /**
1778 * Returns the password for the lamdamon SSH key.
1779 *
1780 * @return string password
1781 */
1782 public function getScriptSSHKeyPassword(): string {
1783 return deobfuscateText($this->scriptSSHKeyPassword);
1784 }
1785
1786 /**
1787 * Sets the password for the lamdamon SSH key.
1788 *
1789 * @param string $value password
1790 */
1791 public function setScriptSSHKeyPassword(string $value): void {
1792 $this->scriptSSHKeyPassword = obfuscateText($value);
1793 }
1794
1795 /**
1796 * Returns the lamdaemon user name.
1797 *
1798 * @return string user name
1799 */
1800 public function getScriptUserName(): string {
1801 return $this->scriptUserName;
1802 }
1803
1804 /**
1805 * Sets the lamdaemon user name.
1806 *
1807 * @param string $value user name
1808 */
1809 public function setScriptUserName(string $value): void {
1810 $this->scriptUserName = $value;
1811 }
1812
1813 /**
1814 * Returns the LDAP search limit.
1815 *
1816 * @return int search limit
1817 */
1818 public function get_searchLimit(): int {
1819 return $this->searchLimit;
1820 }
1821
1822 /**
1823 * Sets the LDAP search limit.
1824 *
1825 * @param int $value new search limit
1826 * @return bool true if $value has correct format
1827 */
1828 public function set_searchLimit(int $value): bool {
1829 if ($value > -1) {
1830 $this->searchLimit = $value;
1831 return true;
1832 }
1833 return false;
1834 }
1835
1836 /**
1837 * Returns an array of all selected account modules
1838 *
1839 * @param string $scope account type
1840 * @return class-string<baseModule>[] user modules
1841 */
1842 public function get_AccountModules($scope) {
1843 if (isset($this->typeSettings["modules_" . $scope])) {
1844 $modulesTmp = explode(",", $this->typeSettings["modules_" . $scope]);
1845 $modules = [];
1846 foreach ($modulesTmp as $mod) {
1847 if (trim($mod) !== '') {
1848 $modules[] = $mod;
1849 }
1850 }
1851 return $modules;
1852 }
1853 else {
1854 return [];
1855 }
1856 }
1857
1858 /**
1859 * Sets the settings for the account modules.
1860 *
1861 * @param array<string, string[]> $settings list of module setting [name => value]
1862 */
1863 public function set_moduleSettings(array $settings): void {
1864 $this->moduleSettings = $settings;
1865 }
1866
1867 /**
1868 * Returns a list of saved module settings
1869 *
1870 * @return array<string, string[]> list of settings: [name => value]
1871 */
1872 public function get_moduleSettings(): array {
1873 return $this->moduleSettings;
1874 }
1875
1876 /**
1877 * Returns a list of active account types.
1878 *
1879 * @return string[] list of types
1880 */
1881 public function get_ActiveTypes(): array {
1882 if (empty($this->activeTypes)) {
1883 return [];
1884 }
1885 else {
1886 return explode(",", $this->activeTypes);
1887 }
1888 }
1889
1890 /**
1891 * Returns a list of active account types as string.
1892 *
1893 * @return string list of types
1894 */
1895 public function getActiveTypesString(): string {
1896 return $this->activeTypes;
1897 }
1898
1899 /**
1900 * Sets the list of active types.
1901 *
1902 * @param string[] $types list of types
1903 */
1904 public function set_ActiveTypes(array $types): void {
1905 $this->activeTypes = implode(",", $types);
1906 }
1907
1908 /**
1909 * Sets the settings for the account types.
1910 *
1911 * @param array<string, string> $settings list of type setting [name => value]
1912 */
1913 public function set_typeSettings(array $settings): void {
1914 $this->typeSettings = $settings;
1915 }
1916
1917 /**
1918 * Returns a list of saved type settings
1919 *
1920 * @return array<string, string> list of settings: [name => value]
1921 */
1922 public function get_typeSettings(): array {
1923 return $this->typeSettings;
1924 }
1925
1926 /**
1927 * Returns the tool settings.
1928 *
1929 * @return array<string, string> $toolSettings tool settings
1930 */
1931 public function getToolSettings(): array {
1932 return $this->toolSettings;
1933 }
1934
1935 /**
1936 * Sets the tool settings.
1937 *
1938 * @param array<string,string> $toolSettings tool settings
1939 */
1940 public function setToolSettings(array $toolSettings): void {
1941 $this->toolSettings = $toolSettings;
1942 }
1943
1944 /**
1945 * Checks if the given tool is activated.
1946 *
1947 * @param string $toolName tool name
1948 * @return bool is active
1949 */
1950 public function isToolActive(string $toolName): bool {
1951 return !isset($this->toolSettings['tool_hide_' . $toolName]) || ($this->toolSettings['tool_hide_' . $toolName] !== 'true');
1952 }
1953
1954 /**
1955 * Returns the access level for this profile.
1956 *
1957 * @return string level
1958 */
1959 public function getAccessLevel(): string {
1960 return $this->accessLevel;
1961 }
1962
1963 /**
1964 * Sets the access level for this profile.
1965 *
1966 * @param string $level level
1967 */
1968 public function setAccessLevel(string $level): void {
1969 $this->accessLevel = $level;
1970 }
1971
1972 /**
1973 * Returns the login method.
1974 *
1975 * @return string login method
1976 * @see LAMconfig::LOGIN_LIST
1977 * @see LAMconfig::LOGIN_SEARCH
1978 */
1979 public function getLoginMethod(): string {
1980 return $this->loginMethod;
1981 }
1982
1983 /**
1984 * Sets the login method.
1985 *
1986 * @param string $loginMethod login method
1987 */
1988 public function setLoginMethod(string $loginMethod): void {
1989 $this->loginMethod = $loginMethod;
1990 }
1991
1992 /**
1993 * Returns the login search filter.
1994 *
1995 * @return string search filter
1996 */
1997 public function getLoginSearchFilter(): string {
1998 return $this->loginSearchFilter;
1999 }
2000
2001 /**
2002 * Sets the login search filter.
2003 *
2004 * @param string $loginSearchFilter search filter
2005 */
2006 public function setLoginSearchFilter(string $loginSearchFilter): void {
2007 $this->loginSearchFilter = $loginSearchFilter;
2008 }
2009
2010 /**
2011 * Returns the login search suffix.
2012 *
2013 * @return string suffix
2014 */
2015 public function getLoginSearchSuffix(): string {
2016 return $this->loginSearchSuffix;
2017 }
2018
2019 /**
2020 * Sets the login search suffix.
2021 *
2022 * @param string $loginSearchSuffix suffix
2023 */
2024 public function setLoginSearchSuffix(string $loginSearchSuffix): void {
2025 $this->loginSearchSuffix = $loginSearchSuffix;
2026 }
2027
2028 /**
2029 * Sets the DN for the login search bind user.
2030 *
2031 * @param string $loginSearchDN DN
2032 * @return bool true if DN is valid
2033 */
2034 public function setLoginSearchDN(string $loginSearchDN): bool {
2035 $this->loginSearchDN = $loginSearchDN;
2036 return ($loginSearchDN === '') || get_preg($loginSearchDN, 'dn');
2037 }
2038
2039 /**
2040 * Returns the DN for the login search bind user.
2041 *
2042 * @return string DN
2043 */
2044 public function getLoginSearchDN(): string {
2045 return $this->loginSearchDN;
2046 }
2047
2048 /**
2049 * Sets the password for the login search bind user.
2050 *
2051 * @param string $loginSearchPassword password
2052 */
2053 public function setLoginSearchPassword(string $loginSearchPassword): void {
2054 $this->loginSearchPassword = obfuscateText($loginSearchPassword);
2055 }
2056
2057 /**
2058 * Returns the password for the login search bind user.
2059 *
2060 * @return string password
2061 */
2062 public function getLoginSearchPassword(): string {
2063 return deobfuscateText($this->loginSearchPassword);
2064 }
2065
2066 /**
2067 * Returns if HTTP authentication should be used.
2068 *
2069 * @return string $httpAuthentication use HTTP authentication ('true' or 'false')
2070 */
2071 public function getHttpAuthentication(): string {
2072 return $this->httpAuthentication;
2073 }
2074
2075 /**
2076 * Specifies if HTTP authentication should be used.
2077 *
2078 * @param string $httpAuthentication use HTTP authentication ('true' or 'false')
2079 */
2080 public function setHttpAuthentication(string $httpAuthentication): void {
2081 $this->httpAuthentication = $httpAuthentication;
2082 }
2083
2084 /**
2085 * Returns the sender address for password reset mails.
2086 *
2087 * @return string mail address
2088 */
2089 public function getLamProMailFrom(): string {
2090 if (empty($this->lamProMailFrom)) {
2091 return '[email protected]';
2092 }
2093 return $this->lamProMailFrom;
2094 }
2095
2096 /**
2097 * Sets the sender address for password reset mails.
2098 *
2099 * @param string $lamProMailFrom mail address
2100 * @return bool true if address is valid
2101 */
2102 public function setLamProMailFrom(string $lamProMailFrom): bool {
2103 $this->lamProMailFrom = $lamProMailFrom;
2104 if (($lamProMailFrom !== '') && !get_preg($lamProMailFrom, 'email') && !get_preg($lamProMailFrom, 'emailWithName')) {
2105 return false;
2106 }
2107 return true;
2108 }
2109
2110 /**
2111 * Returns the reply-to address for password reset mails.
2112 *
2113 * @return string mail address
2114 */
2115 public function getLamProMailReplyTo(): string {
2116 return $this->lamProMailReplyTo;
2117 }
2118
2119 /**
2120 * Sets the reply-to address for password reset mails.
2121 *
2122 * @param string $lamProMailReplyTo mail address
2123 * @return bool true if address is valid
2124 */
2125 public function setLamProMailReplyTo(string $lamProMailReplyTo): bool {
2126 $this->lamProMailReplyTo = $lamProMailReplyTo;
2127 if (($lamProMailReplyTo !== '') && !get_preg($lamProMailReplyTo, 'email') && !get_preg($lamProMailReplyTo, 'emailWithName')) {
2128 return false;
2129 }
2130 return true;
2131 }
2132
2133 /**
2134 * Returns the subject for password reset mails.
2135 *
2136 * @return string subject
2137 */
2138 public function getLamProMailSubject(): string {
2139 return $this->lamProMailSubject;
2140 }
2141
2142 /**
2143 * Sets the subject for password reset mails.
2144 *
2145 * @param string $lamProMailSubject subject
2146 */
2147 public function setLamProMailSubject(string $lamProMailSubject): void {
2148 $this->lamProMailSubject = $lamProMailSubject;
2149 }
2150
2151 /**
2152 * Returns if the password reset mail content should be treated as HTML.
2153 *
2154 * @return string HTML or text
2155 */
2156 public function getLamProMailIsHTML(): string {
2157 return $this->lamProMailIsHTML;
2158 }
2159
2160 /**
2161 * Sets if the password reset mail content should be treated as HTML.
2162 *
2163 * @param string $lamProMailIsHTML true if HTML
2164 */
2165 public function setLamProMailIsHTML(string $lamProMailIsHTML): void {
2166 $this->lamProMailIsHTML = $lamProMailIsHTML;
2167 }
2168
2169 /**
2170 * Returns if sending to an alternate address is allowed.
2171 *
2172 * @return string alternate address allowed
2173 */
2174 public function getLamProMailAllowAlternateAddress(): string {
2175 return $this->lamProMailAllowAlternateAddress;
2176 }
2177
2178 /**
2179 * Sets if sending to an alternate address is allowed.
2180 *
2181 * @param string $lamProMailAllowAlternateAddress alternate address allowed
2182 */
2183 public function setLamProMailAllowAlternateAddress(string $lamProMailAllowAlternateAddress): void {
2184 $this->lamProMailAllowAlternateAddress = $lamProMailAllowAlternateAddress;
2185 }
2186
2187 /**
2188 * Returns the mail body for password reset mails.
2189 *
2190 * @return string body
2191 */
2192 public function getLamProMailText(): string {
2193 return implode("\r\n", explode(LAMConfig::LINE_SEPARATOR, $this->lamProMailText));
2194 }
2195
2196 /**
2197 * Returns the mail body for password reset mails without formatting.
2198 *
2199 * @return string body
2200 */
2201 public function getLamProMailTextRaw(): string {
2202 return $this->lamProMailText;
2203 }
2204
2205 /**
2206 * Sets the mail body for password reset mails.
2207 *
2208 * @param string $lamProMailText body
2209 */
2210 public function setLamProMailText(string $lamProMailText): void {
2211 $this->lamProMailText = implode(LAMConfig::LINE_SEPARATOR, explode("\r\n", $lamProMailText));
2212 }
2213
2214 /**
2215 * Returns the bind user for jobs.
2216 *
2217 * @return string $jobsBindUser bind user
2218 */
2219 public function getJobsBindUser(): string {
2220 return $this->jobsBindUser ?? '';
2221 }
2222
2223 /**
2224 * Sets the bind user for jobs.
2225 *
2226 * @param string $jobsBindUser bind user
2227 */
2228 public function setJobsBindUser(string $jobsBindUser): void {
2229 $this->jobsBindUser = $jobsBindUser;
2230 }
2231
2232 /**
2233 * Returns the bind password for jobs.
2234 *
2235 * @return string $jobsBindPassword password
2236 */
2237 public function getJobsBindPassword(): string {
2238 return $this->jobsBindPassword ?? '';
2239 }
2240
2241 /**
2242 * Sets the bind password for jobs.
2243 *
2244 * @param string $jobsBindPassword password
2245 */
2246 public function setJobsBindPassword(string $jobsBindPassword): void {
2247 $this->jobsBindPassword = $jobsBindPassword;
2248 }
2249
2250 /**
2251 * Returns the database type for jobs.
2252 *
2253 * @return string $jobsDatabase database type
2254 */
2255 public function getJobsDatabase(): string {
2256 if (empty($this->jobsDatabase)) {
2257 return 'SQLite';
2258 }
2259 return $this->jobsDatabase;
2260 }
2261
2262 /**
2263 * Sets the database type for jobs.
2264 *
2265 * @param string $jobsDatabase database type
2266 */
2267 public function setJobsDatabase(string $jobsDatabase): void {
2268 $this->jobsDatabase = $jobsDatabase;
2269 }
2270
2271 /**
2272 * Returns the host.
2273 *
2274 * @return string host
2275 */
2276 public function getJobsDBHost(): string {
2277 return $this->jobsDBHost ?? '';
2278 }
2279
2280 /**
2281 * Sets the host.
2282 *
2283 * @param string $jobsDBHost host
2284 */
2285 public function setJobsDBHost(string $jobsDBHost): void {
2286 $this->jobsDBHost = $jobsDBHost;
2287 }
2288
2289 /**
2290 * Returns the port.
2291 *
2292 * @return string port
2293 */
2294 public function getJobsDBPort(): string {
2295 return $this->jobsDBPort ?? '';
2296 }
2297
2298 /**
2299 * Sets the port.
2300 *
2301 * @param string $jobsDBPort port
2302 */
2303 public function setJobsDBPort(string $jobsDBPort): void {
2304 $this->jobsDBPort = $jobsDBPort;
2305 }
2306
2307 /**
2308 * Returns the CA certificate path.
2309 *
2310 * @return string path
2311 */
2312 public function getJobsDBCaPath(): string {
2313 return $this->jobsDBCaPath ?? '';
2314 }
2315
2316 /**
2317 * Sets the CA certificate path.
2318 *
2319 * @param string $jobsDBCaPath path
2320 */
2321 public function setJobsDBCaPath(string $jobsDBCaPath): void {
2322 $this->jobsDBCaPath = $jobsDBCaPath;
2323 }
2324
2325 /**
2326 * Returns the DB user.
2327 *
2328 * @return string user name
2329 */
2330 public function getJobsDBUser(): string {
2331 return $this->jobsDBUser ?? '';
2332 }
2333
2334 /**
2335 * Sets the DB user.
2336 *
2337 * @param string $jobsDBUser user name
2338 */
2339 public function setJobsDBUser(string $jobsDBUser): void {
2340 $this->jobsDBUser = $jobsDBUser;
2341 }
2342
2343 /**
2344 * Returns the DB password.
2345 *
2346 * @return string password
2347 */
2348 public function getJobsDBPassword(): string {
2349 return $this->jobsDBPassword ?? '';
2350 }
2351
2352 /**
2353 * Sets the DB password.
2354 *
2355 * @param string $jobsDBPassword password
2356 */
2357 public function setJobsDBPassword(string $jobsDBPassword): void {
2358 $this->jobsDBPassword = $jobsDBPassword;
2359 }
2360
2361 /**
2362 * Returns the database name.
2363 *
2364 * @return string DB name
2365 */
2366 public function getJobsDBName(): string {
2367 return $this->jobsDBName ?? '';
2368 }
2369
2370 /**
2371 * Sets the database name
2372 *
2373 * @param string $jobsDBName DB name
2374 */
2375 public function setJobsDBName(string $jobsDBName): void {
2376 $this->jobsDBName = $jobsDBName;
2377 }
2378
2379 /**
2380 * Sets the settings for the jobs.
2381 *
2382 * @param array<string, string[]> $settings list of job settings [name => value]
2383 */
2384 public function setJobSettings(array $settings): void {
2385 $this->jobSettings = $settings;
2386 }
2387
2388 /**
2389 * Returns a list of saved job settings.
2390 *
2391 * @return array<string, string[]> list of settings: [name => value]
2392 */
2393 public function getJobSettings(): array {
2394 return $this->jobSettings;
2395 }
2396
2397 /**
2398 * Returns if setting a specific password is allowed on password reset page.
2399 *
2400 * @return string 'true' or 'false'
2401 */
2402 public function getPwdResetAllowSpecificPassword(): string {
2403 return $this->pwdResetAllowSpecificPassword;
2404 }
2405
2406 /**
2407 * Sets if setting a specific password is allowed on password reset page.
2408 *
2409 * @param string $pwdResetAllowSpecificPassword 'true' or 'false'
2410 */
2411 public function setPwdResetAllowSpecificPassword(string $pwdResetAllowSpecificPassword): void {
2412 $this->pwdResetAllowSpecificPassword = $pwdResetAllowSpecificPassword;
2413 }
2414
2415 /**
2416 * Returns if displaying password on screen is allowed on password reset page.
2417 *
2418 * @return string 'true' or 'false'
2419 */
2420 public function getPwdResetAllowScreenPassword(): string {
2421 return $this->pwdResetAllowScreenPassword;
2422 }
2423
2424 /**
2425 * Sets if displaying password on screen is allowed on password reset page.
2426 *
2427 * @param string $pwdResetAllowScreenPassword 'true' or 'false'
2428 */
2429 public function setPwdResetAllowScreenPassword(string $pwdResetAllowScreenPassword): void {
2430 $this->pwdResetAllowScreenPassword = $pwdResetAllowScreenPassword;
2431 }
2432
2433 /**
2434 * Returns if force password change is set by default on password reset page.
2435 *
2436 * @return string 'true' or 'false'
2437 */
2438 public function getPwdResetForcePasswordChange(): string {
2439 return $this->pwdResetForcePasswordChange;
2440 }
2441
2442 /**
2443 * Sets if force password change is set by default on password reset page.
2444 *
2445 * @param string $pwdResetForcePasswordChange 'true' or 'false'
2446 */
2447 public function setPwdResetForcePasswordChange(string $pwdResetForcePasswordChange): void {
2448 $this->pwdResetForcePasswordChange = $pwdResetForcePasswordChange;
2449 }
2450
2451 /**
2452 * Returns default password output method on password reset page.
2453 *
2454 * @return string LAMConfig::PWDRESET_DEFAULT_SCREEN/PWDRESET_DEFAULT_MAIL/PWDRESET_DEFAULT_BOTH
2455 */
2456 public function getPwdResetDefaultPasswordOutput(): string {
2457 return $this->pwdResetDefaultPasswordOutput;
2458 }
2459
2460 /**
2461 * Sets default password output method on password reset page.
2462 *
2463 * @param string $pwdResetDefaultPasswordOutput LAMConfig::PWDRESET_DEFAULT_SCREEN/PWDRESET_DEFAULT_MAIL/PWDRESET_DEFAULT_BOTH
2464 */
2465 public function setPwdResetDefaultPasswordOutput(string $pwdResetDefaultPasswordOutput): void {
2466 $this->pwdResetDefaultPasswordOutput = $pwdResetDefaultPasswordOutput;
2467 }
2468
2469 /**
2470 * Returns the authentication type.
2471 *
2472 * @return string $twoFactorAuthentication authentication type
2473 */
2474 public function getTwoFactorAuthentication(): string {
2475 if (empty($this->twoFactorAuthentication)) {
2476 return TwoFactorProviderService::TWO_FACTOR_NONE;
2477 }
2478 return $this->twoFactorAuthentication;
2479 }
2480
2481 /**
2482 * Sets the authentication type.
2483 *
2484 * @param string $twoFactorAuthentication authentication type
2485 */
2486 public function setTwoFactorAuthentication(string $twoFactorAuthentication): void {
2487 $this->twoFactorAuthentication = $twoFactorAuthentication;
2488 }
2489
2490 /**
2491 * Returns the authentication URL.
2492 *
2493 * @return string authentication URL
2494 */
2495 public function getTwoFactorAuthenticationURL(): string {
2496 return implode("\r\n", explode(LAMConfig::LINE_SEPARATOR, $this->twoFactorAuthenticationURL));
2497 }
2498
2499 /**
2500 * Returns the authentication URL without formatting.
2501 *
2502 * @return string authentication URL
2503 */
2504 public function getTwoFactorAuthenticationURLRaw(): string {
2505 return $this->twoFactorAuthenticationURL;
2506 }
2507
2508 /**
2509 * Sets the authentication URL.
2510 *
2511 * @param string $twoFactorAuthenticationURL authentication URL
2512 */
2513 public function setTwoFactorAuthenticationURL(string $twoFactorAuthenticationURL): void {
2514 $this->twoFactorAuthenticationURL = implode(LAMConfig::LINE_SEPARATOR, explode("\r\n", $twoFactorAuthenticationURL));
2515 }
2516
2517 /**
2518 * Sets the client id.
2519 *
2520 * @param string $clientId client id
2521 */
2522 public function setTwoFactorAuthenticationClientId(string $clientId): void {
2523 $this->twoFactorAuthenticationClientId = $clientId;
2524 }
2525
2526 /**
2527 * Returns the client id.
2528 *
2529 * @return string client id
2530 */
2531 public function getTwoFactorAuthenticationClientId(): string {
2532 return $this->twoFactorAuthenticationClientId;
2533 }
2534
2535 /**
2536 * Sets the secret key.
2537 *
2538 * @param string $secretKey secret key
2539 */
2540 public function setTwoFactorAuthenticationSecretKey(string $secretKey): void {
2541 $this->twoFactorAuthenticationSecretKey = $secretKey;
2542 }
2543
2544 /**
2545 * Returns the secret key.
2546 *
2547 * @return string secret key
2548 */
2549 public function getTwoFactorAuthenticationSecretKey(): string {
2550 return $this->twoFactorAuthenticationSecretKey;
2551 }
2552
2553 /**
2554 * Sets the domain.
2555 *
2556 * @param string $domain domain
2557 */
2558 public function setTwoFactorAuthenticationDomain(string $domain): void {
2559 $this->twoFactorAuthenticationDomain = $domain;
2560 }
2561
2562 /**
2563 * Returns the domain.
2564 *
2565 * @return string domain
2566 */
2567 public function getTwoFactorAuthenticationDomain(): string {
2568 return $this->twoFactorAuthenticationDomain;
2569 }
2570
2571 /**
2572 * Returns if SSL certificate verification is turned off.
2573 *
2574 * @return bool SSL certificate verification is turned off
2575 */
2576 public function getTwoFactorAuthenticationInsecure(): bool {
2577 return $this->twoFactorAuthenticationInsecure;
2578 }
2579
2580 /**
2581 * Sets if SSL certificate verification is turned off.
2582 *
2583 * @param bool $twoFactorAuthenticationInsecure SSL certificate verification is turned off
2584 */
2585 public function setTwoFactorAuthenticationInsecure(bool $twoFactorAuthenticationInsecure): void {
2586 $this->twoFactorAuthenticationInsecure = $twoFactorAuthenticationInsecure;
2587 }
2588
2589 /**
2590 * Returns the authentication label.
2591 *
2592 * @return string authentication label
2593 */
2594 public function getTwoFactorAuthenticationLabel(): string {
2595 return $this->twoFactorAuthenticationLabel;
2596 }
2597
2598 /**
2599 * Sets the authentication label.
2600 *
2601 * @param string $twoFactorAuthenticationLabel authentication label
2602 */
2603 public function setTwoFactorAuthenticationLabel(string $twoFactorAuthenticationLabel): void {
2604 $this->twoFactorAuthenticationLabel = $twoFactorAuthenticationLabel;
2605 }
2606
2607 /**
2608 * Returns if 2nd factor is optional.
2609 *
2610 * @return bool 2nd factor is optional
2611 */
2612 public function getTwoFactorAuthenticationOptional(): bool {
2613 return $this->twoFactorAuthenticationOptional;
2614 }
2615
2616 /**
2617 * Sets if 2nd factor is optional.
2618 *
2619 * @param bool $twoFactorAuthenticationOptional 2nd factor is optional
2620 */
2621 public function setTwoFactorAuthenticationOptional(bool $twoFactorAuthenticationOptional): void {
2622 $this->twoFactorAuthenticationOptional = $twoFactorAuthenticationOptional;
2623 }
2624
2625 /**
2626 * Returns the caption HTML.
2627 *
2628 * @return string caption HTML
2629 */
2630 public function getTwoFactorAuthenticationCaption(): string {
2631 return $this->twoFactorAuthenticationCaption;
2632 }
2633
2634 /**
2635 * Sets the caption HTML.
2636 *
2637 * @param string $twoFactorAuthenticationCaption caption HTML
2638 */
2639 public function setTwoFactorAuthenticationCaption(string $twoFactorAuthenticationCaption): void {
2640 $this->twoFactorAuthenticationCaption = $twoFactorAuthenticationCaption;
2641 }
2642
2643 /**
2644 * Returns the user attribute.
2645 *
2646 * @return string user attribute
2647 */
2648 public function getTwoFactorAuthenticationAttribute(): string {
2649 if (empty($this->twoFactorAuthenticationAttribute)) {
2650 return 'uid';
2651 }
2652 return $this->twoFactorAuthenticationAttribute;
2653 }
2654
2655 /**
2656 * Sets the user attribute.
2657 *
2658 * @param string $twoFactorAuthenticationAttribute user attribute
2659 */
2660 public function setTwoFactorAuthenticationAttribute(string $twoFactorAuthenticationAttribute): void {
2661 $this->twoFactorAuthenticationAttribute = $twoFactorAuthenticationAttribute;
2662 }
2663
2664 /**
2665 * Returns if remembering devices is allowed.
2666 *
2667 * @return string remembering allowed
2668 */
2669 public function getTwoFactorAllowToRememberDevice(): string {
2670 if (empty($this->twoFactorAllowToRememberDevice)) {
2671 return 'false';
2672 }
2673 return $this->twoFactorAllowToRememberDevice;
2674 }
2675
2676 /**
2677 * Sets the user attribute.
2678 *
2679 * @param string $twoFactorAllowToRememberDevice remembering allowed
2680 */
2681 public function setTwoFactorAllowToRememberDevice(string $twoFactorAllowToRememberDevice): void {
2682 $this->twoFactorAllowToRememberDevice = $twoFactorAllowToRememberDevice;
2683 }
2684
2685 /**
2686 * Returns the duration for device remembering in hours.
2687 *
2688 * @return string duration
2689 */
2690 public function getTwoFactorRememberDeviceDuration(): string {
2691 if (empty($this->twoFactorRememberDeviceDuration)) {
2692 return strval(8 * 60 * 60);
2693 }
2694 return $this->twoFactorRememberDeviceDuration;
2695 }
2696
2697 /**
2698 * Sets the duration for device remembering in hours.
2699 *
2700 * @param string $twoFactorRememberDeviceDuration duration in hours
2701 */
2702 public function setTwoFactorRememberDeviceDuration(string $twoFactorRememberDeviceDuration): void {
2703 $this->twoFactorRememberDeviceDuration = $twoFactorRememberDeviceDuration;
2704 }
2705
2706 /**
2707 * Returns the password for device remembering.
2708 *
2709 * @return string password
2710 */
2711 public function getTwoFactorRememberDevicePassword(): string {
2712 if (empty($this->twoFactorRememberDevicePassword)) {
2713 return generateRandomPassword(30);
2714 }
2715 return $this->twoFactorRememberDevicePassword;
2716 }
2717
2718 /**
2719 * Sets the password for device remembering.
2720 *
2721 * @param string $twoFactorRememberDevicePassword password
2722 */
2723 public function setTwoFactorRememberDevicePassword(string $twoFactorRememberDevicePassword): void {
2724 $this->twoFactorRememberDevicePassword = $twoFactorRememberDevicePassword;
2725 }
2726
2727 /**
2728 * Returns the DN part to hide.
2729 *
2730 * @return string DN part
2731 */
2732 public function getHideDnPart(): string {
2733 return $this->hideDnPart;
2734 }
2735
2736 /**
2737 * Sets the DN part to hide.
2738 *
2739 * @param string $hideDnPart DN part
2740 */
2741 public function setHideDnPart(string $hideDnPart): void {
2742 $this->hideDnPart = $hideDnPart;
2743 }
2744
2745 /**
2746 * Returns the minimum password length.
2747 *
2748 * @return string minimum length
2749 */
2750 public function getPwdPolicyMinLength(): string {
2751 return $this->pwdPolicyMinLength;
2752 }
2753
2754 /**
2755 * Sets the minimum password length.
2756 *
2757 * @param string $pwdPolicyMinLength minimum length
2758 */
2759 public function setPwdPolicyMinLength(string $pwdPolicyMinLength): void {
2760 $this->pwdPolicyMinLength = $pwdPolicyMinLength;
2761 }
2762
2763 /**
2764 * Returns the minimum of lowercase characters.
2765 *
2766 * @return string minimum
2767 */
2768 public function getpwdPolicyMinLowercase(): string {
2769 return $this->pwdPolicyMinLowercase;
2770 }
2771
2772 /**
2773 * Sets the minimum of lowercase characters.
2774 *
2775 * @param string $pwdPolicyMinLowercase minimum
2776 */
2777 public function setPwdPolicyMinLowercase(string $pwdPolicyMinLowercase): void {
2778 $this->pwdPolicyMinLowercase = $pwdPolicyMinLowercase;
2779 }
2780
2781 /**
2782 * Returns the minimum of uppercase characters.
2783 *
2784 * @return string minimum
2785 */
2786 public function getPwdPolicyMinUppercase(): string {
2787 return $this->pwdPolicyMinUppercase;
2788 }
2789
2790 /**
2791 * Sets the minimum of uppercase characters.
2792 *
2793 * @param string $pwdPolicyMinUppercase minimum
2794 */
2795 public function setPwdPolicyMinUppercase(string $pwdPolicyMinUppercase): void {
2796 $this->pwdPolicyMinUppercase = $pwdPolicyMinUppercase;
2797 }
2798
2799 /**
2800 * Returns the minimum of numeric characters.
2801 *
2802 * @return string minimum
2803 */
2804 public function getPwdPolicyMinNumeric(): string {
2805 return $this->pwdPolicyMinNumeric;
2806 }
2807
2808 /**
2809 * Sets the minimum of numeric characters.
2810 *
2811 * @param string $pwdPolicyMinNumeric minimum
2812 */
2813 public function setPwdPolicyMinNumeric(string $pwdPolicyMinNumeric): void {
2814 $this->pwdPolicyMinNumeric = $pwdPolicyMinNumeric;
2815 }
2816
2817 /**
2818 * Returns the minimum of symbolic characters.
2819 *
2820 * @return string minimum
2821 */
2822 public function getPwdPolicyMinSymbolic(): string {
2823 return $this->pwdPolicyMinSymbolic;
2824 }
2825
2826 /**
2827 * Sets the minimum of symbolic characters.
2828 *
2829 * @param string $pwdPolicyMinSymbolic minimum
2830 */
2831 public function setPwdPolicyMinSymbolic(string $pwdPolicyMinSymbolic): void {
2832 $this->pwdPolicyMinSymbolic = $pwdPolicyMinSymbolic;
2833 }
2834
2835 }
2836
2837
2838 /**
2839 * This class manages config.cfg.
2840 *
2841 * @package configuration
2842 */
2843 class LAMCfgMain {
2844
2845 /** PHP error reporting setting as E_ALL & ~E_NOTICE */
2846 public const ERROR_REPORTING_DEFAULT = 'default';
2847 /** PHP error reporting setting from php.ini */
2848 public const ERROR_REPORTING_SYSTEM = 'system';
2849 /** PHP error reporting setting as E_ALL */
2850 public const ERROR_REPORTING_ALL = 'all';
2851
2852 /** send license warnings via email */
2853 public const LICENSE_WARNING_EMAIL = 'email';
2854 /** display license warnings on screen */
2855 public const LICENSE_WARNING_SCREEN = 'screen';
2856 /** send license warnings via email + display on screen */
2857 public const LICENSE_WARNING_ALL = 'all';
2858 /** no license warning */
2859 public const LICENSE_WARNING_NONE = 'none';
2860
2861 /** SSL encryption for mail sending */
2862 public const SMTP_SSL = 'SSL';
2863 /** TLS encryption for mail sending */
2864 public const SMTP_TLS = 'TLS';
2865 /** No encryption for mail sending */
2866 public const SMTP_NONE = 'NONE';
2867
2868 /** store configuration on local file system */
2869 public const DATABASE_FILE_SYSTEM = 'files';
2870 /** store configuration in MySQL database */
2871 public const DATABASE_MYSQL = 'mysql';
2872
2873 public const MAIL_ATTRIBUTE_DEFAULT = 'mail';
2874 public const MAIL_BACKUP_ATTRIBUTE_DEFAULT = 'passwordselfresetbackupmail';
2875
2876 public const SMS_ATTRIBUTES_DEFAULT = 'mobileTelephoneNumber;mobile';
2877
2878 /** Default profile */
2879 public ?string $default = null;
2880
2881 /** Password to change config.cfg */
2882 private ?string $password = null;
2883
2884 /** Time of inactivity before session times out (minutes) */
2885 public int $sessionTimeout = 30;
2886
2887 /** @var string hides detail messages for login errors */
2888 public string $hideLoginErrorDetails = 'false';
2889
2890 /** log level */
2891 public int $logLevel = LOG_NOTICE;
2892
2893 /** log destination ("SYSLOG":syslog, "/...":file, "NONE":none, "REMOTE":server:port) */
2894 public string $logDestination = "SYSLOG";
2895
2896 /** list of hosts which may access LAM */
2897 public string $allowedHosts = "";
2898
2899 /** list of hosts which may access LAM Pro self-service */
2900 public string $allowedHostsSelfService = '';
2901
2902 /** minimum length for passwords */
2903 public int $passwordMinLength = 0;
2904
2905 /** minimum uppercase characters */
2906 public int $passwordMinUpper = 0;
2907
2908 /** minimum lowercase characters */
2909 public int $passwordMinLower = 0;
2910
2911 /** minimum numeric characters */
2912 public int $passwordMinNumeric = 0;
2913
2914 /** minimum symbol characters */
2915 public int $passwordMinSymbol = 0;
2916
2917 /** minimum character classes (upper, lower, numeric, symbols) */
2918 public int $passwordMinClasses = 0;
2919
2920 /** number of password rules that must match (-1 = all) */
2921 public int $checkedRulesCount = -1;
2922
2923 /** password may contain the user name */
2924 public string $passwordMustNotContainUser = 'false';
2925
2926 /** password may contain more than 2 characters of user/first/last name */
2927 public string $passwordMustNotContain3Chars = 'false';
2928
2929 /** external URL for password checking (e.g. https://domain.com/url/{SHA1}) */
2930 public ?string $externalPwdCheckUrl = null;
2931
2932 /** path to config file */
2933 private string $conffile;
2934
2935 /** uploaded SSL certificate that is stored to disk on save() */
2936 private ?string $uploadedSSLCaCert = null;
2937
2938 /** SSL certificate should be deleted on save() */
2939 private bool $delSSLCaCert = false;
2940
2941 /** error reporting */
2942 public string $errorReporting = self::ERROR_REPORTING_DEFAULT;
2943
2944 /** license data */
2945 private string $license = '';
2946
2947 /** license warning email from address */
2948 public string $licenseEmailFrom = '';
2949
2950 /** license warning email TO address(es) separated by ";" */
2951 public string $licenseEmailTo = '';
2952
2953 /** the license warning email was last sent for this expiration date */
2954 public string $licenseEmailDateSent = '0';
2955
2956 /** type of license warning (email/screen/both/none) */
2957 public string $licenseWarningType = '';
2958
2959 /** mail server (server:port) */
2960 public string $mailServer = '';
2961
2962 /** mail server user */
2963 public string $mailUser = '';
2964
2965 /** mail server password */
2966 public string $mailPassword = '';
2967
2968 /**
2969 * @var string encryption type for SMTP connection
2970 */
2971 public string $mailEncryption = '';
2972
2973 /**
2974 * @var string attribute to use for user mail address
2975 */
2976 public string $mailAttribute = self::MAIL_ATTRIBUTE_DEFAULT;
2977
2978 /**
2979 * @var string attribute to use for user backup mail address
2980 */
2981 public string $mailBackupAttribute = self::MAIL_BACKUP_ATTRIBUTE_DEFAULT;
2982
2983 /** @var string SMS provider ID */
2984 public string $smsProvider = '';
2985
2986 /** @var string SMS API key */
2987 public string $smsApiKey = '';
2988
2989 /** @var string SMS token */
2990 public string $smsToken = '';
2991
2992 /** @var string SMS account ID */
2993 public string $smsAccountId = '';
2994
2995 /** @var string SMS region */
2996 public string $smsRegion = '';
2997
2998 /** @var string SMS from */
2999 public string $smsFrom = '';
3000
3001 /** @var string SMS subject line */
3002 public string $smsSubject = '';
3003
3004 /** @var string SMS number attributes */
3005 public string $smsAttributes = self::SMS_ATTRIBUTES_DEFAULT;
3006
3007 /** @var string default country prefix */
3008 public string $smsDefaultCountryPrefix = '';
3009
3010 /** database type */
3011 public string $configDatabaseType = self::DATABASE_FILE_SYSTEM;
3012
3013 /** database server name */
3014 public string $configDatabaseServer = '';
3015
3016 /** database port */
3017 public string $configDatabasePort = '';
3018
3019 /** database name */
3020 public string $configDatabaseName = '';
3021
3022 /** database user */
3023 public string $configDatabaseUser = '';
3024
3025 /** database password */
3026 public string $configDatabasePassword = '';
3027
3028 /** database options */
3029 public string $configDatabaseSSLCA = '';
3030
3031 /** database password */
3032 private string $moduleSettings = '';
3033
3034 /** @var string[] $settings list of data fields to save in config file */
3035 private array $settings = ["password", "default", "sessionTimeout", "hideLoginErrorDetails",
3036 "logLevel", "logDestination", "allowedHosts", "passwordMinLength",
3037 "passwordMinUpper", "passwordMinLower", "passwordMinNumeric",
3038 "passwordMinClasses", "passwordMinSymbol", 'checkedRulesCount',
3039 'passwordMustNotContainUser', 'passwordMustNotContain3Chars',
3040 'externalPwdCheckUrl',
3041 'errorReporting', 'allowedHostsSelfService',
3042 'license', 'licenseEmailFrom', 'licenseEmailTo', 'licenseWarningType', 'licenseEmailDateSent',
3043 'mailServer', 'mailUser', 'mailPassword', 'mailEncryption',
3044 'mailAttribute', 'mailBackupAttribute',
3045 'configDatabaseType',
3046 'configDatabaseServer', 'configDatabasePort', 'configDatabaseName', 'configDatabaseUser',
3047 'configDatabasePassword', 'configDatabaseSSLCA', 'moduleSettings',
3048 'smsProvider', 'smsApiKey', 'smsToken', 'smsAccountId', 'smsRegion', 'smsFrom', 'smsSubject', 'smsAttributes', 'smsDefaultCountryPrefix'
3049 ];
3050
3051 /** @var string[] $persistenceSettings persistence settings are always stored on local file system */
3052 private array $persistenceSettings = [
3053 'configDatabaseType', 'configDatabaseServer',
3054 'configDatabasePort', 'configDatabaseName', 'configDatabaseUser',
3055 'configDatabasePassword', 'configDatabaseSSLCA', 'license'
3056 ];
3057
3058 /**
3059 * Loads preferences from config file
3060 *
3061 * @param string|null $fileName file path for config file
3062 */
3063 public function __construct(?string $fileName = null) {
3064 $this->conffile = $fileName ?? __DIR__ . "/../config/config.cfg";
3065 try {
3066 $this->reload();
3067 }
3068 catch (LAMException $e) {
3069 syslog(LOG_ERR, 'Error loading main config: ' . $e->getTitle() . ' ' . $e->getMessage());
3070 }
3071 }
3072
3073 /**
3074 * Exports the configuration data.
3075 *
3076 * @param bool $skipPersistenceSettings do not include persistence settings
3077 * @return array<string, string|string[]|int|bool|null> config data
3078 */
3079 public function exportData(bool $skipPersistenceSettings = false): array {
3080 $data = [];
3081 foreach ($this->settings as $setting) {
3082 if ($skipPersistenceSettings && in_array($setting, $this->persistenceSettings)) {
3083 continue;
3084 }
3085 $data[$setting] = $this->$setting;
3086 }
3087 return $data;
3088 }
3089
3090 /**
3091 * Exports the configuration data, persistence settings only.
3092 *
3093 * @return array<string, string|string[]|int|bool|null> config data
3094 */
3095 private function exportPersistenceData(): array {
3096 $data = [];
3097 foreach ($this->settings as $setting) {
3098 if (!in_array($setting, $this->persistenceSettings)) {
3099 continue;
3100 }
3101 $data[$setting] = $this->$setting;
3102 }
3103 return $data;
3104 }
3105
3106 /**
3107 * Imports configuration data.
3108 *
3109 * @param array<string, string|string[]|int|bool|null|object> $data config data
3110 * @throws LAMException import error
3111 */
3112 public function importData(array $data): void {
3113 foreach ($data as $dataKey => $dataValue) {
3114 if (!in_array($dataKey, $this->settings)) {
3115 continue;
3116 }
3117 if (!(($dataValue === null) || is_array($dataValue) || is_string($dataValue) || is_int($dataValue) || is_bool($dataValue))) {
3118 throw new LAMException('Invalid import data type for ' . htmlspecialchars($dataKey) . ': ' . gettype($dataValue));
3119 }
3120 $this->$dataKey = $dataValue;
3121 }
3122 }
3123
3124 /**
3125 * Returns the content of the server certificates file
3126 *
3127 * @return null|string certificates
3128 */
3129 public function exportCertificates(): ?string {
3130 $fileName = $this->getSSLCaCertPath();
3131 if ($fileName === null) {
3132 return null;
3133 }
3134 $content = null;
3135 $handle = @fopen($fileName, "r");
3136 if ($handle) {
3137 $content = fread($handle, 10000000);
3138 fclose($handle);
3139 }
3140 return $content;
3141 }
3142
3143 /**
3144 * Imports the server certificates.
3145 *
3146 * @param null|string $certsContent certificates
3147 * @throws LAMException write to file failed
3148 */
3149 public function importCertificates(?string $certsContent): void {
3150 $fileName = $this->getSSLCaCertPath();
3151 if (empty($certsContent)) {
3152 unlink($fileName);
3153 return;
3154 }
3155 $fileName = $this->getInternalSSLCaCertFileName();
3156 $handle = @fopen($fileName, "wb");
3157 if ($handle) {
3158 fwrite($handle, $certsContent);
3159 fclose($handle);
3160 @chmod($fileName, 0600);
3161 }
3162 else {
3163 throw new LAMException(sprintf(_('Unable to write file %s.'), $fileName));
3164 }
3165 }
3166
3167 /**
3168 * Reloads preferences from config file config.cfg
3169 *
3170 * @throws LAMException error reading config
3171 */
3172 private function reload(): void {
3173 if (is_file($this->conffile)) {
3174 $file = @fopen($this->conffile, "r");
3175 if (!$file) {
3176 throw new LAMException(_('The config file is not readable.'));
3177 }
3178 $json = fread($file, 1000000);
3179 $data = json_decode($json, true);
3180 if ($data !== null) {
3181 $this->importData($data);
3182 }
3183 else {
3184 throw new LAMException(_('The config file is not readable.'));
3185 }
3186 fclose($file);
3187 }
3188 if ($this->configDatabaseType === self::DATABASE_MYSQL) {
3189 $this->loadFromDb();
3190 }
3191 }
3192
3193 /**
3194 * Loads the settings from the database.
3195 * Persistence settings are ignored as they must be on local file system.
3196 *
3197 * @throws LAMException error reading config
3198 */
3199 private function loadFromDb(): void {
3200 $configDb = new ConfigurationDatabase($this);
3201 try {
3202 $pdo = $configDb->getPdo();
3203 $result = $pdo->query("SELECT value FROM " . ConfigurationDatabase::TABLE_MAIN_CONFIG . ' WHERE name=\'config\'');
3204 if ($result === false) {
3205 syslog(LOG_ERR, 'Main configuration table query failed.');
3206 throw new LAMException(_('Unable to connect to configuration database.'));
3207 }
3208 $data = $result->fetchAll();
3209 if (empty($data)) {
3210 syslog(LOG_ERR, 'Main configuration table is empty.');
3211 throw new LAMException(_('Unable to connect to configuration database.'));
3212 }
3213 $jsonData = json_decode($data[0]['value'], true);
3214 foreach ($this->persistenceSettings as $persistenceSetting) {
3215 if (isset($jsonData[$persistenceSetting])) {
3216 unset($jsonData[$persistenceSetting]);
3217 }
3218 }
3219 $this->importData($jsonData);
3220 }
3221 catch (PDOException $e) {
3222 syslog(LOG_ERR, 'Unable to read main config: ' . $e->getMessage());
3223 throw new LAMException(_('Unable to connect to configuration database.'), '', $e);
3224 }
3225 catch (LAMException $e) {
3226 syslog(LOG_ERR, 'Unable to import main config: ' . $e->getMessage());
3227 throw new LAMException(_('Unable to connect to configuration database.'), '', $e);
3228 }
3229 }
3230
3231 /**
3232 * Saves the configuration to the persistence layer.
3233 * @throws LAMException error saving config
3234 */
3235 public function save(): void {
3236 if ($this->configDatabaseType === self::DATABASE_MYSQL) {
3237 $this->saveLocal(true);
3238 $this->saveDb();
3239 }
3240 else {
3241 $this->saveLocal(false);
3242 }
3243 // store SSL certificate
3244 if ($this->uploadedSSLCaCert !== null) {
3245 $sslPath = $this->getInternalSSLCaCertFileName();
3246 $file = @fopen($sslPath, "w");
3247 if ($file) {
3248 fwrite($file, $this->uploadedSSLCaCert);
3249 fclose($file);
3250 @chmod($sslPath, 0600);
3251 }
3252 else {
3253 throw new LAMException(_("Cannot write certificate file. Please check the permissions of config/serverCerts.pem."));
3254 }
3255 }
3256 // delete SSL certificate
3257 if ($this->delSSLCaCert) {
3258 $sslPath = $this->getInternalSSLCaCertFileName();
3259 $result = @unlink($sslPath);
3260 if (!$result) {
3261 throw new LAMException(_("Cannot write certificate file. Please check the permissions of config/serverCerts.pem."));
3262 }
3263 }
3264 }
3265
3266 /**
3267 * Saves the config data to the database.
3268 */
3269 private function saveDb(): void {
3270 $configDb = new ConfigurationDatabase($this);
3271 $pdo = $configDb->getPdo();
3272 $json = json_encode($this->exportData(true));
3273 $nameKey = 'config';
3274 $pdo->beginTransaction();
3275 // remove existing data
3276 $sql = 'delete from ' . ConfigurationDatabase::TABLE_MAIN_CONFIG . ' where name = "' . $nameKey . '";';
3277 $pdo->exec($sql);
3278 // new data
3279 $stmt = $pdo->prepare('insert into ' . ConfigurationDatabase::TABLE_MAIN_CONFIG . ' (name, value) VALUES (?, ?)');
3280 $stmt->execute([$nameKey, $json]);
3281 $pdo->commit();
3282 }
3283
3284 /**
3285 * Saves preferences to config file config.cfg
3286 *
3287 * @param bool $persistenceOnly store only persistence related data
3288 * @throws LAMException error saving config
3289 */
3290 public function saveLocal(bool $persistenceOnly): void {
3291 $data = $persistenceOnly ? $this->exportPersistenceData() : $this->exportData();
3292 $json = json_encode($data, JSON_PRETTY_PRINT);
3293
3294 $file = @fopen($this->conffile, "w");
3295 if ($file) {
3296 fwrite($file, $json);
3297 fclose($file);
3298 chmod($this->conffile, 0600);
3299 }
3300 else {
3301 throw new LAMException(_("Cannot open config file!") . " (" . $this->conffile . ")");
3302 }
3303 }
3304
3305 /**
3306 * Returns if the main config has a password set.
3307 *
3308 * @return bool password is set
3309 */
3310 public function hasPasswordSet(): bool {
3311 return ($this->password !== null) && ($this->password !== '');
3312 }
3313
3314 /**
3315 * Sets a new config password.
3316 *
3317 * @param string $password new password
3318 */
3319 public function setPassword(string $password): void {
3320 $this->password = $this->hashPassword($password, generateSalt(16));
3321 }
3322
3323 /**
3324 * Checks if the given password matches.
3325 *
3326 * @param string $password password
3327 * @return bool true, if password matches
3328 */
3329 public function checkPassword(string $password): bool {
3330 if (str_starts_with($this->password, "{SSHA}")) {
3331 $value = substr($this->password, strlen("{SSHA}"));
3332 $parts = explode(" ", $value);
3333 $salt = base64_decode($parts[1]);
3334 $hash = "{SSHA}" . base64_encode(hex2bin(sha1($password . $salt))) . " " . base64_encode($salt);
3335 return ($hash === $this->password);
3336 }
3337 elseif (str_starts_with($this->password, "{CRYPT-SHA512}")) {
3338 $value = substr($this->password, strlen("{CRYPT-SHA512}"));
3339 $parts = explode(" ", $value);
3340 $salt = base64_decode($parts[1]);
3341 return ($this->hashPassword($password, $salt) === $this->password);
3342 }
3343 else {
3344 // old nonhashed password
3345 return ($password === $this->password);
3346 }
3347 }
3348
3349 /**
3350 * Returns the hashed password.
3351 *
3352 * @param string $password password
3353 * @param string $salt salt
3354 * @return string hash value
3355 */
3356 private function hashPassword(string $password, string $salt): string {
3357 return "{CRYPT-SHA512}" . crypt($password, '$6$' . $salt) . " " . base64_encode($salt);
3358 }
3359
3360 /**
3361 * Returns if the configuration file is writable.
3362 *
3363 * @return boolean writable
3364 */
3365 public function isWritable(): bool {
3366 return is_writable($this->conffile);
3367 }
3368
3369 /**
3370 * Returns if the configuration file is existing.
3371 *
3372 * @return bool exists
3373 */
3374 public function isConfigFileExisting(): bool {
3375 return file_exists($this->conffile);
3376 }
3377
3378 /**
3379 * Tries to copy the config file from sample config.
3380 *
3381 * @return bool copied
3382 */
3383 public function installSampleConfig(): bool {
3384 $samplePath = __DIR__ . '/../config/config.cfg.sample';
3385 return file_exists($samplePath) && copy($samplePath, $this->conffile);
3386 }
3387
3388 /**
3389 * Returns the path to the SSL CA certificate file that overrides the system certificates.
3390 *
3391 * @return string|null path to certificate file or null if certificate is not overridden
3392 */
3393 public function getSSLCaCertPath(): ?string {
3394 $path = $this->getInternalSSLCaCertFileName();
3395 if (file_exists($path)) {
3396 return $path;
3397 }
3398 return null;
3399 }
3400
3401 /**
3402 * Returns the file name that will be used internally to store the CA file.
3403 *
3404 * @return String file name
3405 */
3406 private function getInternalSSLCaCertFileName() {
3407 return __DIR__ . '/../config/serverCerts.pem';
3408 }
3409
3410 /**
3411 * Uploads a new SSL CA cert.
3412 *
3413 * @param String $cert file content in DER/PEM format
3414 * @return true|string true if format is correct, error message if file is not accepted
3415 */
3416 public function uploadSSLCaCert($cert) {
3417 if (!str_contains($cert, '-----BEGIN CERTIFICATE-----')) {
3418 $pem = @chunk_split(@base64_encode($cert), 64, "\n");
3419 $cert = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n";
3420 }
3421 else {
3422 // remove any junk before first "-----BEGIN CERTIFICATE-----"
3423 $pos = strpos($cert, '-----BEGIN CERTIFICATE-----');
3424 $cert = substr($cert, $pos);
3425 }
3426 $pemData = @openssl_x509_parse($cert);
3427 if ($pemData === false) {
3428 return _('Please provide a file in DER or PEM format.');
3429 }
3430 $existingCerts = $this->getSSLCaCertificateContent();
3431 if (!empty($existingCerts)) {
3432 // merge with existing certificates
3433 $existingList = $this->splitSSLCaCertificateContent($existingCerts);
3434 $newList = $this->splitSSLCaCertificateContent($cert);
3435 $this->uploadedSSLCaCert = implode("\n", array_unique(array_merge($existingList, $newList)));
3436 }
3437 else {
3438 $this->uploadedSSLCaCert = $cert;
3439 }
3440 $this->delSSLCaCert = false;
3441 return true;
3442 }
3443
3444 /**
3445 * Returns the name of a temporary file in tmp that contains the SSL certificate.
3446 * The file contains either the stored data in serverCerts or the uploaded data.
3447 *
3448 * @return string|null file name or null if no certificate was set
3449 */
3450 public function getSSLCaCertTempFileName() {
3451 if ($this->delSSLCaCert) {
3452 return null;
3453 }
3454 // get certificate data
3455 $content = $this->getSSLCaCertificateContent();
3456 if ($content == null) {
3457 return null;
3458 }
3459 // write to temp file
3460 try {
3461 $temporaryFilesManager = new LamTemporaryFilesManager();
3462 $fileName = $temporaryFilesManager->registerTemporaryFile('.pem');
3463 $handle = $temporaryFilesManager->openTemporaryFileForWrite($fileName);
3464 fwrite($handle, $content);
3465 fclose($handle);
3466 return $fileName;
3467 }
3468 catch (LAMException $e) {
3469 logNewMessage(LOG_ERR, 'Unable to store SSL CA file: ' . $e->getTitle());
3470 return null;
3471 }
3472 }
3473
3474 /**
3475 * Marks a single or all SSL CA certificate files for deletion.
3476 * The changes take effect on save().
3477 *
3478 * @param int|null $index certificate index, null deletes all certificates (default: null)
3479 */
3480 public function deleteSSLCaCert(?int $index = null): void {
3481 if ($index == null) {
3482 // delete all
3483 $this->delSSLCaCert = true;
3484 return;
3485 }
3486 $content = $this->getSSLCaCertificateContent();
3487 $list = $this->splitSSLCaCertificateContent($content);
3488 unset($list[$index]);
3489 if (count($list) < 1) {
3490 $this->delSSLCaCert = true;
3491 $this->uploadedSSLCaCert = null;
3492 }
3493 else {
3494 $this->uploadedSSLCaCert = implode("\n", $list);
3495 }
3496 }
3497
3498 /**
3499 * Returns a list of all CA certificates.
3500 *
3501 * @return array<int, array<string, string[][]>> list of certificates as output of openssl_x509_parse()
3502 */
3503 public function getSSLCaCertificates(): array {
3504 if ($this->delSSLCaCert) {
3505 return [];
3506 }
3507 $content = $this->getSSLCaCertificateContent();
3508 if (empty($content)) {
3509 return [];
3510 }
3511 $list = $this->splitSSLCaCertificateContent($content);
3512 for ($i = 0; $i < count($list); $i++) {
3513 $list[$i] = @openssl_x509_parse($list[$i]);
3514 }
3515 return $list;
3516 }
3517
3518 /**
3519 * Returns the content of the certificate file or uploaded data.
3520 *
3521 * @return string|null null or certificate content
3522 */
3523 private function getSSLCaCertificateContent(): ?string {
3524 $content = null;
3525 if ($this->delSSLCaCert) {
3526 return null;
3527 }
3528 if ($this->uploadedSSLCaCert != null) {
3529 $content = $this->uploadedSSLCaCert;
3530 }
3531 elseif ($this->getSSLCaCertPath() != null) {
3532 $path = $this->getSSLCaCertPath();
3533 $handle = @fopen($path, "r");
3534 if ($handle) {
3535 $content = fread($handle, 10000000);
3536 fclose($handle);
3537 }
3538 }
3539 return $content;
3540 }
3541
3542 /**
3543 * Splits the certificate content into single PEM data chunks.
3544 *
3545 * @param string $content PEM file content
3546 * @return array<int, string> one element for each certificate chunk
3547 */
3548 private function splitSSLCaCertificateContent(string $content): array {
3549 if (empty($content)) {
3550 return [];
3551 }
3552 $content = str_replace("\n\n", "\n", $content);
3553 if (!(str_starts_with($content, '-----BEGIN CERTIFICATE-----'))) {
3554 return [];
3555 }
3556 $lines = explode("\n", $content);
3557 $list = [];
3558 $pos = -1;
3559 foreach ($lines as $line) {
3560 if (str_starts_with($line, '-----BEGIN CERTIFICATE-----')) {
3561 $pos++;
3562 }
3563 if (!isset($list[$pos])) {
3564 $list[$pos] = '';
3565 }
3566 $list[$pos] .= $line . "\n";
3567 }
3568 return $list;
3569 }
3570
3571 /**
3572 * Returns the license key as multiple lines.
3573 *
3574 * @return string[] license
3575 */
3576 public function getLicenseLines(): array {
3577 return explode(LAMConfig::LINE_SEPARATOR, $this->license);
3578 }
3579
3580 /**
3581 * Sets the license key as multiple lines.
3582 *
3583 * @param string[] $licenseLines license lines
3584 */
3585 public function setLicenseLines(array $licenseLines): void {
3586 $this->license = implode(LAMConfig::LINE_SEPARATOR, $licenseLines);
3587 }
3588
3589 /**
3590 * Returns the license warning type (screen/email/both/none).
3591 *
3592 * @return string warning type
3593 */
3594 public function getLicenseWarningType(): string {
3595 if (empty($this->licenseWarningType)) {
3596 return self::LICENSE_WARNING_SCREEN;
3597 }
3598 return $this->licenseWarningType;
3599 }
3600
3601 /**
3602 * Returns if the license warning should be shown on screen.
3603 *
3604 * @return bool show on screen
3605 */
3606 public function showLicenseWarningOnScreen(): bool {
3607 $type = $this->getLicenseWarningType();
3608 return ($type === self::LICENSE_WARNING_ALL) || ($type === self::LICENSE_WARNING_SCREEN);
3609 }
3610
3611 /**
3612 * Returns if the license warning should be sent via email.
3613 *
3614 * @return bool send via email
3615 */
3616 public function sendLicenseWarningByEmail(): bool {
3617 $type = $this->getLicenseWarningType();
3618 return ($type === self::LICENSE_WARNING_ALL) || ($type === self::LICENSE_WARNING_EMAIL);
3619 }
3620
3621 /**
3622 * Returns if the license warning was already sent.
3623 *
3624 * @param int $timeStamp time stamp
3625 */
3626 public function wasLicenseWarningSent(int $timeStamp): bool {
3627 if (empty($this->licenseEmailDateSent)) {
3628 return false;
3629 }
3630 return $timeStamp === intval($this->licenseEmailDateSent);
3631 }
3632
3633 /**
3634 * Hide error details for failed logins.
3635 *
3636 * @return bool hide details
3637 */
3638 public function isHideLoginErrorDetails(): bool {
3639 return $this->hideLoginErrorDetails === 'true';
3640 }
3641
3642 /**
3643 * Returns the mail attribute.
3644 *
3645 * @return string attribute name
3646 */
3647 public function getMailAttribute(): string {
3648 if (!empty($this->mailAttribute)) {
3649 return $this->mailAttribute;
3650 }
3651 return self::MAIL_ATTRIBUTE_DEFAULT;
3652 }
3653
3654 /**
3655 * Returns the mail backup attribute.
3656 *
3657 * @return string attribute name
3658 */
3659 public function getMailBackupAttribute(): string {
3660 if (!empty($this->mailBackupAttribute)) {
3661 return $this->mailBackupAttribute;
3662 }
3663 return self::MAIL_BACKUP_ATTRIBUTE_DEFAULT;
3664 }
3665
3666 /**
3667 * Returns the SMS attributes.
3668 *
3669 * @return string[] attribute names
3670 */
3671 public function getSmsAttributes(): array {
3672 if (!empty($this->smsAttributes)) {
3673 return preg_split('/;[ ]*/', $this->smsAttributes);
3674 }
3675 return preg_split('/;[ ]*/', self::SMS_ATTRIBUTES_DEFAULT);
3676 }
3677
3678 /**
3679 * Returns a list of module settings.
3680 *
3681 * @return array<string, array<string, string>> module settings
3682 */
3683 public function getModuleSettings(): array {
3684 if (empty($this->moduleSettings)) {
3685 return [];
3686 }
3687 return json_decode(base64_decode($this->moduleSettings), true);
3688 }
3689
3690 /**
3691 * Sets the module settings.
3692 *
3693 * @param array<string, array<string, string>> $settings module settings
3694 */
3695 public function setModuleSettings(array $settings): void {
3696 $this->moduleSettings = base64_encode(json_encode($settings));
3697 }
3698
3699 /**
3700 * Checks if the log filename is valid.
3701 *
3702 * @param string $path path
3703 * @return bool is valid
3704 */
3705 public static function isValidLogFilename(string $path): bool {
3706 return !empty($path)
3707 && preg_match("/^[a-z0-9\\/._-]+$/i", $path)
3708 && (str_ends_with($path, '.log') || str_ends_with($path, '.txt'))
3709 && !str_contains($path, '..')
3710 && !str_starts_with($path, './');
3711 }
3712
3713 }