<?php

namespace LAM\CONFIG;

use LAM\LIB\TWO_FACTOR\TwoFactorProviderService;
use LAMCfgMain;
use LAMConfig;
use htmlTable;
use htmlAccordion;
use htmlSpacer;
use DateTimeZone;
use htmlStatusMessage;
use htmlOutputText;
use htmlInputCheckbox;
use htmlHelpLink;
use htmlSubTitle;
use htmlButton;
use htmlResponsiveRow;
use htmlResponsiveInputField;
use htmlResponsiveSelect;
use htmlResponsiveInputCheckbox;
use htmlResponsiveInputTextarea;
use htmlGroup;
use LAMException;
use ServerProfilePersistenceManager;

/*

  This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
  Copyright (C) 2003 - 2025  Roland Gruber

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/


/**
 * Main page of configuration
 *
 * @package configuration
 * @author Roland Gruber
 * @author Thomas Manninger
 */


/** Access to config functions */
include_once(__DIR__ . "/../../lib/config.inc");
/** access to module settings */
include_once(__DIR__ . "/../../lib/modules.inc");
/** access to tools */
include_once(__DIR__ . "/../../lib/tools.inc");
/** 2-factor */
include_once __DIR__ . '/../../lib/2factor.inc';
/** common functions */
include_once __DIR__ . '/../../lib/configPages.inc';

// start session
if (isFileBasedSession()) {
	session_save_path("../../sess");
}
lam_start_session();

setlanguage();

// get password
$passwd = null;
if (isset($_POST['passwd'])) {
	$passwd = $_POST['passwd'];
}

// check if password was entered
// if not: load login page
if (!isset($passwd) && !(isset($_SESSION['conf_isAuthenticated']) && isset($_SESSION['conf_config']))) {
	$_SESSION['conf_message'] = new htmlStatusMessage('ERROR', _("No password was entered!"));
	/** go back to login if password is empty */
	metaRefresh('conflogin.php');
	exit;
}

$serverProfilePersistenceManager = new ServerProfilePersistenceManager();

if (!isset($_SESSION['conf_config']) && isset($_POST['filename'])) {
	try {
		$_SESSION['conf_config'] = $serverProfilePersistenceManager->loadProfile($_POST['filename']);
	}
	catch (LAMException $e) {
		$_SESSION['conf_message'] = new htmlStatusMessage('ERROR', $e->getTitle());
		metaRefresh('conflogin.php');
		exit;
	}
}
$conf = &$_SESSION['conf_config'];

// check if password is valid
// if not: load login page
if ((!isset($_SESSION['conf_isAuthenticated']) || ($_SESSION['conf_isAuthenticated'] !== $conf->getName()))
	&& !$conf->check_Passwd($passwd)) {
	$sessionKeys = array_keys($_SESSION);
	for ($i = 0; $i < count($sessionKeys); $i++) {
		if (str_starts_with($sessionKeys[$i], "conf_")) {
			unset($_SESSION[$sessionKeys[$i]]);
		}
	}
	$_SESSION['conf_message'] = new htmlStatusMessage('ERROR', _("The password is invalid! Please try again."));
	/** go back to login if password is invalid */
	metaRefresh('conflogin.php');
	exit;
}
$_SESSION['conf_isAuthenticated'] = $conf->getName();

// check if user canceled editing
if (isset($_POST['cancelSettings'])) {
	metaRefresh("../login.php");
	exit;
}

$errorsToDisplay = [];
if (isset($_SESSION['conf_messages']) && is_array($_SESSION['conf_messages'])) {
	$errorsToDisplay = array_merge($errorsToDisplay, $_SESSION['conf_messages']);
	unset($_SESSION['conf_messages']);
}

// check if button was pressed and if we have to save the settings or go to another tab
if (isset($_POST['saveSettings']) || isset($_POST['editmodules'])
	|| isset($_POST['edittypes']) || isset($_POST['generalSettingsButton'])
	|| isset($_POST['moduleSettings']) || isset($_POST['jobs'])) {
	$errorsToDisplay = checkInput();
	if (count($errorsToDisplay) == 0) {
		// go to final page
		if (isset($_POST['saveSettings'])) {
			metaRefresh("confsave.php");
			exit;
		}
		// go to modules page
        elseif (isset($_POST['editmodules'])) {
			metaRefresh("confmodules.php");
			exit;
		}
		// go to types page
        elseif (isset($_POST['edittypes'])) {
			metaRefresh("conftypes.php");
			exit;
		}
		// go to module settings page
        elseif (isset($_POST['moduleSettings'])) {
			metaRefresh("moduleSettings.php");
			exit;
		}
		// go to jobs page
        elseif (isset($_POST['jobs'])) {
			metaRefresh("jobs.php");
			exit;
		}
	}
}


echo $_SESSION['header'];
printHeaderContents(_("LDAP Account Manager Configuration"), '../..');
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"../../templates/lib/extra/jodit/jodit.css\">\n";
echo "<body>\n";
// include all JavaScript files
printJsIncludes('../..');
printConfigurationPageHeaderBar($conf);

if (!$serverProfilePersistenceManager->isWritable($_SESSION['conf_config']->getName())) {
	StatusMessage('WARN', _('The config file is not writable.'), _('Your changes cannot be saved until you make the file writable for the webserver user.'));
	echo "<br>";
}

// display error messages
if ($errorsToDisplay !== []) {
	for ($i = 0; $i < count($errorsToDisplay); $i++) {
		call_user_func_array(StatusMessage(...), $errorsToDisplay[$i]);
	}
	echo "<br>";
}

$cfgMain = new LAMCfgMain();

// display formular
echo "<form enctype=\"multipart/form-data\" action=\"confmain.php\" method=\"post\" autocomplete=\"off\" novalidate=\"novalidate\">\n";

printConfigurationPageTabs(ConfigurationPageTab::GENERAL);

?>
    <input type="text" name="hiddenPreventAutocomplete" autocomplete="false" class="hidden" value="">
    <input type="password" name="hiddenPreventAutocompletePwd1" autocomplete="false" class="hidden" value="123">
    <input type="password" name="hiddenPreventAutocompletePwd2" autocomplete="false" class="hidden" value="321">
	<?php

$row = new htmlResponsiveRow();

$serverSettings = new htmlSubTitle(_("Server settings"), '../../graphics/world.svg', null, true);
$row->add($serverSettings);
// server URL
$urlInput = new htmlResponsiveInputField(_("Server address"), 'serverurl', $conf->get_ServerURL(), '201');
$urlInput->setRequired(true);
$row->add($urlInput);
// use TLS
$tlsOptions = [_("yes") => 'yes', _("no") => 'no'];
$tlsSelect = new htmlResponsiveSelect('useTLS', $tlsOptions, [$conf->getUseTLS()], _("Activate TLS"), '201');
$tlsSelect->setHasDescriptiveElements(true);
$row->add($tlsSelect);
// LDAP search limit
$searchLimitOptions = [
	'-' => 0,
	100 => 100,
	500 => 500,
	1000 => 1000,
	5000 => 5000,
	10000 => 10000,
	50000 => 50000,
	100000 => 100000
];
$limitSelect = new htmlResponsiveSelect('searchLimit', $searchLimitOptions, [$conf->get_searchLimit()], _("LDAP search limit"), '222');
$limitSelect->setHasDescriptiveElements(true);
$row->add($limitSelect);
// DN part to hide
$urlInput = new htmlResponsiveInputField(_("DN part to hide"), 'hideDnPart', $conf->getHideDnPart(), '292');
$row->add($urlInput);

// access level is only visible in Pro version
if (isLAMProVersion()) {
	$accessOptions = [
		_('Write access') => LAMConfig::ACCESS_ALL,
		_('Change passwords') => LAMConfig::ACCESS_PASSWORD_CHANGE,
		_('Read-only') => LAMConfig::ACCESS_READ_ONLY
	];
	$accessSelect = new htmlResponsiveSelect('accessLevel', $accessOptions, [$conf->getAccessLevel()], _("Access level"), '215');
	$accessSelect->setHasDescriptiveElements(true);
	$row->add($accessSelect);
}

$row->addVerticalSpacer('1rem');
// login method
$loginOptions = [
	_('Fixed list') => LAMConfig::LOGIN_LIST,
	_('LDAP search') => LAMConfig::LOGIN_SEARCH
];
$loginSelect = new htmlResponsiveSelect('loginMethod', $loginOptions, [$conf->getLoginMethod()], _("Login method"), '220');
$loginSelect->setHasDescriptiveElements(true);
$loginSelect->setTableRowsToHide([
	LAMConfig::LOGIN_LIST => ['loginSearchSuffix', 'loginSearchFilter', 'loginSearchDN', 'loginSearchPassword', 'httpAuthentication'],
	LAMConfig::LOGIN_SEARCH => ['admins']
]);
$loginSelect->setTableRowsToShow([
	LAMConfig::LOGIN_LIST => ['admins'],
	LAMConfig::LOGIN_SEARCH => ['loginSearchSuffix', 'loginSearchFilter', 'loginSearchDN', 'loginSearchPassword', 'httpAuthentication']
]);
$row->add($loginSelect);
// admin list
$adminText = implode("\n", explode(";", $conf->get_Adminstring()));
$adminTextInput = new htmlResponsiveInputTextarea('admins', $adminText, '50', '3', _("List of valid users"), '207');
$adminTextInput->setRequired(true);
$row->add($adminTextInput);
// search suffix
$searchSuffixInput = new htmlResponsiveInputField(_("LDAP suffix"), 'loginSearchSuffix', $conf->getLoginSearchSuffix(), '221');
$searchSuffixInput->setRequired(true);
$row->add($searchSuffixInput);
// login search filter
$searchFilterInput = new htmlResponsiveInputField(_("LDAP filter"), 'loginSearchFilter', $conf->getLoginSearchFilter(), '221');
$searchFilterInput->setRequired(true);
$row->add($searchFilterInput);
// login search bind user
$row->add(new htmlResponsiveInputField(_("Bind user"), 'loginSearchDN', $conf->getLoginSearchDN(), '224'));
// login search bind password
$searchPasswordInput = new htmlResponsiveInputField(_("Bind password"), 'loginSearchPassword', $conf->getLoginSearchPassword(), '224');
$searchPasswordInput->setIsPassword(true);
$row->add($searchPasswordInput);
// HTTP authentication
$row->add(new htmlResponsiveInputCheckbox('httpAuthentication', ($conf->getHttpAuthentication() == 'true'), _('HTTP authentication'), '223'));
$row->addVerticalSpacer('1rem');

// advanced options
$advancedOptionsContent = new htmlResponsiveRow();
// display name
$advancedOptionsContent->add(new htmlResponsiveInputField(_('Display name'), 'serverDisplayName', $conf->getServerDisplayName(), '268'));
// referrals
$followReferrals = ($conf->getFollowReferrals() === 'true');
$advancedOptionsContent->add(new htmlResponsiveInputCheckbox('followReferrals', $followReferrals, _('Follow referrals'), '205'));
// paged results
$pagedResults = ($conf->getPagedResults() === 'true');
$advancedOptionsContent->add(new htmlResponsiveInputCheckbox('pagedResults', $pagedResults, _('Paged results'), '266'));
// show deleted entries
$adShowDeleted = ($conf->getAdShowDeleted() === 'true');
$advancedOptionsContent->add(new htmlResponsiveInputCheckbox('adShowDeleted', $adShowDeleted, _('Show deleted entries'), '295'));
// referential integrity overlay
$referentialIntegrity = ($conf->isReferentialIntegrityOverlayActive());
$advancedOptionsContent->add(new htmlResponsiveInputCheckbox('referentialIntegrityOverlay', $referentialIntegrity, _('Referential integrity overlay'), '269'));
// hide password prompt for expired passwords
$hidePasswordPromptForExpiredPasswords = ($conf->isHidePasswordPromptForExpiredPasswords());
$advancedOptionsContent->add(new htmlResponsiveInputCheckbox('hidePasswordPromptForExpiredPasswords', $hidePasswordPromptForExpiredPasswords, _('Hide password prompt for expired password'), '291'));

// build advanced options box
$advancedOptions = new htmlAccordion('advancedOptions_server', [_('Advanced options') => $advancedOptionsContent], false);
$advancedOptions->colspan = 15;
$row->add($advancedOptions);

$row->addVerticalSpacer('2rem');

// language
$row->add(new htmlSubTitle(_("Language settings"), '../../graphics/language.svg', null, true));
// read available languages
$possibleLanguages = getLanguages();
$defaultLanguage = ['en_GB.utf8'];
if (!empty($possibleLanguages)) {
	$languages = [];
	foreach ($possibleLanguages as $lang) {
		$languages[$lang->description] = $lang->code;
		if (str_starts_with($conf->get_defaultLanguage(), $lang->code)) {
			$defaultLanguage = [$lang->code];
		}
	}
	$languageSelect = new htmlResponsiveSelect('lang', $languages, $defaultLanguage, _("Default language"), '209');
	$languageSelect->setHasDescriptiveElements(true);
	$row->add($languageSelect);
}
else {
	$row->add(new htmlStatusMessage('ERROR', "Unable to load available languages. Setting English as default language."));
}
$timezones = [];
$timezones = array_merge($timezones, DateTimeZone::listIdentifiers(DateTimeZone::AFRICA));
$timezones = [...$timezones, ...DateTimeZone::listIdentifiers(DateTimeZone::AMERICA)];
$timezones = [...$timezones, ...DateTimeZone::listIdentifiers(DateTimeZone::ANTARCTICA)];
$timezones = [...$timezones, ...DateTimeZone::listIdentifiers(DateTimeZone::ARCTIC)];
$timezones = [...$timezones, ...DateTimeZone::listIdentifiers(DateTimeZone::ASIA)];
$timezones = [...$timezones, ...DateTimeZone::listIdentifiers(DateTimeZone::ATLANTIC)];
$timezones = [...$timezones, ...DateTimeZone::listIdentifiers(DateTimeZone::AUSTRALIA)];
$timezones = [...$timezones, ...DateTimeZone::listIdentifiers(DateTimeZone::EUROPE)];
$timezones = [...$timezones, ...DateTimeZone::listIdentifiers(DateTimeZone::INDIAN)];
$timezones = [...$timezones, ...DateTimeZone::listIdentifiers(DateTimeZone::PACIFIC)];
$timezones = [...$timezones, ...DateTimeZone::listIdentifiers(DateTimeZone::UTC)];
$row->add(new htmlResponsiveSelect('timeZone', $timezones, [$conf->getTimeZone()], _('Time zone'), '213'));

$row->addVerticalSpacer('2rem');

// tool settings
$row->add(new htmlSubTitle(_("Tool settings"), '../../graphics/configure.svg', null, true));
$toolSettings = $conf->getToolSettings();
$tools = getTools();
$row->add(new htmlOutputText(_('Hidden tools')));
$row->addVerticalSpacer('0.5rem');
$hideableTools = 0;
foreach ($tools as $tool) {
	if (!$tool->isHideable()) {
		continue;
	}
	$hideableTools++;
	$toolClass = $tool::class;
	if ($toolClass === false) {
		continue;
	}
	$toolName = substr($toolClass, strrpos($toolClass, '\\') + 1);
	$selected = false;
	if (isset($toolSettings['tool_hide_' . $toolName]) && ($toolSettings['tool_hide_' . $toolName] === 'true')) {
		$selected = true;
	}
	$row->add(new htmlResponsiveInputCheckbox('tool_hide_' . $toolName, $selected, $tool->getName(), null, true), 12, 4);
}
for ($i = $hideableTools % 3; $i < 3; $i++) {
	$row->add(new htmlOutputText(''), 0, 4);
}
$toolConfigOptionTypes = [];
foreach ($tools as $tool) {
	$toolConfigContent = $tool->getConfigOptions($toolSettings);
	if ($toolConfigContent !== null) {
		ob_start();
		$optionTypes = parseHtml(null, $tool->getConfigOptions($toolSettings), [], true, 'user');
		ob_end_clean();
		$toolConfigOptionTypes = array_merge($toolConfigOptionTypes, $optionTypes);
		$row->addVerticalSpacer('1rem');
		$row->add($toolConfigContent);
	}
}
$_SESSION['confmain_toolTypes'] = $toolConfigOptionTypes;

$row->addVerticalSpacer('2rem');

// LAM Pro settings
if (isLAMProVersion()) {
	// password reset page
	$row->add(new htmlSubTitle(_("Password reset page settings"), '../../graphics/key.svg', null, true));

	$pwdResetAllowSpecific = true;
	if ($conf->getPwdResetAllowSpecificPassword() == 'false') {
		$pwdResetAllowSpecific = false;
	}
	$row->add(new htmlResponsiveInputCheckbox('pwdResetAllowSpecificPassword', $pwdResetAllowSpecific, _('Allow setting specific passwords'), '280'));

	$pwdResetAllowScreenPassword = true;
	if ($conf->getPwdResetAllowScreenPassword() == 'false') {
		$pwdResetAllowScreenPassword = false;
	}
	$row->add(new htmlResponsiveInputCheckbox('pwdResetAllowScreenPassword', $pwdResetAllowScreenPassword, _('Allow to display password on screen'), '281'));

	$pwdResetForcePasswordChange = true;
	if ($conf->getPwdResetForcePasswordChange() == 'false') {
		$pwdResetForcePasswordChange = false;
	}
	$row->add(new htmlResponsiveInputCheckbox('pwdResetForcePasswordChange', $pwdResetForcePasswordChange, _('Force password change by default'), '283'));

	$pwdResetDefaultPasswordOutputOptions = [
		_('Display on screen') => LAMConfig::PWDRESET_DEFAULT_SCREEN,
		_('Send via mail') => LAMConfig::PWDRESET_DEFAULT_MAIL,
		_('All') => LAMConfig::PWDRESET_DEFAULT_ALL
	];
    if (!empty($cfgMain->smsProvider)) {
		$pwdResetDefaultPasswordOutputOptions[_('Send via SMS')] = LAMConfig::PWDRESET_DEFAULT_SMS;
    }
	$pwdResetDefaultPasswordOutputSelect = new htmlResponsiveSelect('pwdResetDefaultPasswordOutput', $pwdResetDefaultPasswordOutputOptions, [$conf->getPwdResetDefaultPasswordOutput()], _("Default password output"), '282');
	$pwdResetDefaultPasswordOutputSelect->setHasDescriptiveElements(true);
	$row->add($pwdResetDefaultPasswordOutputSelect);

	$row->addVerticalSpacer('2rem');

	// mail settings
	$row->add(new htmlSubTitle(_("Password mail settings"), '../../graphics/mail.svg', null, true));

	$pwdMailFrom = new htmlResponsiveInputField(_('From address'), 'pwdResetMail_from', $conf->getLamProMailFrom(), '550', true);
	$row->add($pwdMailFrom);

	$pwdMailReplyTo = new htmlResponsiveInputField(_('Reply-to address'), 'pwdResetMail_replyTo', $conf->getLamProMailReplyTo(), '554');
	$row->add($pwdMailReplyTo);

	$pwdMailSubject = new htmlResponsiveInputField(_('Subject'), 'pwdResetMail_subject', $conf->getLamProMailSubject(), '551');
	$row->add($pwdMailSubject);

	$pwdMailIsHTML = false;
	if ($conf->getLamProMailIsHTML() == 'true') {
		$pwdMailIsHTML = true;
	}
	$row->add(new htmlResponsiveInputCheckbox('pwdResetMail_isHTML', $pwdMailIsHTML, _('HTML format'), '553'));

	$pwdMailAllowAlternate = true;
	if ($conf->getLamProMailAllowAlternateAddress() == 'false') {
		$pwdMailAllowAlternate = false;
	}
	$row->add(new htmlResponsiveInputCheckbox('pwdResetMail_allowAlternate', $pwdMailAllowAlternate, _('Allow alternate address'), '555'));

	$pwdMailBody = new htmlResponsiveInputTextarea('pwdResetMail_body', $conf->getLamProMailText(), 50, 4, _('Text'), '552');
	$row->add($pwdMailBody);

	$row->addVerticalSpacer('2rem');
}

// lamdaemon settings
$row->add(new htmlSubTitle(_("Lamdaemon settings"), '../../graphics/script.svg', null, true));
$row->add(new htmlResponsiveInputField(_("Server list"), 'scriptservers', $conf->get_scriptServers(), '218'));
$row->add(new htmlResponsiveInputField(_("Path to external script"), 'scriptpath', $conf->get_scriptPath(), '210'));

$row->add(new htmlResponsiveInputField(_('User name'), 'scriptuser', $conf->getScriptUserName(), '284'));
$row->add(new htmlResponsiveInputField(_('SSH key file'), 'scriptkey', $conf->getScriptSSHKey(), '285'));
$sshKeyPassword = new htmlResponsiveInputField(_('SSH key password'), 'scriptkeypassword', $conf->getScriptSSHKeyPassword(), '286');
$sshKeyPassword->setIsPassword(true);
$row->add($sshKeyPassword);

$row->addVerticalSpacer('0.5rem');
$lamdaemonRightsLabel = new htmlGroup();
$lamdaemonRightsLabel->addElement(new htmlOutputText(_("Rights for the home directory")));
$lamdaemonRightsLabel->addElement(new htmlSpacer('0.2rem', null));
$lamdaemonRightsLabel->addElement(new htmlHelpLink('219'));
$row->addLabel($lamdaemonRightsLabel);
$chmod = $conf->get_scriptRights();
$rightsTable = new htmlTable();
$rightsTable->setCSSClasses(['padding5']);
$rightsTable->addElement(new htmlOutputText(''));
$rightsTable->addElement(new htmlOutputText(_("Read")));
$rightsTable->addElement(new htmlOutputText(_("Write")));
$rightsTable->addElement(new htmlOutputText(_("Execute")), true);
$rightsTable->addElement(new htmlOutputText(_("Owner")));
$rightsTable->addElement(new htmlInputCheckbox('chmod_owr', checkChmod("read", "owner", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_oww', checkChmod("write", "owner", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_owe', checkChmod("execute", "owner", $chmod)), true);
$rightsTable->addElement(new htmlOutputText(_("Group")));
$rightsTable->addElement(new htmlInputCheckbox('chmod_grr', checkChmod("read", "group", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_grw', checkChmod("write", "group", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_gre', checkChmod("execute", "group", $chmod)), true);
$rightsTable->addElement(new htmlOutputText(_("Other")));
$rightsTable->addElement(new htmlInputCheckbox('chmod_otr', checkChmod("read", "other", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_otw', checkChmod("write", "other", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_ote', checkChmod("execute", "other", $chmod)), true);
$row->addField($rightsTable);

$row->addVerticalSpacer('2rem');

// security settings
$row->add(new htmlSubTitle(_("Security settings"), '../../graphics/locked.svg', null, true));
// password policy override
$row->add(new htmlSubTitle(_("Global password policy override"), '../../graphics/locked.svg'));
$optionsPwdLength = [''];
for ($i = 1; $i <= 50; $i++) {
	$optionsPwdLength[] = $i;
}
$row->add(new htmlResponsiveSelect('pwdPolicyMinLength', $optionsPwdLength, [$conf->getPwdPolicyMinLength()], _('Minimum password length'), '242'));
$row->add(new htmlResponsiveSelect('pwdPolicyMinLowercase', $optionsPwdLength, [$conf->getpwdPolicyMinLowercase()], _('Minimum lowercase characters'), '242'));
$row->add(new htmlResponsiveSelect('pwdPolicyMinUppercase', $optionsPwdLength, [$conf->getPwdPolicyMinUppercase()], _('Minimum uppercase characters'), '242'));
$row->add(new htmlResponsiveSelect('pwdPolicyMinNumeric', $optionsPwdLength, [$conf->getPwdPolicyMinNumeric()], _('Minimum numeric characters'), '242'));
$row->add(new htmlResponsiveSelect('pwdPolicyMinSymbolic', $optionsPwdLength, [$conf->getPwdPolicyMinSymbolic()], _('Minimum symbolic characters'), '242'));

// 2factor authentication
if (extension_loaded('curl')) {
	$row->add(new htmlSubTitle(_("2-factor authentication"), '../../graphics/locked.svg'));
	$twoFactorOptions = [
		_('None') => TwoFactorProviderService::TWO_FACTOR_NONE,
		'privacyIDEA' => TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA,
		'YubiKey' => TwoFactorProviderService::TWO_FACTOR_YUBICO,
		'Duo' => TwoFactorProviderService::TWO_FACTOR_DUO,
		'Okta' => TwoFactorProviderService::TWO_FACTOR_OKTA,
		'OpenId' => TwoFactorProviderService::TWO_FACTOR_OPENID,
		'WebAuthn' => TwoFactorProviderService::TWO_FACTOR_WEBAUTHN
	];
	$twoFactorSelect = new htmlResponsiveSelect('twoFactor', $twoFactorOptions, [$conf->getTwoFactorAuthentication()], _('Provider'), '514');
	$twoFactorSelect->setHasDescriptiveElements(true);
	$twoFactorSelect->setTableRowsToHide([
		TwoFactorProviderService::TWO_FACTOR_NONE => ['twoFactorURL', 'twoFactorURLs', 'twoFactorInsecure', 'twoFactorLabel',
			'twoFactorOptional', 'twoFactorCaption', 'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorAttribute',
			'twoFactorDomain', 'twoFactorAllowToRememberDeviceOptions'],
		TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA => ['twoFactorURLs', 'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorDomain'],
		TwoFactorProviderService::TWO_FACTOR_YUBICO => ['twoFactorURL', 'twoFactorAttribute', 'twoFactorDomain'],
		TwoFactorProviderService::TWO_FACTOR_DUO => ['twoFactorURLs', 'twoFactorOptional', 'twoFactorInsecure', 'twoFactorLabel',
			'twoFactorDomain', 'twoFactorAllowToRememberDeviceOptions'],
		TwoFactorProviderService::TWO_FACTOR_OKTA => ['twoFactorURLs', 'twoFactorOptional', 'twoFactorInsecure', 'twoFactorLabel',
			'twoFactorDomain', 'twoFactorAllowToRememberDeviceOptions'],
		TwoFactorProviderService::TWO_FACTOR_OPENID => ['twoFactorURLs', 'twoFactorOptional', 'twoFactorInsecure', 'twoFactorLabel',
			'twoFactorDomain', 'twoFactorAllowToRememberDeviceOptions'],
		TwoFactorProviderService::TWO_FACTOR_WEBAUTHN => ['twoFactorURL', 'twoFactorURLs', 'twoFactorInsecure', 'twoFactorLabel',
			'twoFactorCaption', 'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorAttribute']
	]);
	$twoFactorSelect->setTableRowsToShow([
		TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA => ['twoFactorURL', 'twoFactorInsecure', 'twoFactorLabel',
			'twoFactorOptional', 'twoFactorCaption', 'twoFactorAttribute', 'twoFactorAllowToRememberDeviceOptions'],
		TwoFactorProviderService::TWO_FACTOR_YUBICO => ['twoFactorURLs', 'twoFactorInsecure', 'twoFactorLabel',
			'twoFactorOptional', 'twoFactorCaption', 'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorAllowToRememberDeviceOptions'],
		TwoFactorProviderService::TWO_FACTOR_DUO => ['twoFactorURL', 'twoFactorLabel', 'twoFactorCaption',
			'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorAttribute'],
		TwoFactorProviderService::TWO_FACTOR_OKTA => ['twoFactorURL', 'twoFactorCaption', 'twoFactorClientId',
			'twoFactorSecretKey', 'twoFactorAttribute'],
		TwoFactorProviderService::TWO_FACTOR_OPENID => ['twoFactorURL', 'twoFactorCaption', 'twoFactorClientId',
			'twoFactorSecretKey', 'twoFactorAttribute'],
		TwoFactorProviderService::TWO_FACTOR_WEBAUTHN => ['twoFactorDomain', 'twoFactorOptional',
			'twoFactorAllowToRememberDeviceOptions']
	]);
	$row->add($twoFactorSelect);
	$twoFactorAttribute = new htmlResponsiveInputField(_("User name attribute"), 'twoFactorAttribute', $conf->getTwoFactorAuthenticationAttribute(), '528');
	$row->add($twoFactorAttribute);
	$twoFactorUrl = new htmlResponsiveInputField(_("Base URL"), 'twoFactorURL', $conf->getTwoFactorAuthenticationURL(), '515');
	$twoFactorUrl->setRequired(true);
	$row->add($twoFactorUrl);
	$twoFactorUrl = new htmlResponsiveInputTextarea('twoFactorURLs', $conf->getTwoFactorAuthenticationURL(), '80', '4', _("Base URLs"), '515a');
	$twoFactorUrl->setRequired(true);
	$row->add($twoFactorUrl);
	$twoFactorClientId = new htmlResponsiveInputField(_("Client id"), 'twoFactorClientId', $conf->getTwoFactorAuthenticationClientId(), '524');
	$row->add($twoFactorClientId);
	$twoFactorSecretKey = new htmlResponsiveInputField(_("Secret key"), 'twoFactorSecretKey', $conf->getTwoFactorAuthenticationSecretKey(), '528');
	$row->add($twoFactorSecretKey);
	$twoFactorDomain = new htmlResponsiveInputField(_("Domain"), 'twoFactorDomain', $conf->getTwoFactorAuthenticationDomain(), '529');
	$row->add($twoFactorDomain);
	$twoFactorLabel = new htmlResponsiveInputField(_("Label"), 'twoFactorLabel', $conf->getTwoFactorAuthenticationLabel(), '517');
	$row->add($twoFactorLabel);
	$row->add(new htmlResponsiveInputCheckbox('twoFactorOptional', $conf->getTwoFactorAuthenticationOptional(), _('Optional'), '519'));
	$row->add(new htmlResponsiveInputCheckbox('twoFactorInsecure', $conf->getTwoFactorAuthenticationInsecure(), _('Disable certificate check'), '516'));
	$twoFactorCaption = new htmlResponsiveInputTextarea('twoFactorCaption', $conf->getTwoFactorAuthenticationCaption(), '80', '4', _("Caption"));
	$twoFactorCaption->setIsRichEdit(true);
	$row->add($twoFactorCaption);
	$row->addVerticalSpacer('0.5rem');
	$rememberDeviceRow = new htmlResponsiveRow();
	$rememberDeviceRow->setId('twoFactorAllowToRememberDeviceOptions');
	$twoFactorAllowToRememberDeviceChecked = ($conf->getTwoFactorAllowToRememberDevice() === 'true');
	$twoFactorAllowToRememberDevice = new htmlResponsiveInputCheckbox('twoFactorAllowToRememberDevice', $twoFactorAllowToRememberDeviceChecked, _('Allow remembering device'), '530');
	$twoFactorAllowToRememberDevice->setTableRowsToShow(['twoFactorAllowToRememberDeviceExtraOptions']);
	$rememberDeviceRow->add($twoFactorAllowToRememberDevice);
	$rememberDeviceExtraRow = new htmlResponsiveRow();
	$rememberDeviceExtraRow->setId('twoFactorAllowToRememberDeviceExtraOptions');
	$twoFactorRememberDeviceDuration = new htmlResponsiveInputField(_("Remember device period"), 'twoFactorRememberDeviceDuration', formatSecondsToShortFormat($conf->getTwoFactorRememberDeviceDuration()), '531');
	$rememberDeviceExtraRow->add($twoFactorRememberDeviceDuration);
	$twoFactorRememberDevicePassword = new htmlResponsiveInputField(_("Password to remember devices"), 'twoFactorRememberDevicePassword', $conf->getTwoFactorRememberDevicePassword(), '532');
	$twoFactorRememberDevicePassword->setIsPassword(true);
	$rememberDeviceExtraRow->add($twoFactorRememberDevicePassword);
	$rememberDeviceRow->add($rememberDeviceExtraRow);
	$row->add($rememberDeviceRow);
}

// new password
$row->add(new htmlSubTitle(_("Profile password"), '../../graphics/key.svg', null, true));
$password1 = new htmlResponsiveInputField(_("New password"), 'passwd1', null, '212');
$password1->setIsPassword(true, false, true);
$password2 = new htmlResponsiveInputField(_("Reenter password"), 'passwd2');
$password2->setIsPassword(true, false, true);
$password2->setSameValueFieldID('passwd1');
$row->add($password1);
$row->add($password2);

$row->addVerticalSpacer('2rem');

parseHtml(null, $row, [], false, 'user');

echo "</div></div>";

$buttonContainer = new htmlTable();
$buttonContainer->addElement(new htmlSpacer(null, '10px'), true);
$saveButton = new htmlButton('saveSettings', _('Save'));
$saveButton->setCSSClasses(['lam-primary']);
$buttonContainer->addElement($saveButton);
$cancelButton = new htmlButton('cancelSettings', _('Cancel'));
$buttonContainer->addElement($cancelButton, true);
$buttonContainer->addElement(new htmlSpacer(null, '10px'), true);
parseHtml(null, $buttonContainer, [], false, 'user');

?>
    </form>
    <script type="text/javascript" src="../lib/extra/jodit/jodit.js"></script>
    </body>
    </html>
	<?php

/**
 * Checks user input and saves the entered settings.
 *
 * @return array<mixed> list of errors
 */
function checkInput(): array {
	$conf = &$_SESSION['conf_config'];

	// check new preferences
	$errors = [];
	if (!$conf->set_ServerURL($_POST['serverurl'])) {
		$errors[] = ["ERROR", _("Server address is invalid!")];
	}
	$conf->setServerDisplayName($_POST['serverDisplayName']);
	$conf->setUseTLS($_POST['useTLS']);
	if ((str_contains($_POST['serverurl'], 'ldaps://')) && ($_POST['useTLS'] == 'yes')) {
		$errors[] = ["ERROR", _('You cannot use SSL and TLS encryption at the same time. Please use either "ldaps://" or TLS.')];
	}
	if (isset($_POST['followReferrals']) && ($_POST['followReferrals'] == 'on')) {
		$conf->setFollowReferrals('true');
	}
	else {
		$conf->setFollowReferrals('false');
	}
	if (isset($_POST['pagedResults']) && ($_POST['pagedResults'] == 'on')) {
		$conf->setPagedResults('true');
	}
	else {
		$conf->setPagedResults('false');
	}
	if (isset($_POST['adShowDeleted']) && ($_POST['adShowDeleted'] == 'on')) {
		$conf->setAdShowDeleted('true');
	}
	else {
		$conf->setAdShowDeleted('false');
	}
	if (isset($_POST['referentialIntegrityOverlay']) && ($_POST['referentialIntegrityOverlay'] == 'on')) {
		$conf->setReferentialIntegrityOverlay('true');
	}
	else {
		$conf->setReferentialIntegrityOverlay('false');
	}
	if (isset($_POST['hidePasswordPromptForExpiredPasswords']) && ($_POST['hidePasswordPromptForExpiredPasswords'] == 'on')) {
		$conf->setHidePasswordPromptForExpiredPasswords('true');
	}
	else {
		$conf->setHidePasswordPromptForExpiredPasswords('false');
	}
	$conf->set_searchLimit($_POST['searchLimit']);
	$conf->setHideDnPart($_POST['hideDnPart']);
	if (isLAMProVersion()) {
		$conf->setAccessLevel($_POST['accessLevel']);
		if (isset($_POST['pwdResetAllowSpecificPassword']) && ($_POST['pwdResetAllowSpecificPassword'] == 'on')) {
			$conf->setPwdResetAllowSpecificPassword('true');
		}
		else {
			$conf->setPwdResetAllowSpecificPassword('false');
		}
		if (isset($_POST['pwdResetAllowScreenPassword']) && ($_POST['pwdResetAllowScreenPassword'] == 'on')) {
			$conf->setPwdResetAllowScreenPassword('true');
		}
		else {
			$conf->setPwdResetAllowScreenPassword('false');
		}
		if (isset($_POST['pwdResetForcePasswordChange']) && ($_POST['pwdResetForcePasswordChange'] == 'on')) {
			$conf->setPwdResetForcePasswordChange('true');
		}
		else {
			$conf->setPwdResetForcePasswordChange('false');
		}
		$conf->setPwdResetDefaultPasswordOutput($_POST['pwdResetDefaultPasswordOutput']);
		if (!$conf->setLamProMailFrom($_POST['pwdResetMail_from'])) {
			$errors[] = ["ERROR", _("From address for password mails is invalid."), htmlspecialchars($_POST['pwdResetMail_from'])];
		}
		if (!empty($_POST['pwdResetMail_subject']) && empty($_POST['pwdResetMail_from'])) {
			$errors[] = ["ERROR", _("From address for password mails is invalid."), htmlspecialchars($_POST['pwdResetMail_from'])];
		}
		if (!$conf->setLamProMailReplyTo($_POST['pwdResetMail_replyTo'])) {
			$errors[] = ["ERROR", _("Reply-to address for password mails is invalid."), htmlspecialchars($_POST['pwdResetMail_replyTo'])];
		}
		$conf->setLamProMailSubject($_POST['pwdResetMail_subject']);
		if (isset($_POST['pwdResetMail_isHTML']) && ($_POST['pwdResetMail_isHTML'] == 'on')) {
			$conf->setLamProMailIsHTML('true');
		}
		else {
			$conf->setLamProMailIsHTML('false');
		}
		if (isset($_POST['pwdResetMail_allowAlternate']) && ($_POST['pwdResetMail_allowAlternate'] == 'on')) {
			$conf->setLamProMailAllowAlternateAddress('true');
		}
		else {
			$conf->setLamProMailAllowAlternateAddress('false');
		}
		$conf->setLamProMailText($_POST['pwdResetMail_body']);
	}
	$adminText = $_POST['admins'];
	$adminText = explode("\n", $adminText);
	$adminTextNew = [];
	for ($i = 0; $i < count($adminText); $i++) {
		if (trim($adminText[$i]) === "") {
			continue;
		}
		$adminTextNew[] = trim($adminText[$i]);
	}
	$conf->setLoginMethod($_POST['loginMethod']);
	$conf->setLoginSearchFilter($_POST['loginSearchFilter']);
	$conf->setLoginSearchSuffix($_POST['loginSearchSuffix']);
	$conf->setLoginSearchPassword($_POST['loginSearchPassword']);
	$conf->setLoginSearchDN($_POST['loginSearchDN']);
	// check only if search method
	if (($_POST['loginMethod'] == LAMConfig::LOGIN_SEARCH)
        && !$conf->setLoginSearchDN($_POST['loginSearchDN'])) {
		$errors[] = ["ERROR", _("Please enter a valid bind user.")];
	}
	if (isset($_POST['httpAuthentication']) && ($_POST['httpAuthentication'] == 'on')) {
		$conf->setHttpAuthentication('true');
	}
	else {
		$conf->setHttpAuthentication('false');
	}
	if (!$conf->set_Adminstring(implode(";", $adminTextNew))) {
		$errors[] = ["ERROR", _("List of admin users is empty or invalid!")];
	}
	if (!$conf->set_defaultLanguage($_POST['lang'])) {
		$errors[] = ["ERROR", _("Language is not defined!")];
	}
	$conf->setTimeZone($_POST['timeZone']);
	if (!$conf->set_scriptpath($_POST['scriptpath'])) {
		$errors[] = ["ERROR", _("Script path is invalid!")];
	}
	if (!$conf->set_scriptservers($_POST['scriptservers'])) {
		$errors[] = ["ERROR", _("Script server is invalid!")];
	}
	$chmodOwner = 0;
	$chmodGroup = 0;
	$chmodOther = 0;
	if (isset($_POST['chmod_owr']) && ($_POST['chmod_owr'] == 'on')) {
		$chmodOwner += 4;
	}
	if (isset($_POST['chmod_oww']) && ($_POST['chmod_oww'] == 'on')) {
		$chmodOwner += 2;
	}
	if (isset($_POST['chmod_owe']) && ($_POST['chmod_owe'] == 'on')) {
		$chmodOwner += 1;
	}
	if (isset($_POST['chmod_grr']) && ($_POST['chmod_grr'] == 'on')) {
		$chmodGroup += 4;
	}
	if (isset($_POST['chmod_grw']) && ($_POST['chmod_grw'] == 'on')) {
		$chmodGroup += 2;
	}
	if (isset($_POST['chmod_gre']) && ($_POST['chmod_gre'] == 'on')) {
		$chmodGroup += 1;
	}
	if (isset($_POST['chmod_otr']) && ($_POST['chmod_otr'] == 'on')) {
		$chmodOther += 4;
	}
	if (isset($_POST['chmod_otw']) && ($_POST['chmod_otw'] == 'on')) {
		$chmodOther += 2;
	}
	if (isset($_POST['chmod_ote']) && ($_POST['chmod_ote'] == 'on')) {
		$chmodOther += 1;
	}
	$chmod = $chmodOwner . $chmodGroup . $chmodOther;
	if (!$conf->set_scriptrights($chmod)) {
		$errors[] = ["ERROR", _("Script rights are invalid!")];
	}
	$conf->setScriptUserName($_POST['scriptuser']);
	$conf->setScriptSSHKey($_POST['scriptkey']);
	$conf->setScriptSSHKeyPassword($_POST['scriptkeypassword']);
	if (!empty($_POST['scriptkey'])) {
		include_once __DIR__ . '/../../lib/remote.inc';
		$remote = new \LAM\REMOTE\Remote();
		try {
			$remote->loadKey($conf->getScriptSSHKey(), $conf->getScriptSSHKeyPassword());
		}
		catch (LAMException $e) {
			$errors[] = ['ERROR', _('SSH key file'), $e->getTitle()];
		}
	}
	// tool settings
	$tools = getTools();
	$toolSettings = extractConfigOptionsFromPOST($_SESSION['confmain_toolTypes']);
	foreach ($toolSettings as $key => $value) {
		$toolSettings[$key] = implode(LAMConfig::LINE_SEPARATOR, $value);
	}
	foreach ($tools as $tool) {
		$toolClass = $tool::class;
		if ($toolClass === false) {
			continue;
		}
		$toolName = substr($toolClass, strrpos($toolClass, '\\') + 1);
		$toolConfigID = 'tool_hide_' . $toolName;
		$toolSettings[$toolConfigID] = (isset($_POST[$toolConfigID])) && ($_POST[$toolConfigID] == 'on') ? 'true' : 'false';
		$toolErrors = $tool->checkConfigurationOptions($toolSettings);
		if (!empty($toolErrors)) {
			$errors = array_merge($errors, $toolErrors);
		}
	}

	$conf->setToolSettings($toolSettings);
	// password policy override
	$conf->setPwdPolicyMinLength($_POST['pwdPolicyMinLength']);
	$conf->setPwdPolicyMinLowercase($_POST['pwdPolicyMinLowercase']);
	$conf->setPwdPolicyMinUppercase($_POST['pwdPolicyMinUppercase']);
	$conf->setPwdPolicyMinNumeric($_POST['pwdPolicyMinNumeric']);
	$conf->setPwdPolicyMinSymbolic($_POST['pwdPolicyMinSymbolic']);
	// 2-factor
	if (extension_loaded('curl')) {
		$conf->setTwoFactorAuthentication($_POST['twoFactor']);
		if ($_POST['twoFactor'] === TwoFactorProviderService::TWO_FACTOR_YUBICO) {
			$conf->setTwoFactorAuthenticationURL($_POST['twoFactorURLs']);
		}
		else {
			$conf->setTwoFactorAuthenticationURL($_POST['twoFactorURL']);
		}
		$conf->setTwoFactorAuthenticationAttribute($_POST['twoFactorAttribute']);
		$conf->setTwoFactorAuthenticationClientId($_POST['twoFactorClientId']);
		$conf->setTwoFactorAuthenticationSecretKey($_POST['twoFactorSecretKey']);
		$conf->setTwoFactorAuthenticationDomain($_POST['twoFactorDomain']);
		$conf->setTwoFactorAuthenticationInsecure(isset($_POST['twoFactorInsecure']) && ($_POST['twoFactorInsecure'] === 'on'));
		$conf->setTwoFactorAuthenticationLabel($_POST['twoFactorLabel']);
		$conf->setTwoFactorAuthenticationOptional(isset($_POST['twoFactorOptional']) && ($_POST['twoFactorOptional'] === 'on'));
		$conf->setTwoFactorAuthenticationCaption(str_replace(["\r", "\n"], ['', ''], $_POST['twoFactorCaption']));
		$twoFactorAllowToRememberDevice = (isset($_POST['twoFactorAllowToRememberDevice']) && ($_POST['twoFactorAllowToRememberDevice'] === 'on')) ? 'true' : 'false';
		$conf->setTwoFactorAllowToRememberDevice($twoFactorAllowToRememberDevice);
		$conf->setTwoFactorRememberDeviceDuration(unformatShortFormatToSeconds($_POST['twoFactorRememberDeviceDuration']));
		$conf->setTwoFactorRememberDevicePassword($_POST['twoFactorRememberDevicePassword']);
	}
	// check if password was changed
	if (!empty($_POST['passwd1'])) {
		if ($_POST['passwd1'] !== $_POST['passwd2']) {
			$errors[] = ["ERROR", _("Passwords are different!")];
		}
        elseif (!isValidConfigurationPassword($_POST['passwd1'])) {
            $errors[] = ["ERROR", _('Profile password'), _('Please enter at least 8 characters including letters, a number and a symbol.')];
        }
		else {
			// set new password
			$conf->set_Passwd($_POST['passwd1']);
		}
	}

	return $errors;
}
