Debian Codegraph @

templates/config/mainmanage.php

raw
1 <?php
2 namespace LAM\CONFIG;
3
4 use Exception;
5 use htmlJavaScript;
6 use htmlResponsiveTable;
7 use LAM\LOGIN\WEBAUTHN\WebauthnManager;
8 use LAM\PERSISTENCE\ConfigurationDatabase;
9 use LAM\PLUGINS\SMS\SmsService;
10 use LAMCfgMain;
11 use htmlTable;
12 use htmlTitle;
13 use htmlStatusMessage;
14 use htmlSubTitle;
15 use htmlSpacer;
16 use htmlOutputText;
17 use htmlLink;
18 use htmlGroup;
19 use htmlButton;
20 use htmlHelpLink;
21 use htmlInputField;
22 use htmlInputFileUpload;
23 use DateTime;
24 use DateTimeZone;
25 use htmlResponsiveRow;
26 use htmlResponsiveInputTextarea;
27 use htmlResponsiveSelect;
28 use htmlResponsiveInputCheckbox;
29 use htmlResponsiveInputField;
30 use htmlDiv;
31 use htmlHiddenInput;
32 use LAMConfig;
33 use LAMException;
34 use LamTemporaryFilesManager;
35 use PDO;
36
37 /*
38
39 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
40 Copyright (C) 2003 - 2026 Roland Gruber
41
42 This program is free software; you can redistribute it and/or modify
43 it under the terms of the GNU General Public License as published by
44 the Free Software Foundation; either version 2 of the License, or
45 (at your option) any later version.
46
47 This program is distributed in the hope that it will be useful,
48 but WITHOUT ANY WARRANTY; without even the implied warranty of
49 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
50 GNU General Public License for more details.
51
52 You should have received a copy of the GNU General Public License
53 along with this program; if not, write to the Free Software
54 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
55
56 */
57
58
59 /**
60 * Manages the main configuration options.
61 *
62 * @package configuration
63 * @author Roland Gruber
64 */
65
66
67 /** Access to config functions */
68 include_once(__DIR__ . '/../../lib/config.inc');
69 /** Used to print status messages */
70 include_once(__DIR__ . '/../../lib/status.inc');
71 /** LAM Pro */
72 include_once(__DIR__ . '/../../lib/selfService.inc');
73 /** SMS */
74 include_once __DIR__ . '/../../lib/plugins/sms/SmsService.inc';
75
76 // start session
77 if (isFileBasedSession()) {
78 session_save_path("../../sess");
79 }
80 lam_start_session();
81
82 setlanguage();
83
84 if (!isset($_SESSION['cfgMain'])) {
85 $cfg = new LAMCfgMain();
86 $_SESSION['cfgMain'] = $cfg;
87 }
88 $cfg = &$_SESSION['cfgMain'];
89 if (!($cfg instanceof LAMCfgMain)) {
90 die();
91 }
92
93 // check if user is logged in
94 if (!isset($_SESSION["mainconf_password"]) || (!$cfg->checkPassword($_SESSION["mainconf_password"]))) {
95 require(__DIR__ . '/mainlogin.php');
96 exit();
97 }
98
99 if (isset($_POST['cancel'])) {
100 // back to login
101 metaRefresh('../login.php');
102 exit();
103 }
104
105 if (isset($_SESSION['header'])) {
106 echo $_SESSION['header'];
107 }
108 printHeaderContents(_("Edit general settings"), '../..');
109 ?>
110 </head>
111 <body>
112 <div id="lam-topnav" class="lam-header">
113 <div class="lam-header-left lam-menu-stay">
114 <a href="https://www.ldap-account-manager.org/" target="new_window">
115 <img class="align-middle" width="24" height="24" alt="help" src="../../graphics/logo.svg">
116 <span class="hide-on-mobile">
117 <?php
118 echo getLAMVersionText();
119 ?>
120 </span>
121 </a>
122 </div>
123 <?php
124 if (is_dir(__DIR__ . '/../../docs/manual')) {
125 ?>
126 <a class="lam-header-right lam-menu-icon hide-on-tablet" href="javascript:void(0);" class="icon"
127 onclick="window.lam.topmenu.toggle();">
128 <img class="align-middle" width="16" height="16" alt="menu" src="../../graphics/menu.svg">
129 <span class="padding0">&nbsp;</span>
130 </a>
131 <a class="lam-header-right lam-menu-entry" target="_blank" href="../../docs/manual/index.html">
132 <span class="padding0"><?php echo _("Help") ?></span>
133 </a>
134 <?php
135 }
136 ?>
137 </div>
138 <br>
139 <?php
140 // include all JavaScript files
141 printJsIncludes('../..');
142
143 $errors = [];
144 $messages = [];
145 // check if submit button was pressed
146 if (isset($_POST['submitFormData'])) {
147 if (extension_loaded('PDO')) {
148 // set database
149 $cfg->configDatabaseType = $_POST['configDatabaseType'];
150 $cfg->configDatabaseServer = $_POST['configDatabaseServer'];
151 $cfg->configDatabaseSSLCA = $_POST['configDatabaseSSLCA'];
152 $cfg->configDatabasePort = $_POST['configDatabasePort'];
153 $cfg->configDatabaseName = $_POST['configDatabaseName'];
154 $cfg->configDatabaseUser = $_POST['configDatabaseUser'];
155 $cfg->configDatabasePassword = $_POST['configDatabasePassword'];
156 if ($cfg->configDatabaseType === LAMCfgMain::DATABASE_MYSQL) {
157 $mySqlConfigOk = true;
158 if (empty($cfg->configDatabaseServer) || !get_preg($cfg->configDatabaseServer, 'hostname')) {
159 $errors[] = _('Please enter a valid database host name.');
160 $mySqlConfigOk = false;
161 }
162 if (empty($cfg->configDatabaseName)) {
163 $errors[] = _('Please enter a valid database name.');
164 $mySqlConfigOk = false;
165 }
166 if (empty($cfg->configDatabaseUser)) {
167 $errors[] = _('Please enter a valid database user.');
168 $mySqlConfigOk = false;
169 }
170 if (empty($cfg->configDatabasePassword)) {
171 $errors[] = _('Please enter a valid database password.');
172 $mySqlConfigOk = false;
173 }
174 if ($mySqlConfigOk) {
175 try {
176 $configurationDatabase = new ConfigurationDatabase($cfg);
177 $configurationDatabase->checkConnection();
178 }
179 catch (Exception $e) {
180 logNewMessage(LOG_ERR, 'Unable to connect to configuration database: ' . $e->getMessage());
181 $errors[] = _('Unable to connect to configuration database.');
182 }
183 }
184 }
185 }
186 // set master password
187 if (!empty($_POST['masterpassword'])) {
188 if (($_POST['masterpassword'] !== $_POST['masterpassword2'])) {
189 $errors[] = _("Master passwords are different.");
190 }
191 elseif (!isValidConfigurationPassword($_POST['masterpassword'])) {
192 $errors[] = _('Please enter at least 8 characters including letters, a number and a symbol.');
193 }
194 else {
195 $cfg->setPassword($_POST['masterpassword']);
196 $msg = _("New master password set successfully.");
197 unset($_SESSION["mainconf_password"]);
198 }
199 }
200 // set license
201 if (isLAMProVersion()) {
202 $licenseLines = explode("\n", $_POST['license']);
203 $licenseLines = array_map(trim(...), $licenseLines);
204 $cfg->setLicenseLines($licenseLines);
205 $cfg->licenseWarningType = $_POST['licenseWarningType'];
206 $cfg->licenseEmailFrom = $_POST['licenseEmailFrom'];
207 $cfg->licenseEmailTo = $_POST['licenseEmailTo'];
208 if ((($cfg->licenseWarningType === LAMCfgMain::LICENSE_WARNING_EMAIL) || ($cfg->licenseWarningType === LAMCfgMain::LICENSE_WARNING_ALL))
209 && !get_preg($cfg->licenseEmailFrom, 'email')) {
210 $errors[] = _('Licence') . ': ' . _('From address') . ' - ' . _('Please enter a valid email address!');
211 }
212 if (($cfg->licenseWarningType === LAMCfgMain::LICENSE_WARNING_EMAIL) || ($cfg->licenseWarningType === LAMCfgMain::LICENSE_WARNING_ALL)) {
213 $toEmails = preg_split('/;[ ]*/', $cfg->licenseEmailTo);
214 if ($toEmails !== false) {
215 foreach ($toEmails as $toEmail) {
216 if (!get_preg($toEmail, 'email')) {
217 $errors[] = _('Licence') . ': ' . _('To address') . ' - ' . _('Please enter a valid email address!');
218 break;
219 }
220 }
221 }
222 }
223 }
224 // set session timeout
225 $cfg->sessionTimeout = intval($_POST['sessionTimeout']);
226 // set hide login error details
227 $cfg->hideLoginErrorDetails = (isset($_POST['hideLoginErrorDetails']) && ($_POST['hideLoginErrorDetails'] === 'on')) ? 'true' : 'false';
228 // set allowed hosts
229 if (isset($_POST['allowedHosts'])) {
230 $allowedHosts = $_POST['allowedHosts'];
231 $allowedHostsList = explode("\n", $allowedHosts);
232 $allowedHostsListNew = [];
233 foreach ($allowedHostsList as $allowedHostEntry) {
234 $allowedHostEntry = trim($allowedHostEntry);
235 // ignore empty lines
236 if ($allowedHostEntry === '') {
237 continue;
238 }
239 // check each line
240 $ipRegex = '/^[0-9a-f\\.:\\*]+$/i';
241 if (!preg_match($ipRegex, $allowedHostEntry) || (strlen($allowedHostEntry) > 45)) {
242 $errors[] = sprintf(_("The IP address %s is invalid!"), htmlspecialchars(str_replace('%', '%%', $allowedHostEntry)));
243 }
244 $allowedHostsListNew[] = $allowedHostEntry;
245 }
246 $allowedHostsList = array_unique($allowedHostsListNew);
247 $allowedHosts = implode(",", $allowedHostsList);
248 }
249 else {
250 $allowedHosts = "";
251 }
252 $cfg->allowedHosts = $allowedHosts;
253 // set allowed hosts for self-service
254 if (isLAMProVersion()) {
255 if (isset($_POST['allowedHostsSelfService'])) {
256 $allowedHostsSelfService = $_POST['allowedHostsSelfService'];
257 $allowedHostsSelfServiceList = explode("\r\n", $allowedHostsSelfService);
258 $allowedHostsSelfServiceListNew = [];
259 foreach ($allowedHostsSelfServiceList as $allowedHostsSelfServiceEntry) {
260 $allowedHostsSelfServiceEntry = trim($allowedHostsSelfServiceEntry);
261 // ignore empty lines
262 if ($allowedHostsSelfServiceEntry === '') {
263 continue;
264 }
265 // check each line
266 $ipRegex = '/^[0-9a-f\\.:\\*]+$/i';
267 if (!preg_match($ipRegex, $allowedHostsSelfServiceEntry) || (strlen($allowedHostsSelfServiceEntry) > 45)) {
268 $errors[] = sprintf(_("The IP address %s is invalid!"), htmlspecialchars(str_replace('%', '%%', $allowedHostsSelfServiceEntry)));
269 }
270 $allowedHostsSelfServiceListNew[] = $allowedHostsSelfServiceEntry;
271 }
272 $allowedHostsSelfServiceList = array_unique($allowedHostsSelfServiceListNew);
273 $allowedHostsSelfService = implode(",", $allowedHostsSelfServiceList);
274 }
275 else {
276 $allowedHostsSelfService = "";
277 }
278 $cfg->allowedHostsSelfService = $allowedHostsSelfService;
279 }
280 // set log level
281 $cfg->logLevel = intval($_POST['logLevel']);
282 // set log destination
283 if ($_POST['logDestination'] == "none") {
284 $cfg->logDestination = "NONE";
285 }
286 elseif ($_POST['logDestination'] == "syslog") {
287 $cfg->logDestination = "SYSLOG";
288 }
289 elseif ($_POST['logDestination'] == "remote") {
290 $cfg->logDestination = "REMOTE:" . $_POST['logRemote'];
291 $remoteParts = explode(':', $_POST['logRemote']);
292 if ((count($remoteParts) !== 2) || !get_preg($remoteParts[0], 'DNSname') || !get_preg($remoteParts[1], 'digit')) {
293 $errors[] = _("Please enter a valid remote server in format \"server:port\".");
294 }
295 }
296 else {
297 $isValidLogFile = isset($_POST['logFile']) && LAMCfgMain::isValidLogFilename($_POST['logFile']);
298 $blockedPrefixes = ['/usr', '/etc', '/dev', '/boot', '/lib', '/proc', '/root', '/run', '/sys', '/snap'];
299 if (!empty($_SERVER['DOCUMENT_ROOT'])) {
300 $blockedPrefixes[] = $_SERVER['DOCUMENT_ROOT'];
301 }
302 foreach ($blockedPrefixes as $blockedPrefix) {
303 if (!$isValidLogFile) {
304 break;
305 }
306 if (str_starts_with($_POST['logFile'], $blockedPrefix)) {
307 $isValidLogFile = false;
308 }
309 }
310 if ($isValidLogFile) {
311 $cfg->logDestination = $_POST['logFile'];
312 }
313 else {
314 $errors[] = _("The log file is empty or contains invalid characters! Valid characters are: a-z, A-Z, 0-9, /, ., _ and -. The file must end with '.log' or '.txt'.");
315 }
316 }
317 // password policies
318 $cfg->passwordMinLength = intval($_POST['passwordMinLength']);
319 $cfg->passwordMinLower = intval($_POST['passwordMinLower']);
320 $cfg->passwordMinUpper = intval($_POST['passwordMinUpper']);
321 $cfg->passwordMinNumeric = intval($_POST['passwordMinNumeric']);
322 $cfg->passwordMinSymbol = intval($_POST['passwordMinSymbol']);
323 $cfg->passwordMinClasses = intval($_POST['passwordMinClasses']);
324 $cfg->checkedRulesCount = intval($_POST['passwordRulesCount']);
325 $cfg->passwordMustNotContain3Chars = isset($_POST['passwordMustNotContain3Chars']) && ($_POST['passwordMustNotContain3Chars'] == 'on') ? 'true' : 'false';
326 $cfg->passwordMustNotContainUser = isset($_POST['passwordMustNotContainUser']) && ($_POST['passwordMustNotContainUser'] == 'on') ? 'true' : 'false';
327 if (function_exists('curl_init')) {
328 $cfg->externalPwdCheckUrl = $_POST['externalPwdCheckUrl'];
329 if (!empty($cfg->externalPwdCheckUrl) && (!str_contains($cfg->externalPwdCheckUrl, '{SHA1PREFIX}'))) {
330 $errors[] = _('The URL for the external password check is invalid.');
331 }
332 }
333 if (isset($_POST['sslCaCertUpload'])) {
334 if (!isset($_FILES['sslCaCert']) || ($_FILES['sslCaCert']['size'] == 0)) {
335 $errors[] = _('No file selected.');
336 }
337 else {
338 $handle = fopen($_FILES['sslCaCert']['tmp_name'], "r");
339 if ($handle === false) {
340 $errors[] = _('Unable to create temporary file.');
341 }
342 else {
343 $data = fread($handle, 10_000_000);
344 if ($data === false) {
345 $errors[] = _('Unable to create temporary file.');
346 }
347 else {
348 fclose($handle);
349 $sslReturn = $cfg->uploadSSLCaCert($data);
350 if ($sslReturn !== true) {
351 $errors[] = $sslReturn;
352 }
353 else {
354 $messages[] = _('You might need to restart your webserver for changes to take effect.');
355 }
356 }
357 }
358 }
359 }
360 if (isset($_POST['sslCaCertDelete'])) {
361 $cfg->deleteSSLCaCert();
362 $messages[] = _('You might need to restart your webserver for changes to take effect.');
363 }
364 if (isset($_POST['sslCaCertImport'])) {
365 $matches = [];
366 if (preg_match('/^ldaps:\/\/([a-zA-Z0-9_.-]+)(:(\d+))?$/', $_POST['serverurl'], $matches)) {
367 $port = '636';
368 if (!empty($matches[3])) {
369 $port = $matches[3];
370 }
371 $pemResult = getLDAPSSLCertificate($matches[1], $port);
372 if ($pemResult !== false) {
373 $messages[] = _('Imported certificate from server.');
374 $messages[] = _('You might need to restart your webserver for changes to take effect.');
375 $cfg->uploadSSLCaCert($pemResult);
376 }
377 else {
378 $errors[] = _('Unable to import server certificate. Please use the upload function.');
379 }
380 }
381 else {
382 $errors[] = _('Invalid server name. Please enter "server" or "server:port".');
383 }
384 }
385 foreach (array_keys($_POST) as $key) {
386 if (str_starts_with($key, 'deleteCert_')) {
387 $index = (int) substr($key, strlen('deleteCert_'));
388 $cfg->deleteSSLCaCert($index);
389 }
390 }
391 // mail settings
392 if (isLAMProVersion()) {
393 $cfg->mailUser = $_POST['mailUser'];
394 $cfg->mailPassword = $_POST['mailPassword'];
395 $cfg->mailEncryption = $_POST['mailEncryption'];
396 $cfg->mailServer = $_POST['mailServer'];
397 if (!empty($cfg->mailServer) && !get_preg($cfg->mailServer, 'hostAndPort')) {
398 $errors[] = _('Please enter the mail server with host name and port.');
399 }
400 $mailAttribute = strtolower($_POST['mailAttribute']);
401 $mailBackupAttribute = strtolower($_POST['mailBackupAttribute']);
402 if (empty($mailAttribute)) {
403 $cfg->mailAttribute = LAMCfgMain::MAIL_ATTRIBUTE_DEFAULT;
404 }
405 elseif (preg_match('/^[a-z0-9_-]+$/', $mailAttribute)) {
406 $cfg->mailAttribute = $mailAttribute;
407 }
408 else {
409 $errors[] = _('The mail attributes are invalid.');
410 }
411 if (empty($mailBackupAttribute)) {
412 $cfg->mailBackupAttribute = LAMCfgMain::MAIL_BACKUP_ATTRIBUTE_DEFAULT;
413 }
414 elseif (preg_match('/^[a-z0-9_-]+$/', $mailBackupAttribute)) {
415 $cfg->mailBackupAttribute = $mailBackupAttribute;
416 }
417 else {
418 $errors[] = _('The mail attributes are invalid.');
419 }
420 }
421 // SMS settings
422 if (isLAMProVersion()) {
423 $cfg->smsProvider = $_POST['smsProvider'];
424 $cfg->smsAttributes = $_POST['smsAttributes'];
425 $cfg->smsApiKey = $_POST['smsApiKey'];
426 $cfg->smsToken = $_POST['smsApiToken'];
427 $cfg->smsAccountId = $_POST['smsAccountId'];
428 $cfg->smsRegion = $_POST['smsRegion'];
429 $cfg->smsFrom = $_POST['smsFrom'];
430 $cfg->smsSubject = $_POST['smsSubject'];
431 $cfg->smsDefaultCountryPrefix = $_POST['smsDefaultCountryPrefix'];
432 }
433 $cfg->errorReporting = $_POST['errorReporting'];
434 // module settings
435 $allModules = getAllModules();
436 $moduleSettings = $cfg->getModuleSettings();
437 foreach ($allModules as $module) {
438 $module->checkGlobalConfigOptions($moduleSettings, $messages, $errors);
439 }
440 $cfg->setModuleSettings($moduleSettings);
441 // save settings
442 if (isset($_POST['submit']) && empty($errors)) {
443 try {
444 $cfg->save();
445 $scriptTag = new htmlJavaScript('window.lam.dialog.showSuccessMessageAndRedirect("' . _("Your settings were successfully saved.") . '", "", "' . _('Ok') . '", "../login.php")');
446 parseHtml(null, $scriptTag, [], false, null);
447 echo '</body></html>';
448 exit();
449 }
450 catch (LAMException $e) {
451 $errors[] = $e->getTitle();
452 }
453 }
454 }
455
456 ?>
457 <form class="text-center" enctype="multipart/form-data" action="mainmanage.php" method="post" novalidate="novalidate">
458
459 <?php
460 $row = new htmlResponsiveRow();
461 $row->add(new htmlTitle(_('General settings')));
462
463 // print messages
464 foreach ($errors as $error) {
465 $row->add(new htmlStatusMessage("ERROR", $error));
466 }
467 foreach ($messages as $message) {
468 $row->add(new htmlStatusMessage("INFO", $message));
469 }
470
471 // check if config file is writable
472 if (!$cfg->isWritable()) {
473 $row->add(new htmlStatusMessage('WARN', _('The config file is not writable.'), _('Your changes cannot be saved until you make the file writable for the webserver user.')));
474 }
475
476 // database
477 if (extension_loaded('PDO')) {
478 $row->add(new htmlSubTitle(_('Configuration storage')));
479 $storageProviders = [
480 _('Local file system') => LAMCfgMain::DATABASE_FILE_SYSTEM
481 ];
482 if (in_array('mysql', PDO::getAvailableDrivers())) {
483 $storageProviders['MySQL'] = LAMCfgMain::DATABASE_MYSQL;
484 }
485 $storageProviderSelect = new htmlResponsiveSelect('configDatabaseType', $storageProviders, [$cfg->configDatabaseType], _('Database type'), '293');
486 $storageProviderSelect->setHasDescriptiveElements(true);
487 $dbRowsToShow = [
488 LAMCfgMain::DATABASE_FILE_SYSTEM => [],
489 LAMCfgMain::DATABASE_MYSQL => ['configDatabaseServer', 'configDatabasePort', 'configDatabaseName', 'configDatabaseUser', 'configDatabasePassword', 'configDatabaseSSLCA']
490 ];
491 $storageProviderSelect->setTableRowsToShow($dbRowsToShow);
492 $dbRowsToHide = [
493 LAMCfgMain::DATABASE_FILE_SYSTEM => ['configDatabaseServer', 'configDatabasePort', 'configDatabaseName', 'configDatabaseUser', 'configDatabasePassword', 'configDatabaseSSLCA'],
494 LAMCfgMain::DATABASE_MYSQL => []
495 ];
496 $storageProviderSelect->setTableRowsToHide($dbRowsToHide);
497 $row->add($storageProviderSelect);
498 $dbHost = new htmlResponsiveInputField(_('Database host'), 'configDatabaseServer', $cfg->configDatabaseServer, '273');
499 $dbHost->setRequired(true);
500 $row->add($dbHost);
501 $dbPort = new htmlResponsiveInputField(_('Database port'), 'configDatabasePort', $cfg->configDatabasePort, '274');
502 $row->add($dbPort);
503 $dbHostSSLCA = new htmlResponsiveInputField(_('CA certificate path'), 'configDatabaseSSLCA', $cfg->configDatabaseSSLCA, '277');
504 $row->add($dbHostSSLCA);
505 $dbName = new htmlResponsiveInputField(_('Database name'), 'configDatabaseName', $cfg->configDatabaseName, '276');
506 $dbName->setRequired(true);
507 $row->add($dbName);
508 $dbUser = new htmlResponsiveInputField(_('Database user'), 'configDatabaseUser', $cfg->configDatabaseUser, '275');
509 $dbUser->setRequired(true);
510 $row->add($dbUser);
511 $dbPassword = new htmlResponsiveInputField(_('Database password'), 'configDatabasePassword', deobfuscateText($cfg->configDatabasePassword), '275');
512 $dbPassword->setRequired(true);
513 $dbPassword->setIsPassword(true);
514 $row->add($dbPassword);
515 }
516
517 // license
518 if (isLAMProVersion()) {
519 $row->add(new htmlSubTitle(_('Licence')));
520 $row->add(new htmlResponsiveInputTextarea('license', implode("\n", $cfg->getLicenseLines()), 30, 10, _('Licence'), '287'));
521 $warningOptions = [
522 _('Screen') => LAMCfgMain::LICENSE_WARNING_SCREEN,
523 _('Email') => LAMCfgMain::LICENSE_WARNING_EMAIL,
524 _('Both') => LAMCfgMain::LICENSE_WARNING_ALL,
525 _('None') => LAMCfgMain::LICENSE_WARNING_NONE
526 ];
527 $warningTypeSelect = new htmlResponsiveSelect('licenseWarningType', $warningOptions, [$cfg->getLicenseWarningType()], _('Expiration warning'), '288');
528 $warningTypeSelect->setHasDescriptiveElements(true);
529 $warningTypeSelect->setSortElements(false);
530 $warningTypeSelect->setTableRowsToHide([
531 LAMCfgMain::LICENSE_WARNING_SCREEN => ['licenseEmailFrom', 'licenseEmailTo'],
532 LAMCfgMain::LICENSE_WARNING_NONE => ['licenseEmailFrom', 'licenseEmailTo']
533 ]);
534 $warningTypeSelect->setTableRowsToShow([
535 LAMCfgMain::LICENSE_WARNING_EMAIL => ['licenseEmailFrom', 'licenseEmailTo'],
536 LAMCfgMain::LICENSE_WARNING_ALL => ['licenseEmailFrom', 'licenseEmailTo']
537 ]);
538 $row->add($warningTypeSelect);
539 $licenseFrom = new htmlResponsiveInputField(_('From address'), 'licenseEmailFrom', $cfg->licenseEmailFrom, '289');
540 $licenseFrom->setRequired(true);
541 $row->add($licenseFrom);
542 $licenseTo = new htmlResponsiveInputField(_('To address'), 'licenseEmailTo', $cfg->licenseEmailTo, '290');
543 $licenseTo->setRequired(true);
544 $row->add($licenseTo);
545
546 $row->add(new htmlSpacer(null, '1rem'));
547 }
548
549 // security settings
550 $row->add(new htmlSubTitle(_("Security settings")));
551 $options = ['5', '10', '20', '30', '60', '90', '120', '240'];
552 $row->add(new htmlResponsiveSelect('sessionTimeout', $options, [(string) $cfg->sessionTimeout], _("Session timeout"), '238'));
553 $hideLoginErrorDetails = ($cfg->hideLoginErrorDetails === 'true');
554 $row->add(new htmlResponsiveInputCheckbox('hideLoginErrorDetails', $hideLoginErrorDetails, _('Hide LDAP details on failed login'), '257'));
555 $row->add(new htmlResponsiveInputTextarea('allowedHosts', implode("\n", explode(",", $cfg->allowedHosts)), 30, 7, _("Allowed hosts"), '241'));
556 if (isLAMProVersion()) {
557 $row->add(new htmlResponsiveInputTextarea('allowedHostsSelfService', implode("\n", explode(",", $cfg->allowedHostsSelfService)), 30, 7, _("Allowed hosts (self-service)"), '241'));
558 }
559 // SSL certificate
560 $row->addVerticalSpacer('1rem');
561 $row->addLabel(new htmlOutputText(_('SSL certificates')));
562 $sslMethod = _('use system certificates');
563 $sslFileName = $cfg->getSSLCaCertTempFileName();
564 if ($sslFileName != null) {
565 $sslMethod = _('use custom CA certificates');
566 }
567 $sslDelSaveGroup = new htmlGroup();
568 $sslDelSaveGroup->addElement(new htmlOutputText($sslMethod));
569 $sslDelSaveGroup->addElement(new htmlSpacer('5px', null));
570 // delete+download button
571 if ($sslFileName != null) {
572 $temporaryFilesManager = new LamTemporaryFilesManager();
573 $sslDownloadBtn = new htmlLink('', $temporaryFilesManager->getDownloadLink($sslFileName), '../../graphics/save.svg');
574 $sslDownloadBtn->setTargetWindow('_blank');
575 $sslDownloadBtn->setTitle(_('Download CA certificates'));
576 $sslDownloadBtn->setCSSClasses(['icon']);
577 $sslDelSaveGroup->addElement($sslDownloadBtn);
578 $sslDeleteBtn = new htmlButton('sslCaCertDelete', 'del.svg', true);
579 $sslDeleteBtn->setTitle(_('Delete all CA certificates'));
580 $sslDelSaveGroup->addElement($sslDeleteBtn);
581 }
582 $sslDelSaveGroup->addElement(new htmlHelpLink('204'));
583 $row->addField($sslDelSaveGroup);
584 $row->addLabel(new htmlInputFileUpload('sslCaCert'));
585 $sslUploadBtn = new htmlButton('sslCaCertUpload', _('Upload'));
586 $sslUploadBtn->setTitle(_('Upload CA certificate in DER/PEM format.'));
587 $row->addField($sslUploadBtn);
588 if (function_exists('stream_socket_client') && function_exists('stream_context_get_params')) {
589 $sslImportServerUrl = empty($_POST['serverurl']) ? 'ldaps://' : (string) $_POST['serverurl'];
590 $serverUrlUpload = new htmlInputField('serverurl', $sslImportServerUrl);
591 $row->addLabel($serverUrlUpload);
592 $sslImportBtn = new htmlButton('sslCaCertImport', _('Import from server'));
593 $sslImportBtn->setTitle(_('Imports the certificate directly from your LDAP server.'));
594 $row->addField($sslImportBtn);
595 }
596
597 $sslCerts = $cfg->getSSLCaCertificates();
598 if (count($sslCerts) > 0) {
599 $certsTitles = [_('Common name'), _('Valid to'), _('Serial number'), _('Delete')];
600 $certsData = [];
601 foreach ($sslCerts as $i => $sslCert) {
602 $serial = $sslCert['serialNumber'] ?? '';
603 $validTo = $sslCert['validTo_time_t'] ?? '';
604 if (get_preg($validTo, 'digit')) {
605 $date = DateTime::createFromFormat('U', $validTo, new DateTimeZone('UTC'));
606 if ($date !== false) {
607 $validTo = $date->format('Y-m-d');
608 }
609 }
610 $cn = $sslCert['subject']['CN'] ?? '';
611 $delBtn = new htmlButton('deleteCert_' . $i, 'del.svg', true);
612 $certsData[] = [
613 new htmlOutputText($cn),
614 new htmlDiv(null, new htmlOutputText($validTo), ['nowrap']),
615 new htmlOutputText($serial),
616 $delBtn
617 ];
618 }
619 $certsTable = new htmlResponsiveTable($certsTitles, $certsData);
620 $certsTable->setCSSClasses(['text-left']);
621 $row->add($certsTable);
622 }
623
624 // password policy
625 $row->add(new htmlSubTitle(_("Password policy")));
626 $optionsPwdLength = [];
627 for ($i = 0; $i <= 50; $i++) {
628 $optionsPwdLength[] = (string) $i;
629 }
630 $options4 = ['0', '1', '2', '3', '4'];
631 $row->add(new htmlResponsiveSelect('passwordMinLength', $optionsPwdLength, [(string) $cfg->passwordMinLength], _('Minimum password length'), '242'));
632 $row->addVerticalSpacer('1rem');
633 $row->add(new htmlResponsiveSelect('passwordMinLower', $optionsPwdLength, [(string) $cfg->passwordMinLower], _('Minimum lowercase characters'), '242'));
634 $row->add(new htmlResponsiveSelect('passwordMinUpper', $optionsPwdLength, [(string) $cfg->passwordMinUpper], _('Minimum uppercase characters'), '242'));
635 $row->add(new htmlResponsiveSelect('passwordMinNumeric', $optionsPwdLength, [(string) $cfg->passwordMinNumeric], _('Minimum numeric characters'), '242'));
636 $row->add(new htmlResponsiveSelect('passwordMinSymbol', $optionsPwdLength, [(string) $cfg->passwordMinSymbol], _('Minimum symbolic characters'), '242'));
637 $row->add(new htmlResponsiveSelect('passwordMinClasses', $options4, [(string) $cfg->passwordMinClasses], _('Minimum character classes'), '242'));
638 $row->addVerticalSpacer('1rem');
639 $rulesCountOptions = [_('all') => '-1', '3' => '3', '4' => '4'];
640 $rulesCountSelect = new htmlResponsiveSelect('passwordRulesCount', $rulesCountOptions, [(string) $cfg->checkedRulesCount], _('Number of rules that must match'), '246');
641 $rulesCountSelect->setHasDescriptiveElements(true);
642 $row->add($rulesCountSelect);
643 $passwordMustNotContainUser = ($cfg->passwordMustNotContainUser === 'true');
644 $row->add(new htmlResponsiveInputCheckbox('passwordMustNotContainUser', $passwordMustNotContainUser, _('Password must not contain user name'), '247'));
645 $passwordMustNotContain3Chars = ($cfg->passwordMustNotContain3Chars === 'true');
646 $row->add(new htmlResponsiveInputCheckbox('passwordMustNotContain3Chars', $passwordMustNotContain3Chars, _('Password must not contain part of user/first/last name'), '248'));
647 if (function_exists('curl_init')) {
648 $row->addVerticalSpacer('1rem');
649 $row->add(new htmlResponsiveInputField(_('External password check'), 'externalPwdCheckUrl', $cfg->externalPwdCheckUrl, '249'));
650 }
651
652 // logging
653 $row->add(new htmlSubTitle(_("Logging")));
654 $levelOptions = [
655 _("Debug") => (string) LOG_DEBUG,
656 _("Notice") => (string) LOG_NOTICE,
657 _("Warning") => (string) LOG_WARNING,
658 _("Error") => (string) LOG_ERR
659 ];
660 $levelSelect = new htmlResponsiveSelect('logLevel', $levelOptions, [(string) $cfg->logLevel], _("Log level"), '239');
661 $levelSelect->setHasDescriptiveElements(true);
662 $row->add($levelSelect);
663 $destinationOptions = [
664 _("No logging") => "none",
665 _("System logging") => "syslog",
666 _("File") => 'file',
667 _("Remote") => 'remote'
668 ];
669 $destinationSelected = 'file';
670 $destinationPath = $cfg->logDestination;
671 $destinationRemote = '';
672 if ($cfg->logDestination == 'NONE') {
673 $destinationSelected = 'none';
674 $destinationPath = '';
675 }
676 elseif ($cfg->logDestination == 'SYSLOG') {
677 $destinationSelected = 'syslog';
678 $destinationPath = '';
679 }
680 elseif (str_starts_with($cfg->logDestination, 'REMOTE')) {
681 $destinationSelected = 'remote';
682 $remoteParts = explode(':', $cfg->logDestination, 2);
683 $destinationRemote = empty($remoteParts[1]) ? '' : $remoteParts[1];
684 $destinationPath = '';
685 }
686 $logDestinationSelect = new htmlResponsiveSelect('logDestination', $destinationOptions, [$destinationSelected], _("Log destination"), '240');
687 $logDestinationSelect->setTableRowsToHide([
688 'none' => ['logFile', 'logRemote'],
689 'syslog' => ['logFile', 'logRemote'],
690 'remote' => ['logFile'],
691 'file' => ['logRemote']
692 ]);
693 $logDestinationSelect->setTableRowsToShow([
694 'file' => ['logFile'],
695 'remote' => ['logRemote']
696 ]);
697 $logDestinationSelect->setHasDescriptiveElements(true);
698 $row->add($logDestinationSelect);
699 $row->add(new htmlResponsiveInputField(_('File'), 'logFile', $destinationPath));
700 $row->add(new htmlResponsiveInputField(_('Remote server'), 'logRemote', $destinationRemote, '251'));
701 $errorLogOptions = [
702 _('PHP system setting') => LAMCfgMain::ERROR_REPORTING_SYSTEM,
703 _('default') => LAMCfgMain::ERROR_REPORTING_DEFAULT,
704 _('all') => LAMCfgMain::ERROR_REPORTING_ALL
705 ];
706 $errorLogSelect = new htmlResponsiveSelect('errorReporting', $errorLogOptions, [$cfg->errorReporting], _('PHP error reporting'), '244');
707 $errorLogSelect->setHasDescriptiveElements(true);
708 $row->add($errorLogSelect);
709
710 // mail options
711 if (isLAMProVersion()) {
712 $row->add(new htmlSubTitle(_('Mail options')));
713 $mailServer = new htmlResponsiveInputField(_("Mail server"), 'mailServer', $cfg->mailServer, '253');
714 $row->add($mailServer);
715 $mailUser = new htmlResponsiveInputField(_("User name"), 'mailUser', $cfg->mailUser, '254');
716 $row->add($mailUser);
717 $mailPassword = new htmlResponsiveInputField(_("Password"), 'mailPassword', $cfg->mailPassword, '255');
718 $mailPassword->setIsPassword(true);
719 $row->add($mailPassword);
720 $mailEncryptionOptions = [
721 'TLS' => LAMCfgMain::SMTP_TLS,
722 'SSL' => LAMCfgMain::SMTP_SSL,
723 _('None') => LAMCfgMain::SMTP_NONE
724 ];
725 $selectedMailEncryption = empty($cfg->mailEncryption) ? LAMCfgMain::SMTP_TLS : $cfg->mailEncryption;
726 $mailEncryptionSelect = new htmlResponsiveSelect('mailEncryption', $mailEncryptionOptions, [$selectedMailEncryption], _('Encryption protocol'), '256');
727 $mailEncryptionSelect->setHasDescriptiveElements(true);
728 $row->add($mailEncryptionSelect);
729 $row->add(new htmlResponsiveInputField(_("Mail attribute"), 'mailAttribute', $cfg->getMailAttribute(), '258'));
730 $row->add(new htmlResponsiveInputField(_("Secondary mail attribute"), 'mailBackupAttribute', $cfg->getMailBackupAttribute(), '259'));
731 addSecurityTokenToSession(false);
732 $mailTestButton = new htmlButton('testSmtp', _('Test settings'));
733 $mailTestButton->setOnClick("window.lam.smtp.test(event, '" . getSecurityTokenName()
734 . "', '" . getSecurityTokenValue() . "', '" . _('Ok') . "', '" . _('Cancel') . "', '" . _('Test settings') . "')");
735 $row->addLabel(new htmlOutputText("&nbsp;", false));
736 $row->addField($mailTestButton);
737 $testDialogDivContent = new htmlResponsiveRow();
738 $fromAddressInput = new htmlResponsiveInputField(_('From address'), 'testSmtpFrom', null, null, true);
739 $fromAddressInput->setType('email');
740 $testDialogDivContent->add($fromAddressInput);
741 $toAddressInput = new htmlResponsiveInputField(_('To address'), 'testSmtpTo', null, null, true);
742 $toAddressInput->setType('email');
743 $testDialogDivContent->add($toAddressInput);
744 $testDialogDiv = new htmlDiv('smtpTestDialogDiv', $testDialogDivContent, ['hidden']);
745 $row->add($testDialogDiv);
746 }
747
748 // SMS options
749 if (isLAMProVersion()) {
750 $row->add(new htmlSubTitle(_('SMS options')));
751 $smsService = new SmsService();
752 $smsProviders = $smsService->findProviders();
753 $smsProviderOptions = [
754 '-' => '',
755 ];
756 $smsOptionsToHide = [
757 '' => ['smsApiKey', 'smsApiToken', 'smsAccountId', 'smsRegion', 'smsFrom', 'smsSubject', 'smsAttributes',
758 'smsDefaultCountryPrefix', 'btn_testSms']
759 ];
760 $smsOptionsToShow = [];
761 foreach ($smsProviders as $provider) {
762 $smsProviderOptions[$provider->getLabel()] = $provider->getId();
763 $smsOptionsToShow[$provider->getId()][] = 'smsAttributes';
764 $smsOptionsToShow[$provider->getId()][] = 'btn_testSms';
765 if ($provider->usesApiToken()) {
766 $smsOptionsToShow[$provider->getId()][] = 'smsApiToken';
767 }
768 else {
769 $smsOptionsToHide[$provider->getId()][] = 'smsApiToken';
770 }
771 if ($provider->usesApiKey()) {
772 $smsOptionsToShow[$provider->getId()][] = 'smsApiKey';
773 }
774 else {
775 $smsOptionsToHide[$provider->getId()][] = 'smsApiKey';
776 }
777 if ($provider->usesAccountId()) {
778 $smsOptionsToShow[$provider->getId()][] = 'smsAccountId';
779 }
780 else {
781 $smsOptionsToHide[$provider->getId()][] = 'smsAccountId';
782 }
783 if ($provider->usesRegion()) {
784 $smsOptionsToShow[$provider->getId()][] = 'smsRegion';
785 }
786 else {
787 $smsOptionsToHide[$provider->getId()][] = 'smsRegion';
788 }
789 if ($provider->usesFrom()) {
790 $smsOptionsToShow[$provider->getId()][] = 'smsFrom';
791 }
792 else {
793 $smsOptionsToHide[$provider->getId()][] = 'smsFrom';
794 }
795 if ($provider->usesSubject()) {
796 $smsOptionsToShow[$provider->getId()][] = 'smsSubject';
797 }
798 else {
799 $smsOptionsToHide[$provider->getId()][] = 'smsSubject';
800 }
801 }
802 $selectedSmsProvider = empty($cfg->smsProvider) ? '' : $cfg->smsProvider;
803 $smsProviderSelect = new htmlResponsiveSelect('smsProvider', $smsProviderOptions, [$selectedSmsProvider], _('SMS provider'), '296');
804 $smsProviderSelect->setHasDescriptiveElements(true);
805 $smsProviderSelect->setTableRowsToHide($smsOptionsToHide);
806 $smsProviderSelect->setTableRowsToShow($smsOptionsToShow);
807 $row->add($smsProviderSelect);
808 $row->add(new htmlResponsiveInputField(_('Region'), 'smsRegion', $cfg->smsRegion, '299c'));
809 $row->add(new htmlResponsiveInputField(_('Account id'), 'smsAccountId', $cfg->smsAccountId, '298a'));
810 $row->add(new htmlResponsiveInputField(_('API key'), 'smsApiKey', $cfg->smsApiKey, '297'));
811 $row->add(new htmlResponsiveInputField(_('Token'), 'smsApiToken', $cfg->smsToken, '298'));
812 $row->add(new htmlResponsiveInputField(_('From'), 'smsFrom', $cfg->smsFrom, '299b'));
813 $row->add(new htmlResponsiveInputField(_('Subject'), 'smsSubject', $cfg->smsSubject, '299d'));
814 $row->add(new htmlResponsiveInputField(_('Default country prefix'), 'smsDefaultCountryPrefix', $cfg->smsDefaultCountryPrefix, '299a'));
815 $row->add(new htmlResponsiveInputField(_("Mobile phone attributes"), 'smsAttributes', implode(';', $cfg->getSmsAttributes()), '299'));
816 $smsTestButtonRow = new htmlResponsiveRow();
817 $smsTestButton = new htmlButton('testSms', _('Test settings'));
818 $smsTestButton->setOnClick("window.lam.sms.test(event, '" . getSecurityTokenName()
819 . "', '" . getSecurityTokenValue() . "', '" . _('Ok') . "', '" . _('Cancel') . "', '" . _('Test settings') . "')");
820 $smsTestButtonRow->addLabel(new htmlOutputText("&nbsp;", false));
821 $smsTestButtonRow->addField($smsTestButton);
822 $row->add($smsTestButtonRow);
823 $smsTestDialogDivContent = new htmlResponsiveRow();
824 $smsTestNumber = new htmlResponsiveInputField(_('Mobile number'), 'testSmsNumber', null, null, true);
825 $smsTestNumber->setType('tel');
826 $smsTestDialogDivContent->add($smsTestNumber);
827 $smsTestDialogDiv = new htmlDiv('smsTestDialogDiv', $smsTestDialogDivContent, ['hidden']);
828 $row->add($smsTestDialogDiv);
829 }
830
831 // webauthn management
832 if (extension_loaded('PDO')
833 && in_array('sqlite', PDO::getAvailableDrivers())) {
834 include_once __DIR__ . '/../../lib/webauthn.inc';
835 $webAuthnManager = new WebauthnManager();
836 try {
837 $database = $webAuthnManager->getDatabase();
838 if ($database->hasRegisteredCredentials()) {
839 $row->add(new htmlSubTitle(_('WebAuthn devices')));
840 $webauthnSearchField = new htmlResponsiveInputField(_('User DN'), 'webauthn_searchTerm', null, '252');
841 $row->add($webauthnSearchField);
842 $row->addVerticalSpacer('0.5rem');
843 $row->add(new htmlButton('webauthn_search', _('Search')), 12, 12, 12, 'text-center');
844 $resultDiv = new htmlDiv('webauthn_results', new htmlOutputText(''), ['lam-webauthn-results', 'text-left']);
845 addSecurityTokenToSession(false);
846 $resultDiv->addDataAttribute('sec_token_value', getSecurityTokenValue());
847 $row->add($resultDiv);
848 $confirmationDiv = new htmlDiv('webauthnDeleteConfirm', new htmlOutputText(_('Do you really want to remove this device?')), ['hidden']);
849 $row->add($confirmationDiv);
850 }
851 }
852 catch (LAMException $e) {
853 logNewMessage(LOG_ERR, 'Webauthn error: ' . $e->getTitle() . ' ' . $e->getMessage());
854 $row->add(new htmlStatusMessage('ERROR', $e->getTitle()));
855 }
856 }
857
858 // module settings
859 $modules = getAllModules();
860 $supportsGlobalCronJob = false;
861 foreach ($modules as $module) {
862 $supportsGlobalCronJob = $supportsGlobalCronJob || $module->supportsGlobalCronJob();
863 $moduleOptions = $module->getGlobalConfigOptions($cfg->getModuleSettings());
864 if (empty($moduleOptions)) {
865 continue;
866 }
867 $row->add(new htmlSubTitle($module->get_alias()));
868 foreach ($moduleOptions as $moduleOption) {
869 $row->add($moduleOption);
870 }
871 $row->addVerticalSpacer('3rem');
872 }
873
874 // global cron job
875 if ($supportsGlobalCronJob) {
876 $row->add(new htmlSubTitle(_('Global cron job')));
877 $cronCommand = dirname(__FILE__, 3) . '/lib/runCronJobs.sh all';
878 $row->addLabel(new htmlOutputText('Cron command'));
879 $cmdGroup = new htmlGroup();
880 $cmdGroup->addElement(new htmlOutputText('0 0 * * * ' . $cronCommand));
881 $cmdGroup->addElement(new htmlSpacer('2rem', null));
882 $cmdGroup->addElement(new htmlHelpLink('294'));
883 $row->addField($cmdGroup);
884 }
885
886 // change master password
887 $row->add(new htmlSubTitle(_("Change master password")));
888 $pwd1 = new htmlResponsiveInputField(_("New master password"), 'masterpassword', '', '235');
889 $pwd1->setIsPassword(true, false, true);
890 $row->add($pwd1);
891 $pwd2 = new htmlResponsiveInputField(_("Reenter password"), 'masterpassword2', '');
892 $pwd2->setIsPassword(true, false, true);
893 $pwd2->setSameValueFieldID('masterpassword');
894 $row->add($pwd2);
895 $row->addVerticalSpacer('3rem');
896
897 // buttons
898 if ($cfg->isWritable()) {
899 $buttonTable = new htmlTable();
900 $saveButton = new htmlButton('submit', _("Save"));
901 $saveButton->setCSSClasses(['lam-primary']);
902 $buttonTable->addElement($saveButton);
903 $buttonTable->addElement(new htmlSpacer('0.5rem', null));
904 $buttonTable->addElement(new htmlButton('cancel', _("Cancel")));
905 $row->add($buttonTable);
906 $row->add(new htmlHiddenInput('submitFormData', '1'));
907 }
908
909 $box = new htmlDiv(null, $row);
910 $box->setCSSClasses(['roundedShadowBox']);
911 parseHtml(null, $box, [], false, 'user');
912
913
914 /**
915 * Formats an LDAP time string (e.g. from createTimestamp).
916 *
917 * @param String $time LDAP time value
918 * @return String formatted time
919 */
920 function formatSSLTimestamp($time) {
921 if (!empty($time)) {
922 $timeZone = 'UTC';
923 $sysTimeZone = @date_default_timezone_get();
924 if (!empty($sysTimeZone)) {
925 $timeZone = $sysTimeZone;
926 }
927 $date = new DateTime('@' . $time, new DateTimeZone($timeZone));
928 return $date->format('d.m.Y');
929 }
930 return '';
931 }
932
933
934 ?>
935
936 </form>
937 <p><br></p>
938
939 </body>
940 </html>
941