<?php

use LAM\PDF\PDFEntry;
use LAM\PDF\PDFLabelValue;
use LAM\PDF\PdfStructurePersistenceManager;
use LAM\PROFILES\AccountProfilePersistenceManager;
use LAM\TYPES\ConfiguredType;
use \LAM\TYPES\TypeManager;
use function LAM\TYPES\getScopeFromTypeId;

/*

  This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
  Copyright (C) 2003 - 2026  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


*/

/**
 * Interface between modules and other parts of LAM.
 *
 * @package modules
 * @author Tilo Lutz
 * @author Michael Duergner
 * @author Roland Gruber
 */

/** self-service functions */
include_once(__DIR__ . "/selfService.inc");
if (isLAMProVersion()) {
	/** job interface */
	include_once(__DIR__ . "/jobs.inc");
}
/** some helper functions */
include_once(__DIR__ . "/account.inc");
/** parent class of account modules */
include_once(__DIR__ . "/baseModule.inc");
/** access to LDAP server */
include_once(__DIR__ . "/ldap.inc");
/** remote functions */
include_once(__DIR__ . "/remote.inc");
/** security functions */
include_once(__DIR__ . "/security.inc");
/** meta HTML classes */
include_once(__DIR__ . "/html.inc");

/**
 * This includes all module files.
 */
$modulesINC_dirname = substr(__FILE__, 0, strlen(__FILE__) - 12) . "/modules";
$modulesINC_dir = dir($modulesINC_dirname);
// get module names.
while ($entry = $modulesINC_dir->read()) {
	if ((substr($entry, strlen($entry) - 4, 4) === '.inc') && is_file($modulesINC_dirname . '/' . $entry)) {
		include_once($modulesINC_dirname . '/' . $entry);
	}
}

/**
 * Returns the alias name of a module
 *
 * @param string $name the module name
 * @param string $scope the account type ("user", "group", "host")
 * @return string|null alias name
 */
function getModuleAlias(string $name, string $scope): ?string {
	$module = moduleCache::getModule($name, $scope);
	return $module?->get_alias();
}

/**
 * Returns true if the module is a base module
 *
 * @param string $name the module name
 * @param string $scope the account type ("user", "group", "host")
 * @return boolean true if base module
 */
function is_base_module($name, $scope) {
	$module = moduleCache::getModule($name, $scope);
	return $module->is_base_module();
}

/**
 * Returns the LDAP filter used by the account lists
 *
 * @param string $typeId the account type ("user", "group", "host")
 * @return string LDAP filter
 */
function get_ldap_filter($typeId) {
	$typeManager = new \LAM\TYPES\TypeManager();
	$type = $typeManager->getConfiguredType($typeId);
	$mods = $_SESSION['config']->get_AccountModules($typeId);
	$filters = ['or' => [], 'and' => []];
	$orFilter = '';
	for ($i = 0; $i < count($mods); $i++) {
		$module = moduleCache::getModule($mods[$i], $type->getScope());
		$modinfo = $module->get_ldap_filter($typeId);
		if (isset($modinfo['or'])) {
			$filters['or'][] = $modinfo['or'];
		}
		if (isset($modinfo['and'])) {
			$filters['and'][] = $modinfo['and'];
		}
	}
	// build OR filter
	if (count($filters['or']) === 1) {
		$orFilter = $filters['or'][0];
	}
	elseif (count($filters['or']) > 1) {
		$orFilter = "(|" . implode("", $filters['or']) . ")";
	}
	// add built OR filter to AND filters
	if (!empty($orFilter)) {
		$filters['and'][] = $orFilter;
	}
	// add type filter
	$typeSettings = $_SESSION['config']->get_typeSettings();
	if (isset($typeSettings['filter_' . $typeId]) && ($typeSettings['filter_' . $typeId] != '')) {
		if (str_starts_with($typeSettings['filter_' . $typeId], '(')) {
			$filters['and'][] = $typeSettings['filter_' . $typeId];
		}
		else {
			$filters['and'][] = '(' . $typeSettings['filter_' . $typeId] . ')';
		}
	}
	$finalFilter = (count($filters['and']) < 2) ? $filters['and'][0] : "(&" . implode("", $filters['and']) . ")";
	$loginData = $_SESSION['ldap']->getUserName();
	return str_replace('@@LOGIN_DN@@', $loginData, $finalFilter);
}

/**
 * Returns a list of LDAP attributes which can be used to form the RDN.
 *
 * The list is already sorted by the priority given by the modules.
 *
 * @param string $typeId account type (user, group, host)
 * @param string[] $selectedModules return only RDN attributes of these modules
 * @return string[] list of LDAP attributes
 */
function getRDNAttributes($typeId, $selectedModules = null) {
	$mods = $_SESSION['config']->get_AccountModules($typeId);
	if ($selectedModules != null) {
		$mods = $selectedModules;
	}
	$attrs_low = [];
	$attrs_normal = [];
	$attrs_high = [];
	for ($i = 0; $i < count($mods); $i++) {
		// get list of attributes
		$module = moduleCache::getModule($mods[$i], \LAM\TYPES\getScopeFromTypeId($typeId));
		$attrs = $module->get_RDNAttributes($typeId);
		$keys = array_keys($attrs);
		// sort attributes
		for ($k = 0; $k < count($keys); $k++) {
			switch ($attrs[$keys[$k]]) {
				case "normal":
					$attrs_normal[] = $keys[$k];
					break;
				case "high":
					$attrs_high[] = $keys[$k];
					break;
				case "low":
				default:
					$attrs_low[] = $keys[$k];
					break;
			}
		}
	}
	// merge arrays
	$return = array_values(array_unique($attrs_high));
	for ($i = 0; $i < count($attrs_normal); $i++) {
		if (!in_array($attrs_normal[$i], $return)) {
			$return[] = $attrs_normal[$i];
		}
	}
	for ($i = 0; $i < count($attrs_low); $i++) {
		if (!in_array($attrs_low[$i], $return)) {
			$return[] = $attrs_low[$i];
		}
	}
	return $return;
}

/**
 * Returns a hash array (module name => dependencies) of all module dependencies
 *
 * "dependencies" contains an array with two sub arrays: depends, conflicts
 * <br>The elements of "depends" are either module names or an array of module names (OR-case).
 * <br>The elements of conflicts are module names.
 *
 * @param string $scope the account type (user, group, host)
 * @return array<string, array<string, array<string|string[]>>> dependencies
 */
function getModulesDependencies($scope) {
	$return = [];
	$mods = getAvailableModules($scope);
	for ($i = 0; $i < count($mods); $i++) {
		$module = moduleCache::getModule($mods[$i], $scope);
		$return[$mods[$i]] = $module->get_dependencies();
	}
	return $return;
}


/**
 * Checks if there are missing dependencies between modules.
 *
 * @param string[] $selected selected module names
 * @param array<string, array<string, array<string|string[]>>> $deps module dependencies
 * @return false|string[][] false if no missing dependency was found,
 * otherwise an array of array(selected module, depending module) if missing dependencies were found
 */
function check_module_depends($selected, $deps) {
	$ret = [];
	for ($m = 0; $m < count($selected); $m++) {  // check selected modules
		for ($i = 0; $i < count($deps[$selected[$m]]['depends']); $i++) {  // check dependencies of module
			// check if we have OR-combined modules
			if (is_array($deps[$selected[$m]]['depends'][$i])) {
				// one of the elements is needed
				$found = false;
				$depends = $deps[$selected[$m]]['depends'][$i];
				for ($d = 0; $d < count($depends); $d++) {
					if (in_array($depends[$d], $selected)) {
						$found = true;
						break;
					}
				}
				if (!$found) {
					// missing dependency, add to return value
					$ret[] = [$selected[$m], implode(" || ", $depends)];
				}
			}
			elseif (!in_array($deps[$selected[$m]]['depends'][$i], $selected)) {
				// single dependency
				// missing dependency, add to return value
				$ret[] = [$selected[$m], $deps[$selected[$m]]['depends'][$i]];
			}
		}
	}
	if ($ret !== []) {
		return $ret;
	}
	return false;
}

/**
 * Checks if there are conflicts between modules
 *
 * @param string[] $selected selected module names
 * @param array<string, array<string, array<string|string[]>>> $deps module dependencies
 * @return false|array<int, string[]> false if no conflict was found,
 * otherwise an array of array(selected module, conflicting module) if conflicts were found
 */
function check_module_conflicts($selected, $deps) {
	$ret = [];
	for ($m = 0; $m < count($selected); $m++) {
		for ($i = 0; $i < count($deps[$selected[$m]]['conflicts']); $i++) {
			if (in_array($deps[$selected[$m]]['conflicts'][$i], $selected)) {
				$ret[] = [$selected[$m], $deps[$selected[$m]]['conflicts'][$i]];
			}
		}
	}
	if ($ret !== []) {
		return $ret;
	}
	return false;
}

/**
 * Returns an array with all available user module names
 *
 * @param string $scope account type (user, group, host)
 * @param bool $mustSupportAdminInterface module must support LAM admin interface (default: false)
 * @return string[] list of possible modules
 */
function getAvailableModules($scope, bool $mustSupportAdminInterface = false): array {
	$dirname = substr(__FILE__, 0, strlen(__FILE__) - 12) . "/modules";
	$dir = dir($dirname);
	$return = [];
	// get module names.
	while ($entry = $dir->read()) {
		if ((substr($entry, strlen($entry) - 4, 4) === '.inc') && is_file($dirname . '/' . $entry)) {
			$entry = substr($entry, 0, strpos($entry, '.'));
			$temp = moduleCache::getModule($entry, $scope);
			if ($temp === null) {
				continue;
			}
			if ($mustSupportAdminInterface && !$temp->supportsAdminInterface()) {
				continue;
			}
			if ($temp->can_manage()) {
				$return[] = $entry;
			}
		}
	}
	return $return;
}

/**
 * Returns an array with all modules.
 *
 * @return baseModule[] list of modules
 */
function getAllModules(): array {
	$dirname = substr(__FILE__, 0, strlen(__FILE__) - 12) . "/modules";
	$dir = dir($dirname);
	$return = [];
	// get module names.
	while ($entry = $dir->read()) {
		if ((substr($entry, strlen($entry) - 4, 4) === '.inc') && is_file($dirname . '/' . $entry)) {
			$entry = substr($entry, 0, strpos($entry, '.'));
			$return[] = new $entry(null);
		}
	}
	return $return;
}

/**
 * Returns the elements for the profile page.
 *
 * @param string $typeId account type (user, group, host)
 * @return array<string, htmlResponsiveRow> profile elements
 */
function getProfileOptions(string $typeId): array {
	$typeManager = new TypeManager();
	$type = $typeManager->getConfiguredType($typeId);
	$mods = $type->getModules();
	$return = [];
	for ($i = 0; $i < count($mods); $i++) {
		$module = moduleCache::getModule($mods[$i], $type->getScope());
		$moduleOptions = $module->get_profileOptions($typeId);
		if ($moduleOptions !== null) {
			$return[$mods[$i]] = $moduleOptions;
		}
	}
	return $return;
}

/**
 * Checks if the profile options are valid
 *
 * @param string $typeId account type (user, group, host)
 * @param array<string, string[]> $options hash array containing all options (name => array(...))
 * @return array<string|string[]>[] list of error messages
 */
function checkProfileOptions($typeId, $options) {
	$typeManager = new TypeManager();
	$type = $typeManager->getConfiguredType($typeId);
	$mods = $type->getModules();
	$return = [];
	for ($i = 0; $i < count($mods); $i++) {
		$module = moduleCache::getModule($mods[$i], $type->getScope());
		$temp = $module->check_profileOptions($options, $type->getId());
		$return = array_merge($return, $temp);
	}
	return $return;
}

/**
 * Returns a hash array (module name => elements) of all module options for the configuration page.
 *
 * @param array<string, string[]> $moduleToScopes hash array (module name => array(account types))
 * @return array<class-string<baseModule>, htmlElement|htmlElement[]> configuration options
 */
function getConfigOptions(array $moduleToScopes): array {
	$return = [];
	foreach ($moduleToScopes as $module => $typeIds) {
		$m = moduleCache::getModule($module, getScopeFromTypeId($typeIds[0]));
		$return[$module] = $m->get_configOptions($typeIds, $moduleToScopes);
	}
	return $return;
}

/**
 * Checks if the configuration options are valid
 *
 * @param array<string, string[]> $moduleToTypeIds hash array (module name => array(account type ids))
 * @param array<string, string[]> $options hash array containing all options (name => array(...))
 * @return array<string|string[]>[] list of error messages
 */
function checkConfigOptions($moduleToTypeIds, &$options) {
	$return = [];
	foreach ($moduleToTypeIds as $module => $typeIds) {
		$m = moduleCache::getModule($module, getScopeFromTypeId($typeIds[0]));
		$errors = $m->check_configOptions($typeIds, $options);
		$return = array_merge($return, $errors);
	}
	return $return;
}

/**
 * Returns a help entry from an account module.
 *
 * @param string|null $module module name
 * @param string $helpID help identifier
 * @param string $scope account type
 * @return array<string, string>|null help entry
 */
function getHelp($module, $helpID, $scope): ?array {
	global $helpArray;
	if (in_array($module, [null, '', 'main'], true)) {
		if (!isset($helpArray)) {
			include_once(__DIR__ . '/../help/help.inc');
		}
		return $helpArray[$helpID];
	}
	$moduleObject = moduleCache::getModule($module, $scope);
	return $moduleObject->get_help($helpID);
}

/**
 * Returns a list of available PDF entries.
 *
 * @param string $typeId account type (user, group, host)
 * @return array<string, array<string, string>> PDF entries (field ID => field label)
 */
function getAvailablePDFFields(string $typeId): array {
	$typeManager = new TypeManager();
	$_SESSION['pdfContainer'] = new accountContainer($typeManager->getConfiguredType($typeId), 'pdfContainer');
	$_SESSION['pdfContainer']->initModules();
	$mods = $_SESSION['pdfContainer']->getAccountModules();
	$return = [];
	foreach ($mods as $module) {
		$fields = $module->get_pdfFields($typeId);
		$moduleName = $module::class;
		$return[$moduleName] = [];
		foreach ($fields as $fieldID => $fieldLabel) {
			$return[$moduleName][$fieldID] = $fieldLabel;
		}
	}
	$return['main'] = ['dn' => _('DN')];
	unset($_SESSION['pdfContainer']);
	return $return;
}

/**
 * Returns an array containing all input columns for the file upload.
 *
 * Syntax:
 * <br> array(
 * <br>  string: name,  // fixed non-translated name which is used as column name (should be of format: <module name>_<column name>)
 * <br>  string: description,  // short descriptive name
 * <br>  string: help,  // help ID
 * <br>  string: example,  // example value
 * <br>  boolean: required  // true, if user must set a value for this column
 * <br> )
 *
 * @param ConfiguredType $type account type
 * @param string[] $selectedModules selected account modules
 * @return array<string, array<string, string|bool>[]> column list
 */
function getUploadColumns(&$type, $selectedModules): array {
	$return = [];
	for ($i = 0; $i < count($selectedModules); $i++) {
		$module = moduleCache::getModule($selectedModules[$i], $type->getScope());
		$return[$selectedModules[$i]] = $module->get_uploadColumns($selectedModules, $type);
	}
	return $return;
}

/**
 * This function builds the LDAP accounts for the file upload.
 *
 * If there are problems status messages will be printed automatically.
 *
 * @param ConfiguredType $type account type
 * @param array<int, string>[] $data array containing one account in each element
 * @param array<string, int> $ids array(<column_name> => <column number>)
 * @param string[] $selectedModules selected account modules
 * @param htmlResponsiveRow $container HTML container
 * @return mixed array including accounts or false if there were errors
 */
function buildUploadAccounts($type, $data, $ids, $selectedModules, htmlResponsiveRow $container) {
	// build module order
	$unOrdered = $selectedModules;
	$ordered = [];
	$predepends = [];
	// get dependencies
	for ($i = 0; $i < count($unOrdered); $i++) {
		$mod = moduleCache::getModule($unOrdered[$i], $type->getScope());
		logNewMessage(LOG_DEBUG, 'Checking dependencies for ' . $unOrdered[$i]);
		$predepends[$unOrdered[$i]] = $mod->get_uploadPreDepends();
	}
	// first all modules without predepends can be ordered
	for ($i = 0; $i < count($unOrdered); $i++) {
		if (count($predepends[$unOrdered[$i]]) === 0) {
			$ordered[] = $unOrdered[$i];
			unset($unOrdered[$i]);
			$unOrdered = array_values($unOrdered);
			$i--;
		}
	}
	$unOrdered = array_values($unOrdered);  // fix indexes
	// now add all modules with fulfilled dependencies until all are in order
	while ($unOrdered !== []) {
		$newRound = false;
		for ($i = 0; $i < count($unOrdered); $i++) {
			$deps = $predepends[$unOrdered[$i]];
			$depends = false;
			for ($d = 0; $d < count($deps); $d++) {
				if (in_array($deps[$d], $unOrdered)) {
					$depends = true;
					break;
				}
			}
			if (!$depends) {  // add to order if dependencies are fulfilled
				$ordered[] = $unOrdered[$i];
				unset($unOrdered[$i]);
				$unOrdered = array_values($unOrdered);
				$newRound = true;
				break;
			}
		}
		if ($newRound) {
			continue;
		}
		// this point should never be reached, LAM was unable to find a correct module order
		$container->add(new htmlStatusMessage("ERROR", "Internal Error: Unable to find correct module order."), 12);
		return false;
	}
	// give raw data to modules
	$errors = [];
	$partialAccounts = [];
	foreach ($data as $i => $dataRow) {
		$partialAccounts[$i]['objectClass'] = [];
	}
	$stopUpload = false;
	for ($i = 0; $i < count($ordered); $i++) {
		if (!in_array(baseModule::class, class_parents($ordered[$i]))) {
			logNewMessage(LOG_WARNING, 'Invalid module name: ' . $ordered[$i]);
			continue;
		}
		$module = new $ordered[$i]($type->getScope());
		logNewMessage(LOG_DEBUG, 'Building data for ' . $ordered[$i]);
		$moduleErrors = $module->build_uploadAccounts($data, $ids, $partialAccounts, $selectedModules, $type);
		if (count($moduleErrors) > 0) {
			$errors = array_merge($errors, $moduleErrors);
			foreach ($moduleErrors as $error) {
				if ($error[0] == 'ERROR') {
					array_unshift($errors, ["INFO", _("Displayed account numbers start at \"0\". Add 2 to get the row in your spreadsheet."), ""]);
					$errors[] = ["ERROR", _("Upload was stopped after errors in %s module!"), "", [$module->get_alias()]];
					// skip other modules if error was found
					$stopUpload = true;
					break;
				}
			}
		}
		if ($stopUpload) {
			break;
		}
	}
	if ($errors !== []) {
		for ($i = 0; (($i < count($errors)) && ($i < 50)); $i++) {
			$text = empty($errors[$i][2]) ? null : $errors[$i][2];
			$values = empty($errors[$i][3]) ? null : $errors[$i][3];
			$container->add(new htmlStatusMessage($errors[$i][0], $errors[$i][1], $text, $values), 12);
		}
	}
	if ($stopUpload) {
		return false;
	}
	logNewMessage(LOG_DEBUG, 'Data built');
	return $partialAccounts;
}

/**
 * Runs any actions that need to be done before an LDAP entry is created.
 *
 * @param ConfiguredType $type account type
 * @param string[] $selectedModules list of selected account modules
 * @param array<string, string[]|string> $attributes LDAP attributes of this entry (attributes are provided as reference, handle modifications of $attributes with care)
 * @return array<string|string[]>[] array which contains status messages. Each entry is an array containing the status message parameters.
 */
function doUploadPreActions($type, $selectedModules, $attributes) {
	$messages = [];
	for ($i = 0; $i < count($selectedModules); $i++) {
		$activeModule = $selectedModules[$i];
		$module = moduleCache::getModule($activeModule, $type->getScope());
		$messages = array_merge($messages, $module->doUploadPreActions($attributes, $type));
	}
	return $messages;
}

/**
 * This function executes one post upload action.
 *
 * @param ConfiguredType $type account type
 * @param array<int, string>[] $data array containing one account in each element
 * @param array<string, int> $ids array(<column_name> => <column number>)
 * @param int[] $failed list of accounts which were not created successfully
 * @param string[] $selectedModules list of selected account modules
 * @param array<string, string[]|string>[] $accounts list of LDAP entries
 * @return array<string, string|int|string[]> current status
 * <br>array (
 * <br> 'status' => 'finished' | 'inProgress'
 * <br> 'module' => <name of active module>
 * <br> 'progress' => 0..100
 * <br> 'errors' => array (<array of parameters for StatusMessage>)
 * <br>)
 */
function doUploadPostActions($type, &$data, $ids, $failed, $selectedModules, &$accounts) {
	// check if function is called the first time
	if (!isset($_SESSION['mass_postActions']['remainingModules'])) {
		// make list of remaining modules
		$moduleList = $selectedModules;
		$_SESSION['mass_postActions']['remainingModules'] = $moduleList;
	}
	$activeModule = $_SESSION['mass_postActions']['remainingModules'][0];
	// initialize temporary variable
	if (!isset($_SESSION['mass_postActions'][$activeModule])) {
		$_SESSION['mass_postActions'][$activeModule] = [];
	}
	// let first module do one post action
	$module = moduleCache::getModule($activeModule, $type->getScope());
	$return = $module->doUploadPostActions($data, $ids, $failed, $_SESSION['mass_postActions'][$activeModule], $accounts, $selectedModules, $type);
	// remove active module from list if already finished
	if ($return['status'] == 'finished') {
		unset($_SESSION['mass_postActions']['remainingModules'][0]);
		$_SESSION['mass_postActions']['remainingModules'] = array_values($_SESSION['mass_postActions']['remainingModules']);
	}
	// update status and return back to upload page
	$return['module'] = $activeModule;
	$return['status'] = (count($_SESSION['mass_postActions']['remainingModules']) > 0) ? 'inProgress' : 'finished';
	return $return;
}

/**
 * Takes a list of meta-HTML elements and prints the equivalent HTML output.
 *
 * The modules are not allowed to display HTML code directly but return
 * meta HTML code. This allows to have a common design for all module pages.
 *
 * @param string|null $module Name of account module
 * @param htmlElement|htmlElement[]|null $input htmlElement or array of htmlElement elements
 * @param array<string, string[]> $values List of values which override the defaults in $input (name => value)
 * @param bool $restricted If true then no buttons will be displayed
 * @param string|null $scope Account type
 * @return array<string, string> list of input field names and their type (name => type)
 */
function parseHtml($module, $input, $values, $restricted, $scope) {
	if ($input === null) {
		return [];
	}
	if ($input instanceof htmlElement) {
		return $input->generateHTML($module, [$input], $values, $restricted, $scope);
	}
	if ($input !== []) {
		$return = [];
		for ($i = 0; $i < count($input); $i++) {
			$return = array_merge($return, $input[$i]->generateHTML($module, $input, $values, $restricted, $scope));
		}
		return $return;
	}
	return [];
}

/**
 * Prints a LAM help link.
 *
 * @param array<string, string> $entry help entry
 * @param string $number help number
 * @param string $module module name
 * @param string $scope account scope
 * @param string[] $classes CSS classes
 */
function printHelpLink($entry, $number, $module = '', $scope = '', $classes = []): void {
	$helpPath = "../";
	if (is_file("./help.php")) {
		$helpPath = "";
	}
	$title = $entry['Headline'];
	$message = $entry['Text'];
	if (isset($entry['attr'])) {
		$message .= '<br><br><hr class="dotted">' . _('Technical name') . ': <i>' . $entry['attr'] . '</i>';
	}
	// replace special characters
	$message = htmlspecialchars($message);
	$title = htmlspecialchars($title);
	$selfServiceOption = '';
	if (isSelfService()) {
		$selfServiceOption = '&amp;selfService=1';
	}
	echo "<a class=\"margin2 " . implode(" ", $classes) . "\" href=\"" . $helpPath . "help.php?module=$module&amp;HelpNumber=" . $number . "&amp;scope=" . $scope . $selfServiceOption . "\" ";
	echo "target=\"help\" tabindex=\"-1\">";
	echo "<img helptitle=\"" . $title . "\" helpdata=\"" . $message . "\" class=\"align-middle help-icon\" src=\"../{$helpPath}graphics/help.svg\" alt=\"" . _('Help') . "\" width=\"16\" height=\"16\">";
	echo "</a>";
}


/**
 * This class includes all modules and attributes of an account.
 *
 * @package modules
 */
class accountContainer {

	/**
	 * Constructor
	 *
	 * @param ConfiguredType $type account type
	 * @param string $base key in $_SESSION where this object is saved
	 */
	public function __construct(ConfiguredType $type, string $base) {
		$this->type = $type;
		$this->base = $base;
	}

	/**
	 * @var array<string, string[]|string>|string|null $attributes Array of all used attributes
	 *  Syntax is attribute => array ( objectClass => MUST or MAY, ...)
	 */
	public array|string|null $attributes = null;

	/**
	 * This variable stores the account type.
	 */
	private ConfiguredType $type;

	/** This is an array with all module objects
	 *
	 * @var baseModule[]|string modules
	 */
	private string|array $module;

	/** DN suffix of the account */
	public ?string $dnSuffix = null;

	/** @var string|null DN of account when it was loaded */
	public ?string $dn_orig = null;

	/** RDN attribute of this account */
	public ?string $rdn = null;

	/** DN of saved account */
	public ?string $finalDN = null;

	/** @var array<string, string[]|string>|string|null $attributes_orig original LDAP attributes when account was loaded from LDAP */
	public array|string|null $attributes_orig = null;

	/** @var string[]|null $order module order */
	private ?array $order = null;

	/** Name of accountContainer variable in session */
	private string $base;

	/** This variable stores the page number of the currently displayed page */
	private int $current_page = 0;

	/** This variable is set to the pagename of a subpage if it should be displayed */
	private string $subpage = 'attributes';

	/** True if this is a newly created account */
	public bool $isNewAccount = false;

	/** name of last loaded account profile */
	private string $lastLoadedProfile = '';

	/** @var string[]|null cache for existing OUs */
	private ?array $cachedOUs = null;

	/** icon in title bar */
	private ?htmlElement $titleBarIcon = null;
	/** main title in title bar */
	private ?string $titleBarTitle = null;
	/** subtitle in title bar */
	private string $titleBarSubtitle = '';
	/** password to send via mail */
	private ?string $sendPasswordViaMail = null;
	/** password to send via SMS */
	private ?string $sendPasswordViaSms = null;
	/** send password via mail to this alternate address */
	private ?string $sendPasswordViaMailAlternateAddress = null;

	/**
	 * @var array<string, string> additional attributes for pre/post actions
	 */
	private array $extraInfoAttributes = [];

	/**
	 * @var bool errors occurred after saving LDAP data (postModify scripts)
	 */
	private bool $postSaveErrorsOccurred = false;


	/**
	 * Returns the account module with the given class name
	 *
	 * @template T of baseModule
	 * @param class-string<T> $name class name (e.g. posixAccount)
	 * @return T|null account module
	 */
	public function getAccountModule(string $name): ?baseModule {
		return $this->module[$name] ?? null;
	}

	/**
	 * Returns the included account modules.
	 *
	 * @return baseModule[] modules
	 */
	public function getAccountModules() {
		return $this->module;
	}

	/**
	 * Returns the account type of this object (e.g. user, group, host).
	 *
	 * @return ConfiguredType account type
	 */
	public function get_type() {
		return $this->type;
	}

	/**
	 * Returns the session edit key for this container.
	 *
	 * @return string key
	 */
	public function getEditKey() {
		return $this->base;
	}

	/**
	 * This function is called when the user clicks on any button on the account pages.
	 * It prints the HTML code of each account page.
	 */
	public function continue_main(): void {
		$oldPage = $this->current_page;
		$oldSubpage = $this->subpage;
		$result = [];
		$errorsOccurred = false;
		$typeObject = $this->type->getBaseType();
		$profileLoaded = $this->loadProfileIfRequested();
		if ($this->subpage === '') {
			$this->subpage = 'attributes';
		}
		if (isset($_POST['accountContainerReset'])) {
			$result = $this->load_account($this->dn_orig);
		}
		elseif (isset($_POST['accountContainerDelete'])) {
			metaRefresh("../lists/deletelink.php?type=" . $this->type->getId() . "&DN='" . rawurlencode($this->dn_orig) . "'");
			unset($_SESSION[$this->base]);
			exit();
		}
		elseif (!$profileLoaded) {
			// change dn suffix
			$possibleOUs = $this->getOUs();
			if (!empty($_GET['suffix']) && in_array($_GET['suffix'], $possibleOUs)) {
				$this->dnSuffix = $_GET['suffix'];
			}
			if (!empty($_POST['accountContainerSuffix']) && in_array($_POST['accountContainerSuffix'], $possibleOUs)) {
				$this->dnSuffix = $_POST['accountContainerSuffix'];
			}
			// change RDN
			$rdnList = getRDNAttributes($this->type->getId());
			if (!empty($_POST['accountContainerRDN']) && in_array($_POST['accountContainerRDN'], $rdnList)) {
				$this->rdn = $_POST['accountContainerRDN'];
			}
			// create another account
			if (isset($_POST['accountContainerCreateAgain'])) {
				// open a fresh account page
				unset($_SESSION[$this->base]);
				metaRefresh("edit.php?type=" . $this->type->getId() . "&suffix=" . $this->dnSuffix);
				exit();
			}
			// reedit account
			if (isset($_POST['accountContainerBackToEdit'])) {
				// open a fresh account page
				unset($_SESSION[$this->base]);
				metaRefresh("edit.php?type=" . $this->type->getId() . "&DN=" . urlencode($this->finalDN));
				exit();
			}
			// back to account list
			if (isset($_POST['accountContainerBackToList'])) {
				// Return to the account list
				unset($_SESSION[$this->base]);
				metaRefresh("../lists/list.php?type=" . $this->type->getId() . '&accountEditBack=true');
				exit;
			}
			// create the PDF file
			if (isset($_POST['accountContainerCreatePDF'])) {
				metaRefresh('../lists/list.php?printPDF=1&type=' . $this->type->getId() . "&refresh=true&PDFSessionID=" . $this->base);
				exit;
			}
			// module actions
			if (($_POST !== []) && checkIfWriteAccessIsAllowed($this->type->getId())) {
				$result = call_user_func([&$this->module[$this->order[$this->current_page]], 'process_' . $this->subpage]);
				if (is_array($result)) {  // messages were returned, check for errors
					for ($i = 0; $i < count($result); $i++) {
						if ($result[$i][0] == 'ERROR') {
							$errorsOccurred = true;
							break;
						}
					}
				}
				$this->sortModules();
			}
			// run type post actions
			$typeObject->runEditPagePostAction($this);
			// save account
			if (!$errorsOccurred && isset($_POST['accountContainerSaveAccount'])) {
				// check if all modules are complete
				$modules = array_keys($this->module);
				$incompleteModules = [];
				foreach ($modules as $module) {
					if (!$this->module[$module]->module_complete()) {
						$incompleteModules[] = $this->module[$module]->get_alias();
					}
				}
				if ($incompleteModules !== []) {
					$result[] = ['INFO', _('Some required information is missing'),
						sprintf(_('Please set up all required attributes on page: %s'), implode(", ", $incompleteModules))];
				}
				else {
					// save account
					$saveMessages = $this->save_account();
					$saveOk = true;
					for ($i = 0; $i < count($saveMessages); $i++) {
						if ($saveMessages[$i][0] == 'ERROR') {
							$saveOk = false;
						}
					}
					if (!$saveOk) {
						$result = $saveMessages;
					}
					else {
						$this->printSuccessPage($saveMessages);
						return;
					}
				}
			}
		}
		// change to the next page
		if (is_array($result)) {  // messages were returned, check for errors
			for ($i = 0; $i < count($result); $i++) {
				if ($result[$i][0] == 'ERROR') {
					$errorsOccurred = true;
					break;
				}
			}
		}
		if (!$errorsOccurred) {
			// go to subpage of current module
			$postKeys = array_keys($_POST);
			for ($p = 0; $p < count($postKeys); $p++) {
				if (is_string($postKeys[$p]) && (str_starts_with($postKeys[$p], 'form_subpage_' . $this->order[$this->current_page]))) {
					$temp = substr($postKeys[$p], strlen($this->order[$this->current_page]) + 14);
					$temp = explode('_', $temp);
					if (count($temp) === 2) {
						$this->subpage = $temp[0];
					}
				}
			}
			for ($i = 0; $i < count($this->order); $i++) {
				if (isset($_POST['form_main_' . $this->order[$i]])) {
					if ($this->module[$this->order[$i]]->module_ready()) {
						$this->current_page = $i;
						$this->subpage = 'attributes';
					}
					else {
						StatusMessage('ERROR', _('The module %s is not yet ready.'),
							_('Please enter the account information on the other pages first.'),
							[$this->module[$this->order[$i]]->get_alias()]);
					}
				}
			}
		}
		if ($profileLoaded) {
			$profileName = $_POST['accountContainerSelectLoadProfile'];
			$result[] = ['INFO', _('Profile "%s" loaded.'), '<div class="hidden lam-dialog-msg" id="lam-make-default-profile-dlg">' . _('Setting saved') . '</div>' .
				'<a href="#" id="lam-make-default-profile" data-name="%s" data-typeid="%s" data-ok="%s">' . _('Click here to make this your default profile.') . '</a>', [$profileName, $profileName, $this->get_type()->getId(), _('Ok')]];
		}
		// update titles
		$this->titleBarIcon = $typeObject->buildAccountStatusIcon($this);
		$this->titleBarTitle = $typeObject->getTitleBarTitle($this);
		$this->titleBarSubtitle = $typeObject->getTitleBarSubtitle($this);
		// prints a module content page
		$this->printModuleContent($result);
		if (!$errorsOccurred && ($oldPage === $this->current_page) && ($oldSubpage === $this->subpage)
			&& isset($_POST['scrollPositionTop']) && get_preg($_POST['scrollPositionTop'], 'digit')
			&& isset($_POST['scrollPositionLeft']) && get_preg($_POST['scrollPositionLeft'], 'digit')) {
			// scroll to last position
			$scrollJs = new htmlJavaScript('window.lam.utility.restoreScrollPosition(' . $_POST['scrollPositionTop'] . ', ' . $_POST['scrollPositionLeft'] . ')');
			parseHtml(null, $scrollJs, [], false, $this->type->getScope());
		}
		$this->printPageFooter();
	}

	/**
	 * Prints the content part provided by the current module.
	 *
	 * @param array<string|string[]>[] $result list of messages
	 */
	private function printModuleContent(array $result): void {
		$this->printPageHeader();
		$this->printPasswordPromt();
		// display error messages
		for ($i = 0; $i < count($result); $i++) {
			call_user_func_array(StatusMessage(...), $result[$i]);
		}
		echo '<div id="passwordMessageArea"></div>';
		echo "<table class=\"lam-account-edit-table\">\n";
		echo "<tr><td style=\"padding: 5px 0px 0px 0px;\">\n";
		$this->printCommonControls();
		echo "</td></tr>\n";
		echo "<tr valign=\"top\"><td style=\"padding: 15px;\">";
		// print title bar
		$titleBarContainer = new htmlResponsiveRow();
		$titleBarContainer->setCSSClasses(['maxrow']);
		$titleGroup = new htmlGroup();
		if ($this->titleBarIcon !== null) {
			$titleGroup->addElement($this->titleBarIcon);
			$titleGroup->addElement(new htmlSpacer('1rem', null));
		}
		$titleBarTitleText = new htmlOutputText($this->titleBarTitle, false);
		$titleGroup->addElement($titleBarTitleText);
		$titleBarContainer->add(new htmlDiv(null, $titleGroup, ['titleBarTitle', 'text-left']), 12, 12, 4);
		$titleBarSubtitleText = new htmlOutputText($this->titleBarSubtitle, false);
		$titleBarContainer->add(new htmlDiv(null, $titleBarSubtitleText, ['titleBarSubtitle', 'responsiveLabel']), 12, 12, 8);
		$titleBarSuffixRdn = new htmlResponsiveRow();
		$titleBarSuffixRdn->add(new htmlHorizontalLine(), 12);
		// suffix
		$suffixList = [];
		foreach ($this->getOUs() as $suffix) {
			$suffixList[getAbstractDN($suffix)] = $suffix;
		}
		if (($this->dnSuffix != '') && !in_array_ignore_case($this->dnSuffix, $this->getOUs())) {
			$suffixList[getAbstractDN($this->dnSuffix)] = $this->dnSuffix;
		}
		$selectedSuffix = [$this->dnSuffix];
		$suffixSelect = new htmlResponsiveSelect('accountContainerSuffix', $suffixList, $selectedSuffix, _('Suffix'));
		$suffixSelect->setHasDescriptiveElements(true);
		$suffixSelect->setRightToLeftTextDirection(true);
		$suffixSelect->setShortLabel();
		$suffixSelect->setSortElements(false);
		$titleBarSuffixRdn->add($suffixSelect, 12, 12, 7);
		// RDN selection
		$rdnlist = getRDNAttributes($this->type->getId());
		$rdnSelect = new htmlResponsiveSelect('accountContainerRDN', $rdnlist, [$this->rdn], _('RDN identifier'), '400');
		$rdnSelect->setShortLabel();
		$rdnSelect->setSortElements(false);
		$titleBarSuffixRdn->add($rdnSelect, 12, 12, 5);
		$titleBarContainer->add($titleBarSuffixRdn);

		$titleBarDiv = new htmlDiv(null, $titleBarContainer, ['titleBar']);
		parseHtml(null, $titleBarDiv, [], false, $this->type->getScope());

		echo '<div id="lamVerticalTabs" class="lam-vertical-tab-container">';
		echo '<table class="lam-vertical-tabs fullwidth">';
		echo '<tr><td class="lam-vertical-tabs-navigation">';
		// tab menu
		$this->printModuleTabs();
		echo '</td><td style="vertical-align: top; width: 100%;">';
		echo "<div class=\"lam-vertical-tab-content fullwidth module-content-row\">\n";
		// content area
		// display html-code from modules
		try {
			$return = call_user_func([$this->module[$this->order[$this->current_page]], 'display_html_' . $this->subpage]);
		}
		catch (LAMException $e) {
			$return = new htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage());
		}
		parseHtml($this->order[$this->current_page], $return, [], false, $this->type->getScope());
		echo "</div>\n";
		echo '</td>';
		echo '</tr>';
		echo '</table>';
		echo "</div>\n";
		echo "</td></tr>\n";
		// Display rest of html-page
		echo "</table>\n";
	}

	/**
	 * Prints the input fields of the central password service.
	 */
	private function printPasswordPromt(): void {
		echo "<div id=\"passwordDialogOuter\" class=\"modal modal-pwd-options\">\n";
		echo "<div id=\"passwordDialog\" class=\"modal-content\">\n";
		$printContainer = false;
		$container = new htmlResponsiveRow();
		$container->setCSSClasses(['text-left']);
		$title = new htmlTitle(_('Set password'));
		$container->add($title);
		// password fields
		$pwdInput1 = new htmlResponsiveInputField(_('Password'), 'newPassword1', null, '404');
		$pwdInput1->setIsPassword(true, true);
		$container->add($pwdInput1);
		$pwdInput2 = new htmlResponsiveInputField(_('Repeat password'), 'newPassword2');
		$pwdInput2->setIsPassword(true);
		$pwdInput2->setSameValueFieldID('newPassword1');
		$container->add($pwdInput2);
		// print force password change option
		$forceChangeSupported = [];
		foreach ($this->module as $module) {
			if (($module instanceof passwordService) && $module->supportsForcePasswordChange()) {
				$forceChangeSupported[] = $module;
			}
		}
		if (!empty($forceChangeSupported)) {
			$container->addLabel(new htmlLabel('lamForcePasswordChange', _('Force password change')));
			$forcePwdGroup = new htmlGroup();
			$forcePwdGroup->addElement(new htmlInputCheckbox('lamForcePasswordChange', false));
			$forcePwdGroup->addElement(new htmlSpacer('1rem', null));
			foreach ($forceChangeSupported as $module) {
				$forcePwdGroup->addElement(new htmlImage('../../graphics/' . $module->getIcon(), '16px', '16px', $module->get_alias(), $module->get_alias()));
				$forcePwdGroup->addElement(new htmlSpacer('0.1rem', null));
			}
			$forcePwdGroup->addElement(new htmlHelpLink('406'));
			$container->addField($forcePwdGroup);
			$container->addVerticalSpacer('0.25rem');
		}
		if (isLAMProVersion() && (isset($this->attributes_orig['mail'][0]) || $this->anyModuleManagesMail())) {
			$pwdMailCheckbox = new htmlResponsiveInputCheckbox('lamPasswordChangeSendMail', false, _('Send via mail'), '407');
			$pwdMailCheckbox->setTableRowsToShow(['lamPasswordChangeMailAddress']);
			$container->add($pwdMailCheckbox);
			if ($_SESSION['config']->getLamProMailAllowAlternateAddress() != 'false') {
				$alternateMail = '';
				$pwdResetModule = $this->getAccountModule('passwordSelfReset');
				if ($pwdResetModule !== null) {
					$backupMail = $pwdResetModule->getBackupEmail();
					if (!empty($backupMail)) {
						$alternateMail = $pwdResetModule->getBackupEmail();
					}
				}
				$alternateMailInput = new htmlResponsiveInputField(_('Alternate recipient'), 'lamPasswordChangeMailAddress', $alternateMail, '410');
				$container->add($alternateMailInput);
			}
		}
		if (isLAMProVersion() && ($this->attributes_orig !== null) && (getSmsPhoneNumber($this->attributes_orig) !== null)) {
			$container->add(new htmlResponsiveInputCheckbox('lamPasswordChangeSendSms', false, _('Send via SMS'), '412'));
		}
		$container->addVerticalSpacer('0.25rem');
		// password modules
		$moduleContainer = new htmlGroup();
		foreach ($this->module as $name => $module) {
			if (($module instanceof passwordService) && $module->managesPasswordAttributes()) {
				$printContainer = true;
				$buttonImage = $module->getIcon();
				if ($buttonImage != null) {
					if (!(str_starts_with($buttonImage, 'http')) && !(str_starts_with($buttonImage, '/'))) {
						$buttonImage = '../../graphics/' . $buttonImage;
					}
					$moduleContainer->addElement(new htmlImage($buttonImage, '16px', '16px', getModuleAlias($name, $this->type->getScope())));
				}
				$moduleContainer->addElement(new htmlInputCheckbox('password_cb_' . $name, true));
				$moduleContainer->addElement(new htmlLabel('password_cb_' . $name, getModuleAlias($name, $this->type->getScope())));
				$moduleContainer->addElement(new htmlSpacer('10px', null));
			}
		}
		$container->add($moduleContainer);
		// buttons
		$container->addVerticalSpacer('1rem');
		$buttonGroup = new htmlGroup();
		$okButton = new htmlButton('changePwdOk', _('Ok'));
		$okButton->setCSSClasses(['lam-primary']);
		$okButton->setOnClick("passwordHandleInput('false', '../misc/ajax.php?function=passwordChange&editKey="
			. htmlspecialchars($this->base) . "', '" . getSecurityTokenName() . "', '" . getSecurityTokenValue()
			. "', '" . _('Ok') . "'); return false;");
		$buttonGroup->addElement($okButton);
		$randomButton = new htmlButton('changePwdRandom', _('Set random password'));
		$randomButton->setCSSClasses(['lam-secondary']);
		$randomButton->setOnClick("passwordHandleInput('true', '../misc/ajax.php?function=passwordChange&editKey="
			. htmlspecialchars($this->base) . "', '" . getSecurityTokenName() . "', '" . getSecurityTokenValue()
			. "', '" . _('Ok') . "'); return false;");
		$buttonGroup->addElement($randomButton);
		$cancelButton = new htmlButton('changePwdCancel', _('Cancel'));
		$cancelButton->setOnClick("document.querySelector('.modal-pwd-options').classList.remove('show-modal'); return false;");
		$buttonGroup->addElement($cancelButton);
		$container->add($buttonGroup);
		// generate HTML
		if ($printContainer) {
			parseHtml(null, $container, [], false, $this->type->getScope());
		}
		echo "</div>\n";
		echo "</div>\n";
	}

	/**
	 * Sets the new password in all selected account modules.
	 *
	 * @param array<string, string|string[]> $input input parameters
	 * @return array<string, bool|string> result
	 */
	public function setNewPassword($input): array {
		$password1 = $input['password1'];
		$password2 = $input['password2'];
		$random = $input['random'] === 'true';
		$modules = [];
		foreach ($input['modules'] as $moduleName) {
			$moduleName = str_replace('password_cb_', '', $moduleName);
			if (array_key_exists($moduleName, $this->module)) {
				$modules[] = $moduleName;
			}
		}
		$return = [
			'messages' => '',
			'errorsOccurred' => 'false'
		];
		$sendMail = isset($input['sendMail']) && ($input['sendMail'] == 'true');
		$sendSms = isset($input['sendSms']) && ($input['sendSms'] == 'true');
		if ($random) {
			$password1 = generateRandomPassword();
			if (!$sendMail && !$sendSms) {
				$return['messages'] .= StatusMessage('INFO', _('The password was set to:') . ' ' . htmlspecialchars($password1), '', [], true);
			}
		}
		else {
			// check if passwords match
			if ($password1 != $password2) {
				$return['messages'] .= StatusMessage('ERROR', _('Passwords are different!'), '', [], true);
				$return['errorsOccurred'] = 'true';
			}
			// check password strength
			$pwdPolicyResult = checkPasswordStrength($password1, null, []);
			if (!$pwdPolicyResult->isValid()) {
				$return['messages'] .= StatusMessage('ERROR', $pwdPolicyResult->getTextMessage(), '', [], true);
				$return['errorsOccurred'] = 'true';
			}
		}
		$forcePasswordChange = false;
		if (isset($input['forcePasswordChange']) && ($input['forcePasswordChange'] == 'true')) {
			$forcePasswordChange = true;
		}
		$return['forcePasswordChange'] = $forcePasswordChange;
		if ($return['errorsOccurred'] === 'false') {
			// set new password
			foreach ($this->module as $module) {
				if ($module instanceof passwordService) {
					$messages = $module->passwordChangeRequested($password1, $modules, $forcePasswordChange);
					for ($m = 0; $m < count($messages); $m++) {
						if ($messages[$m][0] == 'ERROR') {
							$return['errorsOccurred'] = 'true';
						}
						if (count($messages[$m]) === 2) {
							$return['messages'] .= StatusMessage($messages[$m][0], $messages[$m][1], '', [], true);
						}
						elseif (count($messages[$m]) === 3) {
							$return['messages'] .= StatusMessage($messages[$m][0], $messages[$m][1], $messages[$m][2], [], true);
						}
						elseif (count($messages[$m]) === 4) {
							$return['messages'] .= StatusMessage($messages[$m][0], $messages[$m][1], $messages[$m][2], $messages[$m][3], true);
						}
					}
				}
			}
		}
		if (isLAMProVersion() && $sendMail) {
			$this->sendPasswordViaMail = $password1;
			if (($_SESSION['config']->getLamProMailAllowAlternateAddress() != 'false') && !empty($input['sendMailAlternateAddress'])) {
				if (!get_preg($input['sendMailAlternateAddress'], 'email')) {
					$return['messages'] .= StatusMessage('ERROR', _('Alternate recipient'), _('Please enter a valid email address!'), [], true);
					$return['errorsOccurred'] = 'true';
				}
				$this->sendPasswordViaMailAlternateAddress = $input['sendMailAlternateAddress'];
			}
		}
		if (isLAMProVersion() && $sendSms) {
			$this->sendPasswordViaSms = $password1;
		}
		if ($return['errorsOccurred'] === 'false') {
			$return['messages'] .= StatusMessage('INFO', _('The new password will be stored in the directory after you save this account.'), '', [], true);
			$this->extraInfoAttributes['INFO.passwordUpdated'] = 'yes';
			$this->extraInfoAttributes['INFO.forcePasswordChange'] = $forcePasswordChange ? 'yes' : 'no';
			$this->extraInfoAttributes['INFO.passwordChangeModules'] = implode(', ', $modules);
			$this->extraInfoAttributes['INFO.passwordChangeType'] = $random ? 'random' : 'manual';
			$this->extraInfoAttributes['INFO.sendPasswordViaEmail'] = $sendMail ? 'yes' : 'no';
			$this->extraInfoAttributes['INFO.sendPasswordViaSms'] = $sendSms ? 'yes' : 'no';
			if (!empty($input['sendMailAlternateAddress'])) {
				$this->extraInfoAttributes['INFO.sendPasswordAlternateAddress'] = $input['sendMailAlternateAddress'];
			}
		}
		return $return;
	}

	/**
	 * Returns if any module manages the mail attribute.
	 *
	 * @return boolean mail is managed
	 */
	private function anyModuleManagesMail() {
		foreach ($this->module as $mod) {
			if (in_array('mail', $mod->getManagedAttributes($this->get_type()->getId()))) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Prints common controls like the save button and the ou selection.
	 */
	private function printCommonControls(): void {
		$row = new htmlResponsiveRow();
		$row->setCSSClasses(['maxrow']);
		$leftButtonGroup = new htmlGroup();
		$leftButtonGroup->alignment = htmlElement::ALIGN_LEFT;
		if (checkIfWriteAccessIsAllowed($this->type->getId()) && !$this->postSaveErrorsOccurred) {
			// save button
			$saveButton = new htmlButton('accountContainerSaveAccount', _('Save'));
			$saveButton->setCSSClasses(['fullwidth-mobile-only lam-primary']);
			$leftButtonGroup->addElement($saveButton);
			// set password button
			if ($this->showSetPasswordButton()) {
				$leftButtonGroup->addElement(new htmlSpacer('15px', null, ['hide-on-mobile']));
				$passwordButton = new htmlButton('accountContainerPassword', _('Set password'));
				$passwordButton->setCSSClasses(['fullwidth-mobile-only lam-secondary']);
				$passwordButton->setOnClick("window.lam.dialog.showModal('.modal-pwd-options');");
				$leftButtonGroup->addElement($passwordButton);
			}
			// delete button
			if (!$this->isNewAccount && checkIfDeleteEntriesIsAllowed($this->get_type()->getId())) {
				$leftButtonGroup->addElement(new htmlSpacer('15px', null, ['hide-on-mobile']));
				$deleteButton = new htmlButton('accountContainerDelete', _('Delete'));
				$deleteButton->setCSSClasses(['fullwidth-mobile-only lam-danger']);
				$leftButtonGroup->addElement($deleteButton);
			}
			$leftButtonGroup->addElement(new htmlSpacer('15px', null, ['hide-on-mobile']));
			// reset button
			if (!$this->isNewAccount) {
				$resetButton = new htmlButton('accountContainerReset', _('Reset changes'));
				$resetButton->setCSSClasses(['fullwidth-mobile-only']);
				$leftButtonGroup->addElement($resetButton);
			}
		}
		$type = $this->type->getBaseType();
		$backToListButton = new htmlButton('accountContainerBackToList', $type->LABEL_BACK_TO_ACCOUNT_LIST);
		$backToListButton->setCSSClasses(['fullwidth-mobile-only']);
		$leftButtonGroup->addElement($backToListButton);
		$row->add($leftButtonGroup, 12, 9);

		$rightGroup = new htmlGroup();
		if (checkIfWriteAccessIsAllowed($this->type->getId()) && !$this->postSaveErrorsOccurred) {
			// profile selection
			$accountProfilePersistenceManager = new AccountProfilePersistenceManager();
			$profilelist = $accountProfilePersistenceManager->getAccountProfileNames($this->type->getId(), $_SESSION['config']->getName());
			if (count($profilelist) > 0) {
				$profileButton = new htmlButton('accountContainerLoadProfileButton', _('Load profile'));
				$profileButton->setOnClick('confirmLoadProfile(\'' . _('Load profile') . '\', \'' . _('This may overwrite existing values with profile data. Continue?') . '\','
					. ' \'' . _('Ok') . '\', \'' . _('Cancel') . '\', event); return false;');
				$profileButton->addDataAttribute('lastprofile', $this->lastLoadedProfile);
				$profileListOptions = [];
				foreach ($profilelist as $profileName) {
					$profileListOptions[$profileName] = $profileName;
				}
				$profileButton->addDataAttribute('profiles', json_encode($profileListOptions));
				$rightGroup->addElement($profileButton);
				$rightGroup->addElement(new htmlSpacer('1px', null));
				$rightGroup->addElement(new htmlHelpLink('401'));
			}
		}
		$row->add($rightGroup, 12, 3, 3, 'text-right');

		parseHtml(null, $row, [], false, $this->type->getScope());
	}

	/**
	 * Returns if the page should show a button to set the password.
	 *
	 * @return bool show or hide button
	 */
	private function showSetPasswordButton(): bool {
		foreach ($this->module as $module) {
			if (($module instanceof passwordService) && $module->managesPasswordAttributes()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Prints the header of the account pages.
	 */
	private function printPageHeader(): void {
		if (!empty($_POST)) {
			validateSecurityToken();
		}
		include __DIR__ . '/adminHeader.inc';
		echo "<form id=\"inputForm\" enctype=\"multipart/form-data\" action=\"edit.php?editKey=" . htmlspecialchars($this->base) . "\" method=\"post\" onSubmit=\"window.lam.utility.saveScrollPosition('inputForm')\" autocomplete=\"off\" novalidate=\"novalidate\">\n";
		echo '<input type="hidden" name="' . getSecurityTokenName() . '" value="' . getSecurityTokenValue() . '">';
	}

	/**
	 * Prints the footer of the account pages.
	 */
	private function printPageFooter(): void {
		echo "</form>\n";
		include __DIR__ . '/adminFooter.inc';
	}

	/**
	 * Prints the HTML code to notify the user about the successful saving.
	 *
	 * @param array<string|string[]>[] $messages array which contains status messages. Each entry is an array containing the status message parameters.
	 */
	private function printSuccessPage($messages): void {
		$this->printPageHeader();
		// Show success message
		$text = ($this->dn_orig == '') ? _("Account was created successfully.") : _("Account was modified successfully.");
		echo "<div smallPaddingContent\">";

		$container = new htmlResponsiveRow();
		$container->addVerticalSpacer('2rem');
		// show messages
		for ($i = 0; $i < count($messages); $i++) {
			if (count($messages[$i]) === 2) {
				$message = new htmlStatusMessage($messages[$i][0], $messages[$i][1]);
				$container->add($message);
			}
			else {
				$message = new htmlStatusMessage($messages[$i][0], $messages[$i][1], $messages[$i][2]);
				$container->add($message);
			}
		}
		$message = new htmlStatusMessage('INFO', _('LDAP operation successful.'), $text);
		$container->add($message);
		$container->addVerticalSpacer('2rem');

		$type = $this->type->getBaseType();
		$buttonGroup = new htmlGroup();
		$backToListButton = new htmlButton('accountContainerBackToList', $type->LABEL_BACK_TO_ACCOUNT_LIST);
		$backToListButton->setCSSClasses(['lam-primary fullwidth-mobile-only']);
		$buttonGroup->addElement($backToListButton);
		$buttonGroup->addElement(new htmlSpacer('1rem', null));
		if (checkIfNewEntriesAreAllowed($this->type->getId())) {
			$createButton = new htmlButton('accountContainerCreateAgain', $type->LABEL_CREATE_ANOTHER_ACCOUNT);
			$createButton->setCSSClasses(['lam-secondary fullwidth-mobile-only']);
			$buttonGroup->addElement($createButton);
			$buttonGroup->addElement(new htmlSpacer('0.5rem', null));
		}
		$pdfStructurePersistenceManager = new PdfStructurePersistenceManager();
		$pdfStructures = $pdfStructurePersistenceManager->getPDFStructures($_SESSION['config']->getName(), $this->type->getId());
		if ($pdfStructures) {
			$pdfButton = new htmlButton('accountContainerCreatePDF', _('Create PDF file'));
			$pdfButton->setCSSClasses(['lam-secondary fullwidth-mobile-only']);
			$buttonGroup->addElement($pdfButton);
			$buttonGroup->addElement(new htmlSpacer('1rem', null));
		}
		$backToEditButton = new htmlButton('accountContainerBackToEdit', _('Edit again'));
		$backToEditButton->setCSSClasses(['fullwidth-mobile-only']);
		$buttonGroup->addElement($backToEditButton);
		$container->add($buttonGroup);

		parseHtml(null, $container, [], false, $this->type->getScope());

		echo "</div>\n";
		$this->printPageFooter();
	}

	/**
	 * Checks if the user requested to load a profile.
	 *
	 * @return bool true, if profile was loaded
	 */
	private function loadProfileIfRequested(): bool {
		if (isset($_POST['accountContainerLoadProfile']) && isset($_POST['accountContainerSelectLoadProfile'])) {
			$accountProfilePersistenceManager = new AccountProfilePersistenceManager();
			$profile = $accountProfilePersistenceManager->loadAccountProfile($this->type->getId(), $_POST['accountContainerSelectLoadProfile'], $_SESSION['config']->getName());
			$this->lastLoadedProfile = $_POST['accountContainerSelectLoadProfile'];
			// pass profile to each module
			$modules = array_keys($this->module);
			foreach ($modules as $module) {
				$this->module[$module]->load_profile($profile);
			}
			if (isset($profile['ldap_rdn'][0])
				&& in_array($profile['ldap_rdn'][0], getRDNAttributes($this->type->getId()))) {
				$this->rdn = $profile['ldap_rdn'][0];
			}
			if (isset($profile['ldap_suffix'][0]) && ($profile['ldap_suffix'][0] != '-')) {
				$this->dnSuffix = $profile['ldap_suffix'][0];
			}
			return true;
		}
		return false;
	}

	/**
	 * Prints the HTML code of the module tabs.
	 */
	private function printModuleTabs(): void {
		echo '<ul class="lam-vertical-tabs-navigation">';
		// Loop for each module
		for ($i = 0; $i < count($this->order); $i++) {
			$buttonStatus = $this->module[$this->order[$i]]->getButtonStatus();
			$alias = $this->module[$this->order[$i]]->get_alias();
			// skip hidden buttons
			if ($buttonStatus == 'hidden') {
				continue;
			}
			$buttonImage = $this->module[$this->order[$i]]->getIcon();
			$activatedClass = '';
			if ($this->order[$this->current_page] == $this->order[$i]) {
				$activatedClass = ' lam-vertical-tabs-selected';
			}
			// print button
			echo '<li class="lam-vertical-tabs ' . $activatedClass . '">';
			echo "<button class=\"lam-account-type " . $activatedClass . "\" name=\"form_main_" . $this->order[$i] . "\"";
			if ($buttonStatus == 'disabled') {
				echo " disabled";
			}
			echo ' >';
			if ($buttonImage != null) {
				if (!(str_starts_with($buttonImage, 'http')) && !(str_starts_with($buttonImage, '/'))) {
					$buttonImage = '../../graphics/' . $buttonImage;
				}
				echo "<img height=32 width=32 class=\"align-middle\" style=\"padding: 3px;\" alt=\"\" src=\"$buttonImage\">&nbsp;";
			}
			echo '<span class="hide-on-mobile">';
			echo $alias;
			echo '<span>';
			echo "</button>\n";
			echo "</li>\n";
		}
		echo '</ul>';
	}

	/**
	 * This function checks which LDAP attributes have changed while the account was edited.
	 *
	 * @param array<string, string[]|string> $attributes list of current LDAP attributes
	 * @param array<string, string[]|string> $orig list of old attributes when account was loaded
	 * @return array<string, array<string, array<string, string[]>>> an array which can be passed to $this->saveAccount()
	 */
	public function save_module_attributes($attributes, $orig): array {
		$return = [];
		$toModify = [];
		$notChanged = [];
		// cleanup
		foreach ($attributes as $name => &$values) {
			// remove empty values
			$values = array_values($values);
			for ($i = 0; $i < count($values); $i++) {
				if ($values[$i] === '') {
					unset($values[$i]);
				}
			}
			$values = array_values($values);
			// remove empty list of values
			if (count($values) === 0) {
				unset($attributes[$name]);
			}
		}
		// find deleted attributes (in $orig but no longer in $attributes)
		foreach ($orig as $name => $value) {
			if (count($value) === 0) {
				continue;
			}
			if (!isset($attributes[$name]) || (count($attributes[$name]) === 0)) {
				$toModify[$name] = [];
			}
		}
		// find changed attributes
		foreach ($attributes as $name => $value) {
			// new/changed attributes
			if ((!isset($orig[$name]) && (count($value) !== 0))
				|| (isset($orig[$name]) && !areArrayContentsEqual($value, $orig[$name]))) {
				$toModify[$name] = $value;
			}
			// unchanged attributes
			else {
				$notChanged[$name] = $value;
			}
		}
		if ($toModify !== []) {
			$return[$this->dn_orig]['modify'] = $toModify;
		}
		if ($notChanged !== []) {
			$return[$this->dn_orig]['notchanged'] = $notChanged;
		}
		return $return;
	}

	/**
	 * Loads an LDAP account with the given DN.
	 *
	 * @param string $dn the DN of the account
	 * @param array<string, string> $infoAttributes list of additional informational attributes that are added to the LDAP attributes
	 * E.g. this is used to inject the clear text password in the file upload. Informational attribute names must start with "INFO.".
	 * @return array<string|string[]>[] error messages
	 */
	public function load_account($dn, $infoAttributes = []): array {
		if (!str_ends_with(strtolower($dn), strtolower($this->type->getSuffix()))) {
			logNewMessage(LOG_ERR, 'User tried to access entry of type ' . $this->type->getId() . ' outside suffix ' . $this->type->getSuffix());
			die();
		}
		logNewMessage(LOG_DEBUG, "Edit account " . $dn);
		$this->extraInfoAttributes['INFO.isNewAccount'] = 'no';
		$this->extraInfoAttributes['INFO.passwordUpdated'] = 'no';
		$this->extraInfoAttributes['INFO.passwordChangeType'] = 'none';
		$this->module = [];
		$modules = $_SESSION['config']->get_AccountModules($this->type->getId());
		$filter = empty($this->type->getAdditionalLdapFilter()) ? '(objectClass=*)' : $this->type->getAdditionalLdapFilter();
		$searchAttrs = ['*', '+'];
		foreach ($modules as $module) {
			$modTmp = new $module($this->type->getScope());
			$searchAttrs = array_merge($searchAttrs, $modTmp->getManagedHiddenAttributes($this->type->getId()));
		}
		$result = @ldap_read($_SESSION['ldap']->server(), $dn, $filter, $searchAttrs, 0, 0, 0, LDAP_DEREF_NEVER);
		if (!$result) {
			return [["ERROR", _("Unable to load LDAP entry:") . " " . htmlspecialchars($dn), getDefaultLDAPErrorString($_SESSION['ldap']->server())]];
		}
		$entry = @ldap_first_entry($_SESSION['ldap']->server(), $result);
		if (!$entry) {
			return [["ERROR", _("Unable to load LDAP entry:") . " " . htmlspecialchars($dn), getDefaultLDAPErrorString($_SESSION['ldap']->server())]];
		}
		$this->dnSuffix = extractDNSuffix($dn);
		$this->dn_orig = $dn;
		// extract RDN
		$this->rdn = extractRDNAttribute($dn);
		$attr = ldap_get_attributes($_SESSION['ldap']->server(), $entry);
		$attr = [$attr];
		cleanLDAPResult($attr);
		$attr = $attr[0];
		// fix spelling errors
		$attr = $this->fixLDAPAttributes($attr, $modules);
		// get binary attributes
		$binaryAttr = ['jpegPhoto'];
		for ($i = 0; $i < count($binaryAttr); $i++) {
			if (isset($attr[$binaryAttr[$i]][0])) {
				$binData = ldap_get_values_len($_SESSION['ldap']->server(), $entry, $binaryAttr[$i]);
				unset($binData['count']);
				$attr[$binaryAttr[$i]] = $binData;
			}
		}
		// add informational attributes
		$attr = array_merge($attr, $infoAttributes);
		// save original attributes
		$this->attributes_orig = $attr;

		foreach ($modules as $module) {
			if (!isset($this->module[$module])) {
				$this->module[$module] = new $module($this->type->getScope());
				$this->module[$module]->init($this->base);
			}
			$this->module[$module]->load_attributes($attr);
		}

		// sort module buttons
		$this->sortModules();
		// get titles
		$typeObject = $this->type->getBaseType();
		$this->titleBarIcon = $typeObject->buildAccountStatusIcon($this);
		$this->titleBarTitle = $typeObject->getTitleBarTitle($this);
		$this->titleBarSubtitle = $typeObject->getTitleBarSubtitle($this);
		return [];
	}

	/**
	 * Fixes spelling errors in the attribute names.
	 *
	 * @param array<string, string[]|string>|null $attributes LDAP attributes
	 * @param string[] $modules list of active modules
	 * @return array<string, string[]|string> fixed attributes
	 */
	public function fixLDAPAttributes($attributes, $modules): array {
		if (!is_array($attributes)) {
			return [];
		}
		$keys = array_keys($attributes);
		// get correct object class names, aliases and attributes
		$objectClasses = [];
		$aliases = [];
		$ldapAttributesTemp = [];
		foreach ($modules as $module) {
			$moduleObj = moduleCache::getModule($module, $this->type->getScope());
			$objectClasses = array_merge($objectClasses, $moduleObj->getManagedObjectClasses($this->type->getId()));
			$aliases = array_merge($aliases, $moduleObj->getLDAPAliases($this->type->getId()));
			$ldapAttributesTemp = array_merge($ldapAttributesTemp,
				$moduleObj->getManagedAttributes($this->type->getId()),
				$moduleObj->getManagedHiddenAttributes($this->type->getId()));
		}
		// build lower-case attribute names
		$ldapAttributes = [];
		for ($i = 0; $i < count($ldapAttributesTemp); $i++) {
			$ldapAttributes[strtolower($ldapAttributesTemp[$i])] = $ldapAttributesTemp[$i];
		}
		$ldapAttributesKeys = array_keys($ldapAttributes);
		// convert alias names to lower-case (for easier comparison)
		$aliasKeys = array_keys($aliases);
		for ($i = 0; $i < count($aliasKeys); $i++) {
			if ($aliasKeys[$i] != strtolower($aliasKeys[$i])) {
				$aliases[strtolower($aliasKeys[$i])] = $aliases[$aliasKeys[$i]];
				unset($aliases[$aliasKeys[$i]]);
				$aliasKeys[$i] = strtolower($aliasKeys[$i]);
			}
		}
		// fix object classes and attributes
		for ($i = 0; $i < count($keys); $i++) {
			// check object classes
			if (strtolower($keys[$i]) === 'objectclass') {
				// fix object class attribute
				if ($keys[$i] != 'objectClass') {
					$temp = $attributes[$keys[$i]];
					unset($attributes[$keys[$i]]);
					$attributes['objectClass'] = $temp;
				}
				// fix object classes
				for ($attrClass = 0; $attrClass < count($attributes['objectClass']); $attrClass++) {
					for ($modClass = 0; $modClass < count($objectClasses); $modClass++) {
						if (strtolower($attributes['objectClass'][$attrClass]) === strtolower($objectClasses[$modClass])) {
							if ($attributes['objectClass'][$attrClass] != $objectClasses[$modClass]) {
								unset($attributes['objectClass'][$attrClass]);
								$attributes['objectClass'][] = $objectClasses[$modClass];
							}
							break;
						}
					}
				}
			}
			elseif (in_array(strtolower($keys[$i]), $aliasKeys)) {
				// fix aliases
				$attributes[$aliases[strtolower($keys[$i])]] = $attributes[$keys[$i]];
				unset($attributes[$keys[$i]]);
			}
			elseif (in_array(strtolower($keys[$i]), $ldapAttributesKeys)) {
				if ($keys[$i] != $ldapAttributes[strtolower($keys[$i])]) {
					$attributes[$ldapAttributes[strtolower($keys[$i])]] = $attributes[$keys[$i]];
					unset($attributes[$keys[$i]]);
				}
			}
		}
		return $attributes;
	}

	/**
	 * This function will prepare the object for a new account.
	 */
	public function new_account(): void {
		logNewMessage(LOG_DEBUG, "New account with type " . $this->type->getId());
		$this->isNewAccount = true;
		$this->lastLoadedProfile = 'default';
		$this->initModules();
		$this->extraInfoAttributes['INFO.isNewAccount'] = 'yes';
		$this->extraInfoAttributes['INFO.passwordUpdated'] = 'no';
		// sort module buttons
		$this->sortModules();
		$profileName = 'default';
		$profileCookieKey = 'defaultProfile_' . $this->get_type()->getId();
		try {
			$accountProfilePersistenceManager = new AccountProfilePersistenceManager();
			if (!empty($_COOKIE[$profileCookieKey])) {
				$cookieProfileName = $_COOKIE[$profileCookieKey];
				if ($accountProfilePersistenceManager->isAccountProfileExisting($this->get_type()->getId(), $cookieProfileName, $_SESSION['config']->getName())) {
					$profileName = $cookieProfileName;
					$this->lastLoadedProfile = $cookieProfileName;
				}
			}
			$profile = $accountProfilePersistenceManager->loadAccountProfile($this->type->getId(), $profileName, $_SESSION['config']->getName());
			// pass profile to each module
			$modules = array_keys($this->module);
			foreach ($modules as $module) {
				$this->module[$module]->load_profile($profile);
			}
			if (isset($profile['ldap_rdn'][0]) && in_array($profile['ldap_rdn'][0], getRDNAttributes($this->type->getId()))) {
				$this->rdn = $profile['ldap_rdn'][0];
			}
			if (isset($profile['ldap_suffix'][0]) && ($profile['ldap_suffix'][0] != '-')) {
				$this->dnSuffix = $profile['ldap_suffix'][0];
			}
		}
		catch (LAMException $e) {
			logNewMessage(LOG_ERR, $e->getTitle());
		}
		// get titles
		$typeObject = $this->type->getBaseType();
		$this->titleBarIcon = $typeObject->buildAccountStatusIcon($this);
		$this->titleBarTitle = $typeObject->getTitleBarTitle($this);
		$this->titleBarSubtitle = $typeObject->getTitleBarSubtitle($this);
	}

	/**
	 * Copies the data from the given account to this one.
	 *
	 * @param string $copyDn DN to copy from
	 */
	public function copyFromExistingAccount(string $copyDn): void {
		$copyData = ldapGetDN($copyDn, ['*', '+']);
		$modules = $_SESSION['config']->get_AccountModules($this->type->getId());
		$copyData = $this->fixLDAPAttributes($copyData, $modules);
		foreach ($this->module as $accountModule) {
			$accountModule->loadAttributesFromAccountCopy($copyData);
		}
	}

	/**
	 * Creates the account modules and initializes them.
	 */
	public function initModules(): void {
		$modules = $_SESSION['config']->get_AccountModules($this->type->getId());
		foreach ($modules as $module) {
			$this->module[$module] = new $module($this->type->getScope());
			$this->module[$module]->init($this->base);
		}
	}

	/**
	 * This function will save an account to the LDAP database.
	 *
	 * @return array<string|string[]>[] list of status messages
	 */
	private function save_account(): array {
		if (!checkIfWriteAccessIsAllowed($this->type->getId())) {
			die();
		}
		$this->finalDN = $this->dn_orig;
		$errors = [];
		$module = array_keys($this->module);
		$attributes = [];
		// load attributes
		foreach ($module as $singlemodule) {
			// load changes
			$temp = $this->module[$singlemodule]->save_attributes();
			// merge changes
			$DNs = array_keys($temp);
			$attributes = array_merge_recursive($temp, $attributes);
			for ($i = 0; $i < count($DNs); $i++) {
				$ops = array_keys($temp[$DNs[$i]]);
				for ($j = 0; $j < count($ops); $j++) {
					$attrs = array_keys($temp[$DNs[$i]][$ops[$j]]);
					for ($k = 0; $k < count($attrs); $k++) {
						$attributes[$DNs[$i]][$ops[$j]][$attrs[$k]] = array_values(array_unique($attributes[$DNs[$i]][$ops[$j]][$attrs[$k]]));
					}
				}
			}
		}
		// build DN for new accounts and change it for existing ones if needed
		if (isset($attributes[$this->dn_orig]['modify'][$this->rdn][0])) {
			$this->finalDN = $this->rdn . '=' . ldap_escape($attributes[$this->dn_orig]['modify'][$this->rdn][0], '', LDAP_ESCAPE_DN) . ',' . $this->dnSuffix;
			if ($this->dn_orig != $this->finalDN) {
				$attributes[$this->finalDN] = $attributes[$this->dn_orig];
				unset($attributes[$this->dn_orig]);
			}
		}
		elseif (isset($attributes[$this->dn_orig]['add'][$this->rdn][0])) {
			$this->finalDN = $this->rdn . '=' . ldap_escape($attributes[$this->dn_orig]['add'][$this->rdn][0], '', LDAP_ESCAPE_DN) . ',' . $this->dnSuffix;
			if ($this->dn_orig != $this->finalDN) {
				$attributes[$this->finalDN] = $attributes[$this->dn_orig];
				unset($attributes[$this->dn_orig]);
			}
		}
		elseif (isset($attributes[$this->dn_orig]['remove'][$this->rdn][0]) && isset($attributes[$this->dn_orig]['notchanged'][$this->rdn][0])) {
			$this->finalDN = $this->rdn . '=' . ldap_escape($attributes[$this->dn_orig]['notchanged'][$this->rdn][0], '', LDAP_ESCAPE_DN) . ',' . $this->dnSuffix;
			if ($this->dn_orig != $this->finalDN) {
				$attributes[$this->finalDN] = $attributes[$this->dn_orig];
				unset($attributes[$this->dn_orig]);
			}
		}
		elseif (!$this->isNewAccount && (($this->dnSuffix != extractDNSuffix($this->dn_orig)) || ($this->rdn != extractRDNAttribute($this->dn_orig)))) {
			$this->finalDN = $this->rdn . '=' . ldap_escape($attributes[$this->dn_orig]['notchanged'][$this->rdn][0], '', LDAP_ESCAPE_DN) . ',' . $this->dnSuffix;
			$attributes[$this->finalDN] = $attributes[$this->dn_orig];
			unset($attributes[$this->dn_orig]);
		}
		// remove pwdAccountLockedTime attribute change if also userPassword is changed (PPolicy will remove this attribute itself)
		if (isset($attributes[$this->finalDN]['modify']['userpassword']) || isset($attributes[$this->finalDN]['remove']['userpassword'])) {
			if (isset($attributes[$this->finalDN]['modify']['pwdAccountLockedTime'])) {
				unset($attributes[$this->finalDN]['modify']['pwdAccountLockedTime']);
			}
			if (isset($attributes[$this->finalDN]['remove']['pwdAccountLockedTime'])) {
				unset($attributes[$this->finalDN]['remove']['pwdAccountLockedTime']);
			}
		}
		// pre modify actions
		$prePostModifyAttributes = $this->extraInfoAttributes;
		if (isset($attributes[$this->finalDN]) && is_array($attributes[$this->finalDN])) {
			if (isset($attributes[$this->finalDN]['notchanged'])) {
				$prePostModifyAttributes = array_merge($prePostModifyAttributes, $attributes[$this->finalDN]['notchanged']);
			}
			if (isset($attributes[$this->finalDN]['modify'])) {
				foreach ($attributes[$this->finalDN]['modify'] as $key => $value) {
					$prePostModifyAttributes[$key] = $value;
					$prePostModifyAttributes['MOD.' . $key] = $value;
				}
			}
			if (isset($attributes[$this->finalDN]['add'])) {
				foreach ($attributes[$this->finalDN]['add'] as $key => $value) {
					$prePostModifyAttributes['NEW.' . $key] = $value;
					if (isset($prePostModifyAttributes[$key])) {
						$prePostModifyAttributes[$key] = array_merge($prePostModifyAttributes[$key], $value);
					}
					else {
						$prePostModifyAttributes[$key] = $value;
					}
				}
			}
			if (isset($attributes[$this->finalDN]['remove'])) {
				foreach ($attributes[$this->finalDN]['remove'] as $key => $value) {
					$prePostModifyAttributes['DEL.' . $key] = $value;
				}
			}
			if (isset($attributes[$this->finalDN]['info'])) {
				foreach ($attributes[$this->finalDN]['info'] as $key => $value) {
					$prePostModifyAttributes['INFO.' . $key] = $value;
				}
			}
		}
		if (!$this->isNewAccount) {
			foreach ($this->attributes_orig as $key => $value) {
				$prePostModifyAttributes['ORIG.' . $key] = $value;
			}
			$prePostModifyAttributes['ORIG.dn'][0] = $this->dn_orig;
		}
		$prePostModifyAttributes['dn'][0] = $this->finalDN;
		if (!$this->isNewAccount && ($this->finalDN !== $this->dn_orig)) {
			$prePostModifyAttributes['MOD.dn'][0] = $this->finalDN;
		}
		logNewMessage(LOG_DEBUG, 'Edit page pre/postModify attributes: ' . print_r($prePostModifyAttributes, true));
		$preModifyOk = true;
		foreach ($module as $singlemodule) {
			$preModifyMessages = $this->module[$singlemodule]->preModifyActions($this->isNewAccount, $prePostModifyAttributes);
			$errors = array_merge($errors, $preModifyMessages);
			for ($i = 0; $i < count($preModifyMessages); $i++) {
				if ($preModifyMessages[$i][0] == 'ERROR') {
					$preModifyOk = false;
					break;
				}
			}
		}
		if (!$preModifyOk) {
			$errors[] = ['ERROR', _('The operation was stopped because of the above errors.')];
			return $errors;
		}
		// Set to true if a real error has happened
		$stopprocessing = false;
		$finalDnLower = strtolower($this->finalDN);
		$dnOrigLower = ($this->dn_orig !== null) ? strtolower($this->dn_orig) : '';
		if (($finalDnLower !== $dnOrigLower) && (unescapeLdapSpecialCharacters($finalDnLower) !== unescapeLdapSpecialCharacters($dnOrigLower))) {
			// move existing DN
			if ($this->dn_orig != '') {
				$removeOldRDN = $_SESSION['ldap']->isActiveDirectory();
				if (isset($attributes[$this->finalDN]['modify'])) {
					$attributes[$this->finalDN]['modify'] = array_change_key_case($attributes[$this->finalDN]['modify'], CASE_LOWER);
				}
				$rdnAttr = strtolower(extractRDNAttribute($this->finalDN));
				if (isset($attributes[$this->finalDN]['modify'][$rdnAttr])
					&& (count($attributes[$this->finalDN]['modify'][$rdnAttr]) === 1)
					&& (($attributes[$this->finalDN]['modify'][$rdnAttr][0] == extractRDNValue($this->finalDN))
						|| (unescapeLdapSpecialCharacters($attributes[$this->finalDN]['modify'][$rdnAttr][0]) == unescapeLdapSpecialCharacters(extractRDNValue($this->finalDN))))) {
					// remove old RDN if attribute is single valued
					$removeOldRDN = true;
					unset($attributes[$this->finalDN]['modify'][extractRDNAttribute($this->finalDN)]);
				}
				logNewMessage(LOG_DEBUG, 'Rename ' . $this->dn_orig . ' to ' . $this->finalDN);
				$success = ldap_rename($_SESSION['ldap']->server(), $this->dn_orig, $this->getRDN($this->finalDN), $this->getParentDN($this->finalDN), $removeOldRDN);
				if ($success) {
					logNewMessage(LOG_NOTICE, 'Renamed DN ' . $this->dn_orig . " to " . $this->finalDN);
					// do not add attribute value as new one if added via rename operation
					if (!empty($attributes[$this->finalDN]['add'][$rdnAttr]) && in_array(extractRDNValue($this->finalDN), $attributes[$this->finalDN]['add'][$rdnAttr])) {
						$attributes[$this->finalDN]['add'][$rdnAttr] = array_delete([extractRDNValue($this->finalDN)], $attributes[$this->finalDN]['add'][$rdnAttr]);
						if (empty($attributes[$this->finalDN]['add'][$rdnAttr])) {
							unset($attributes[$this->finalDN]['add'][$rdnAttr]);
						}
					}
				}
				else {
					logNewMessage(LOG_ERR, 'Unable to rename DN: ' . $this->dn_orig . ' (' . ldap_error($_SESSION['ldap']->server()) . '). '
						. getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
					$errors[] = ['ERROR', sprintf(_('Was unable to rename DN: %s.'), $this->dn_orig), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
					$stopprocessing = true;
				}
			}
			// create complete new dn
			else {
				$attr = [];
				if (isset($attributes[$this->finalDN]['add']) && is_array($attributes[$this->finalDN]['add'])) {
					$attr = array_merge_recursive($attr, $attributes[$this->finalDN]['add']);
				}
				if (isset($attributes[$this->finalDN]['notchanged']) && is_array($attributes[$this->finalDN]['notchanged'])) {
					$attr = array_merge_recursive($attr, $attributes[$this->finalDN]['notchanged']);
				}
				if (isset($attributes[$this->finalDN]['modify']) && is_array($attributes[$this->finalDN]['modify'])) {
					$attr = array_merge_recursive($attr, $attributes[$this->finalDN]['modify']);
				}
				$success = @ldap_add($_SESSION['ldap']->server(), $this->finalDN, $attr);
				if (!$success) {
					logNewMessage(LOG_ERR, 'Unable to create DN: ' . $this->finalDN . ' (' . ldap_error($_SESSION['ldap']->server()) . '). '
						. getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
					$errors[] = ['ERROR', sprintf(_('Was unable to create DN: %s.'), $this->finalDN), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
					$stopprocessing = true;
				}
				else {
					logNewMessage(LOG_NOTICE, 'Created DN: ' . $this->finalDN);
				}
				unset($attributes[$this->finalDN]);
			}
		}
		$DNs = array_keys($attributes);
		for ($i = 0; $i < count($DNs); $i++) {
			if (!$stopprocessing) {
				logNewMessage(LOG_DEBUG, 'Attribute changes for ' . $DNs[$i] . ":\n" . print_r($attributes[$DNs[$i]], true));
				// modify attributes
				if (!empty($attributes[$DNs[$i]]['modify'])) {
					$success = @ldap_mod_replace($_SESSION['ldap']->server(), $DNs[$i], $attributes[$DNs[$i]]['modify']);
					if (!$success) {
						logNewMessage(LOG_ERR, 'Unable to modify attributes of DN: ' . $DNs[$i] . ' (' . ldap_error($_SESSION['ldap']->server()) . '). '
							. getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
						logNewMessage(LOG_DEBUG, print_r($attributes[$DNs[$i]]['modify'], true));
						$errors[] = ['ERROR', sprintf(_('Was unable to modify attributes of DN: %s.'), $DNs[$i]), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
						$stopprocessing = true;
					}
					else {
						logNewMessage(LOG_NOTICE, 'Modified DN: ' . $DNs[$i]);
						// check if the password of the currently logged in user was changed
						$lamAdmin = $_SESSION['ldap']->getUserName();
						if ((strtolower($DNs[$i]) === strtolower($lamAdmin)) && isset($attributes[$DNs[$i]]['info']['userPasswordClearText'][0])) {
							$_SESSION['ldap']->tryAndApplyNewPassword($attributes[$DNs[$i]]['info']['userPasswordClearText'][0]);
						}
					}
				}
				// add attributes
				if (!empty($attributes[$DNs[$i]]['add']) && !$stopprocessing) {
					$success = @ldap_mod_add($_SESSION['ldap']->server(), $DNs[$i], $attributes[$DNs[$i]]['add']);
					if (!$success) {
						logNewMessage(LOG_ERR, 'Unable to add attributes to DN: ' . $DNs[$i] . ' (' . ldap_error($_SESSION['ldap']->server()) . '). '
							. getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
						$errors[] = ['ERROR', sprintf(_('Was unable to add attributes to DN: %s.'), $DNs[$i]), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
						$stopprocessing = true;
					}
					else {
						logNewMessage(LOG_NOTICE, 'Modified DN: ' . $DNs[$i]);
					}
				}
				// remove attributes
				if (!empty($attributes[$DNs[$i]]['remove']) && !$stopprocessing) {
					$success = @ldap_mod_del($_SESSION['ldap']->server(), $DNs[$i], $attributes[$DNs[$i]]['remove']);
					if (!$success) {
						logNewMessage(LOG_ERR, 'Unable to delete attributes from DN: ' . $DNs[$i] . ' (' . ldap_error($_SESSION['ldap']->server()) . '). '
							. getExtendedLDAPErrorMessage($_SESSION['ldap']->server()));
						$errors[] = ['ERROR', sprintf(_('Was unable to remove attributes from DN: %s.'), $DNs[$i]), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
						$stopprocessing = true;
					}
					else {
						logNewMessage(LOG_NOTICE, 'Modified DN: ' . $DNs[$i]);
					}
				}
			}
		}
		// send password mail
		if (!$stopprocessing && isLAMProVersion() && ($this->sendPasswordViaMail != null)) {
			$mailMessages = sendPasswordMail($this->sendPasswordViaMail, $prePostModifyAttributes, $this->sendPasswordViaMailAlternateAddress);
			if (count($mailMessages) > 0) {
				$errors = array_merge($errors, $mailMessages);
			}
			$this->sendPasswordViaMail = null;
			$this->sendPasswordViaMailAlternateAddress = null;
		}
		// send password SMS
		if (!$stopprocessing && isLAMProVersion() && ($this->sendPasswordViaSms != null)) {
			$smsMessages = sendPasswordSms($this->sendPasswordViaSms, $prePostModifyAttributes);
			if (count($smsMessages) > 0) {
				$errors = array_merge($errors, $smsMessages);
			}
			$this->sendPasswordViaSms = null;
		}
		if (!$stopprocessing) {
			// post modify actions
			foreach ($module as $singlemodule) {
				$postMessages = $this->module[$singlemodule]->postModifyActions($this->isNewAccount, $prePostModifyAttributes);
				foreach ($postMessages as $postMessage) {
					if ($postMessage[0] == 'ERROR') {
						$this->postSaveErrorsOccurred = true;
					}
				}
				$errors = array_merge($errors, $postMessages);
			}
		}
		return $errors;
	}

	/**
	 * Defines if the LDAP entry has only virtual child entries. This is the case for e.g. LDAP views.
	 *
	 * @return bool has only virtual children
	 */
	public function hasOnlyVirtualChildren(): bool {
		foreach ($this->module as $module) {
			if ($module->hasOnlyVirtualChildren()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Returns a list of possible PDF entries for this account.
	 *
	 * @param string[] $pdfKeys list of PDF keys that are included in document
	 * @param string $typeId type id (user, group, host)
	 * @return array<string, PDFEntry[]> list of key => PDFEntry
	 */
	public function get_pdfEntries($pdfKeys, $typeId): array {
		$return = [];
		while (($current = current($this->module)) != null) {
			$return = array_merge($return, $current->get_pdfEntries($pdfKeys, $typeId));
			next($this->module);
		}
		$dn = $this->dn_orig;
		if ($this->finalDN !== null) {
			$dn = $this->finalDN;
		}
		return array_merge($return, ['main_dn' => [new PDFLabelValue(_('DN'), $dn)]]);
	}

	/**
	 * Sorts the module buttons for the account page.
	 */
	private function sortModules(): void {
		$order = [];
		$modules = array_keys($this->module);
		$depModules = [];
		if ($this->order !== null) {
			$currentPage = $this->order[$this->current_page];
		}
		for ($i = 0; $i < count($modules); $i++) {
			// insert waiting modules
			for ($w = 0; $w < count($depModules); $w++) {
				$dependencies = $this->module[$depModules[$w]]->get_dependencies();
				$dependencies = $dependencies['depends'];
				$everything_found = true;
				for ($d = 0; $d < count($dependencies); $d++) {
					if (!in_array($dependencies[$d], $order)) {
						$everything_found = false;
						break;
					}
				}
				// insert after depending module
				if ($everything_found) {
					$order[] = $depModules[$w];
					unset($depModules[$w]);
					$depModules = array_values($depModules);
					$w--;
				}
			}
			// check next module
			$dependencies = $this->module[$modules[$i]]->get_dependencies();
			if (isset($dependencies['depends'])) {
				$everything_found = true;
				$dependencies = $dependencies['depends'];
				for ($d = 0; $d < count($dependencies); $d++) {
					if (is_array($dependencies[$d])) { // or-combined dependencies
						$noneFound = true;
						foreach ($dependencies[$d] as $or) {
							if (in_array($or, $order)) {
								$noneFound = false;
								break;
							}
						}
						if ($noneFound) {
							$everything_found = false;
							break;
						}
					}
					elseif (!in_array($dependencies[$d], $order)) { // single dependency
						$everything_found = false;
						break;
					}
				}
				// remove module if dependencies are not satisfied
				if (!$everything_found) {
					$depModules[] = $modules[$i];
					unset($modules[$i]);
					$modules = array_values($modules);
					$i--;
				}
				else {
					$order[] = $modules[$i];
				}
			}
			else {
				$order[] = $modules[$i];
			}
		}
		// add modules which could not be sorted (e.g. because of cyclic dependencies)
		if ($depModules !== []) {
			for ($i = 0; $i < count($depModules); $i++) {
				$order[] = $depModules[$i];
			}
		}
		// move disabled modules to end
		$activeModules = [];
		$passiveModules = [];
		for ($i = 0; $i < count($order); $i++) {
			if ($this->module[$order[$i]]->getButtonStatus() == 'enabled') {
				$activeModules[] = $order[$i];
			}
			else {
				$passiveModules[] = $order[$i];
			}
		}
		$this->order = array_merge($activeModules, $passiveModules);
		// check if ordering changed and current page number must be updated
		if (isset($currentPage) && ($currentPage != $this->order[$this->current_page])) {
			$this->current_page = array_search($currentPage, $this->order);
		}
	}

	/**
	 * Returns the RDN part of a given DN.
	 *
	 * @param string|null $dn DN
	 * @return string RDN
	 */
	function getRDN(?string $dn): string {
		if (($dn === "") || ($dn === null)) {
			return "";
		}
		return substr($dn, 0, strpos($dn, ","));
	}

	/**
	 * Returns the parent DN of a given DN.
	 *
	 * @param string|null $dn DN
	 * @return string DN
	 */
	private function getParentDN(?string $dn): string {
		if (($dn === "") || ($dn === null)) {
			return "";
		}
		return substr($dn, strpos($dn, ",") + 1);
	}

	/**
	 * Returns a list of OUs that exist for this account type.
	 *
	 * @return string[] OU list
	 */
	public function getOUs(): array {
		if ($this->cachedOUs !== null) {
			return $this->cachedOUs;
		}
		$this->cachedOUs = $this->type->getSuffixList();
		return $this->cachedOUs;
	}

	/**
	 * Replaces POST data with wildcard values from modules.
	 *
	 * @param string[] $keyPrefixes POST keys as full name or prefix (e.g. "key" matches "key1")
	 */
	public function replaceWildcardsInPOST($keyPrefixes): void {
		$this->replaceWildcardsInArray($keyPrefixes, $_POST);
	}

	/**
	 * Replaces data with wildcard values from modules.
	 *
	 * @param string[] $keyPrefixes POST keys as full name or prefix (e.g. "key" matches "key1")
	 * @param array<string, array<int, string>|string> $data list of values that need replacement
	 */
	public function replaceWildcardsInArray($keyPrefixes, &$data): void {
		$replacements = [];
		foreach ($this->module as $module) {
			$replacements = array_merge($replacements, $module->getWildCardReplacements());
		}
		while (true) {
			if (!$this->replaceWildcards($replacements, $keyPrefixes, $data)) {
				break;
			}
		}
	}

	/**
	 * Replaces wildcards in an array.
	 *
	 * @param array<string, string> $replacements replacements (key => value)
	 * @param string[] $keyPrefixes prefixes of $data array keys that should be replaced
	 * @param array<string, array<int, string>|string> $data data array
	 * @return bool replacement done
	 */
	private function replaceWildcards($replacements, $keyPrefixes, &$data): bool {
		$found = false;
		foreach ($data as $key => $value) {
			foreach ($keyPrefixes as $keyPrefix) {
				if (str_starts_with($key, $keyPrefix)) {
					if (!is_array($value)) {
						$found = $this->doReplace($replacements, $data[$key]) || $found;
					}
					else {
						foreach (array_keys($value) as $valueIndex) {
							$found = $this->doReplace($replacements, $data[$key][$valueIndex]) || $found;
						}
					}
				}
			}
		}
		return $found;
	}

	/**
	 * Replaces wildcards in a value.
	 *
	 * @param array<string, string> $replacements replacements (key => value)
	 * @param string $value value to perform replacements
	 * @return bool replacement done
	 */
	private function doReplace($replacements, &$value): bool {
		$found = false;
		foreach ($replacements as $replKey => $replValue) {
			$searchString = '$' . $replKey;
			if (str_contains($value, $searchString)) {
				$found = true;
				$value = str_replace($searchString, $replValue, $value);
			}
			$searchString = '$_' . $replKey;
			if (str_contains($value, $searchString)) {
				$found = true;
				$value = str_replace($searchString, strtolower($replValue), $value);
			}
		}
		return $found;
	}

	/**
	 * Encrypts sensitive data before storing in session.
	 *
	 * @return array list of attributes which are serialized
	 */
	public function __sleep() {
		// encrypt data
		$this->attributes = lamEncrypt(json_encode($this->attributes, JSON_INVALID_UTF8_IGNORE));
		$this->attributes_orig = lamEncrypt(json_encode($this->attributes_orig, JSON_INVALID_UTF8_IGNORE));
		$this->module = lamEncrypt(serialize($this->module));
		// save all attributes
		return array_keys(get_object_vars($this));
	}

	/**
	 * Decrypts sensitive data after accountContainer was loaded from session.
	 */
	public function __wakeup() {
		// decrypt data
		$this->attributes = json_decode(lamDecrypt($this->attributes), true, 512, JSON_INVALID_UTF8_IGNORE);
		$this->attributes_orig = json_decode(lamDecrypt($this->attributes_orig), true, 512, JSON_INVALID_UTF8_IGNORE);
		$this->module = unserialize(lamDecrypt($this->module));
	}

}

/**
 * This interface needs to be implemented by all account modules which manage passwords.
 * It allows LAM to provide central password changes.
 *
 * @package modules
 */
interface passwordService {

	/**
	 * This method specifies if a module manages password attributes. The module alias will
	 * then appear as option in the GUI.
	 * <br>If the module only wants to get notified about password changes then return false.
	 *
	 * @return bool true if this module manages password attributes
	 */
	public function managesPasswordAttributes(): bool;

	/**
	 * Specifies if this module supports to force that a user must change his password on next login.
	 *
	 * @return bool force password change supported
	 */
	public function supportsForcePasswordChange(): bool;

	/**
	 * This function is called whenever the password should be changed. Account modules
	 * must change their password attributes only if the modules list contains their module name.
	 *
	 * @param string $password new password
	 * @param string[] $modules list of modules for which the password should be changed
	 * @param bool $forcePasswordChange force the user to change his password at next login
	 * @return string[][] list of error messages if any as parameter array for StatusMessage
	 *               e.g. return array(array('ERROR', 'Password change failed.'))
	 */
	public function passwordChangeRequested(string $password, array $modules, bool $forcePasswordChange): array;

	/**
	 * Specifies if the module support password quick change for the current account.
	 *
	 * @return bool password quick change page supported
	 */
	public function supportsPasswordQuickChangePage(): bool;

	/**
	 * Adds account details such as first/last name for the current account.
	 *
	 * @param htmlResponsiveRow $row row where to add content
	 */
	public function addPasswordQuickChangeAccountDetails(htmlResponsiveRow $row): void;

	/**
	 * Returns a list of password quick change options.
	 *
	 * @param bool $forcePasswordChangeByDefault password change should be preselected
	 * @return PasswordQuickChangeOption[] options
	 */
	public function getPasswordQuickChangeOptions(bool $forcePasswordChangeByDefault): array;

	/**
	 * Returns a list of LDAP attribute changes to perform.
	 *
	 * @param string $password new password
	 * @return array<string, string[]|string> LDAP attribute values (attr_name => array(attr_value))
	 * @throws LAMException error getting changes
	 */
	public function getPasswordQuickChangeChanges(string $password): array;

	/**
	 * Returns the username if known to be validated for password strength.
	 *
	 * @return string|null user name
	 */
	public function getPasswordQuickChangePasswordStrengthUserName(): ?string;

	/**
	 * Returns additional attribute values to check when password strength is validated.
	 *
	 * @return string[] attribute values
	 */
	public function getPasswordQuickChangePasswordStrengthAttributes(): array;

	/**
	 * Returns if the password is not same as an old password from history.
	 *
	 * @param string $password new password
	 * @return bool is in history
	 */
	public function getPasswordQuickChangeIsPasswordInHistory(string $password): bool;

}

/**
 * Option for the password quick change page.
 */
class PasswordQuickChangeOption {

	public string $label;

	public string $id;

	public bool $preSelected;

	/**
	 * PasswordQuickChangeOption constructor.
	 *
	 * @param string $id unique id for this option
	 * @param string $label descriptive label
	 * @param bool $preSelected is preselected
	 */
	public function __construct(string $id, string $label, bool $preSelected = true) {
		$this->label = $label;
		$this->id = $id;
		$this->preSelected = $preSelected;
	}

}

/**
 * Provides module information about the status of an LDAP account.
 */
interface AccountStatusProvider {

	/**
	 * Returns the list of account status detail lines.
	 *
	 * @param ConfiguredType $type account type
	 * @param array<string, string[]|string>|null $attributes LDAP attributes (use account container attributes if not provided)
	 * @return AccountStatusDetails[] status details
	 */
	public function getAccountStatusDetails(ConfiguredType $type, ?array &$attributes): array;

	/**
	 * Returns the list of LDAP attributes that must be read to get the account status.
	 *
	 * @param ConfiguredType $type type
	 * @return string[] attribute names
	 */
	public function getAccountStatusRequiredAttributes(ConfiguredType $type): array;

	/**
	 * Returns a list of options how the account could be locked.
	 *
	 * @param ConfiguredType $type type
	 * @param array<string, string[]|string>|null $attributes LDAP attributes
	 * @return AccountStatusDetails[] lock options
	 */
	public function getAccountStatusPossibleLockOptions(ConfiguredType $type, ?array &$attributes): array;

	/**
	 * Locks the account with the given lock IDs.
	 *
	 * @param ConfiguredType $type type
	 * @param array<string, string[]|string>|null $attributes LDAP attributes
	 * @param string[] $lockIds IDs from AccountStatusDetails
	 * @throws LAMException error during locking
	 */
	public function accountStatusPerformLock(ConfiguredType $type, ?array &$attributes, array $lockIds): void;

	/**
	 * Unlocks the account with the given lock IDs.
	 *
	 * @param ConfiguredType $type type
	 * @param array<string, string[]|string>|null $attributes LDAP attributes
	 * @param string[] $lockIds IDs from AccountStatusDetails
	 */
	public function accountStatusPerformUnlock(ConfiguredType $type, ?array &$attributes, array $lockIds): void;

}

/**
 * Provides the complete information about the status of an LDAP account.
 */
class AccountStatus {

	/** @var AccountStatusDetails[] list of details */
	private array $details;

	/**
	 * Constructor.
	 *
	 * @param AccountStatusDetails[] $details details
	 */
	public function __construct(array $details) {
		$this->details = $details;
	}

	/**
	 * Creates the account status from the given type and LDAP attributes.
	 *
	 * @param ConfiguredType $type type
	 * @param array<string, string[]|string> $attributes LDAP attributes
	 * @return AccountStatus status
	 */
	public static function fromAttributes(ConfiguredType $type, array $attributes): AccountStatus {
		$modules = $_SESSION['config']->get_AccountModules($type->getId());
		$details = [];
		foreach ($modules as $module) {
			$moduleObject = moduleCache::getModule($module, $type->getScope());
			if (!($moduleObject instanceof AccountStatusProvider)) {
				continue;
			}
			$details = array_merge($details, $moduleObject->getAccountStatusDetails($type, $attributes));
		}
		return new AccountStatus($details);
	}

	/**
	 * Creates the lockable account status from the given type and LDAP attributes.
	 *
	 * @param ConfiguredType $type type
	 * @param array<string, string[]|string> $attributes LDAP attributes
	 * @return AccountStatus lockable status
	 */
	public static function lockableFromAttributes(ConfiguredType $type, array $attributes): AccountStatus {
		$modules = $_SESSION['config']->get_AccountModules($type->getId());
		$details = [];
		foreach ($modules as $module) {
			$moduleObject = moduleCache::getModule($module, $type->getScope());
			if (!($moduleObject instanceof AccountStatusProvider)) {
				continue;
			}
			$details = array_merge($details, $moduleObject->getAccountStatusPossibleLockOptions($type, $attributes));
		}
		return new AccountStatus($details);
	}

	/**
	 * Returns the account details.
	 *
	 * @return AccountStatusDetails[] details
	 */
	public function getDetails(): array {
		return $this->details;
	}

	/**
	 * Returns if the account/password is fully expired (e.g. login no longer possible without password change).
	 *
	 * @return bool is expired
	 */
	public function isExpired(): bool {
		foreach ($this->details as $detail) {
			if ($detail->isExpired()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Returns if the account/password is partially expired (e.g. a single application is expired).
	 *
	 * @return bool is expired
	 */
	public function isPartiallyExpired(): bool {
		foreach ($this->details as $detail) {
			if ($detail->isPartiallyExpired()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Returns if the account is fully locked (login no longer possible).
	 *
	 * @return bool is locked
	 */
	public function isLocked(): bool {
		foreach ($this->details as $detail) {
			if ($detail->isLocked()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Returns if the account is partially locked (e.g. a single application is locked).
	 *
	 * @return bool is locked
	 */
	public function isPartiallyLocked(): bool {
		foreach ($this->details as $detail) {
			if ($detail->isPartiallyLocked()) {
				return true;
			}
		}
		return false;
	}

}

class AccountStatusDetails {

	private string $details;
	private string $id;
	private bool $expired = false;
	private bool $partiallyExpired = false;
	private bool $locked = false;
	private bool $partiallyLocked = false;
	private string $icon;

	/**
	 * Constructor.
	 *
	 * @param string $details details message
	 * @param string $id ID for reference
	 * @param string $icon icon name
	 */
	public function __construct(string $details, string $id, string $icon) {
		$this->details = $details;
		$this->id = $id;
		$this->icon = $icon;
	}

	/**
	 * Creates a new expired status entry.
	 *
	 * @param string $details details message
	 * @param string $id ID for reference
	 * @param string $icon icon name
	 * @return AccountStatusDetails status entry
	 */
	public static function newExpired(string $details, string $id, ?string $icon = null): AccountStatusDetails {
		if ($icon === null) {
			$icon = 'expired.svg';
		}
		$details = new AccountStatusDetails($details, $id, $icon);
		$details->expired = true;
		return $details;
	}

	/**
	 * Creates a new partially expired status entry.
	 *
	 * @param string $details details message
	 * @param string $id ID for reference
	 * @param string $icon icon name
	 * @return AccountStatusDetails status entry
	 */
	public static function newPartiallyExpired(string $details, string $id, ?string $icon = null): AccountStatusDetails {
		if ($icon === null) {
			$icon = 'expired.svg';
		}
		$details = new AccountStatusDetails($details, $id, $icon);
		$details->partiallyExpired = true;
		return $details;
	}

	/**
	 * Creates a new locked status entry.
	 *
	 * @param string $details details message
	 * @param string $id ID for reference
	 * @param string $icon icon name
	 * @return AccountStatusDetails status entry
	 */
	public static function newLocked(string $details, string $id, ?string $icon = null): AccountStatusDetails {
		if ($icon === null) {
			$icon = 'locked.svg';
		}
		$details = new AccountStatusDetails($details, $id, $icon);
		$details->locked = true;
		return $details;
	}

	/**
	 * Creates a new partially locked status entry.
	 *
	 * @param string $details details message
	 * @param string $id ID for reference
	 * @param string $icon icon name
	 * @return AccountStatusDetails status entry
	 */
	public static function newPartiallyLocked(string $details, string $id, ?string $icon = null): AccountStatusDetails {
		if ($icon === null) {
			$icon = 'partiallyLocked.svg';
		}
		$details = new AccountStatusDetails($details, $id, $icon);
		$details->partiallyLocked = true;
		return $details;
	}

	/**
	 * Returns if the account/password is fully expired (e.g. login no longer possible without password change).
	 *
	 * @return bool is expired
	 */
	public function isExpired(): bool {
		return $this->expired;
	}

	/**
	 * Returns if the account/password is partially expired (e.g. a single application is expired).
	 *
	 * @return bool is expired
	 */
	public function isPartiallyExpired(): bool {
		return $this->partiallyExpired;
	}

	/**
	 * Returns if the account is fully locked (login no longer possible).
	 *
	 * @return bool is locked
	 */
	public function isLocked(): bool {
		return $this->locked;
	}

	/**
	 * Returns if the account is partially locked (e.g. a single application is locked).
	 *
	 * @return bool is locked
	 */
	public function isPartiallyLocked(): bool {
		return $this->partiallyLocked;
	}

	/**
	 * Returns the icon name.
	 *
	 * @return string icon name
	 */
	public function getIcon(): string {
		return $this->icon;
	}

	/**
	 * Returns the details.
	 *
	 * @return string details
	 */
	public function getDetails(): string {
		return $this->details;
	}

	/**
	 * Returns the id.
	 *
	 * @return string id
	 */
	public function getId(): string {
		return $this->id;
	}

}

/**
 * Validation of scope and module names.
 */
class ScopeAndModuleValidation {

	/** @var string[]|null $cachedModuleNames names */
	private static ?array $cachedModuleNames = null;

	/** @var string[]|null $cachedScopeNames names */
	private static ?array $cachedScopeNames = null;

	private const REGEX_SCOPE = "/^[a-z0-9_-]+$/i";
	private const REGEX_MODULE = "/^[a-z0-9_-]+$/i";

	/**
	 * Checks if the provided scope name is valid.
	 *
	 * @param string $scope scope name
	 * @return bool is existing
	 */
	public static function isValidScopeName(string $scope): bool {
		if (!preg_match(self::REGEX_SCOPE, $scope)) {
			return false;
		}
		if (self::$cachedScopeNames === null) {
			$dirname = __DIR__ . "/types";
			$dir = dir($dirname);
			$scopeNames = [];
			while ($entry = $dir->read()) {
				if ((substr($entry, strlen($entry) - 4, 4) === '.inc')
					&& (is_file($dirname . '/' . $entry) || is_link($dirname . '/' . $entry))) {
					$entry = substr($entry, 0, -4);
					if (preg_match(self::REGEX_SCOPE, $entry)) {
						$scopeNames[] = $entry;
					}
				}
			}
			self::$cachedScopeNames = $scopeNames;
		}
		return in_array($scope, self::$cachedScopeNames);
	}

	/**
	 * Checks if the provided module name is valid.
	 *
	 * @param string $moduleName module name
	 * @return bool is existing
	 */
	public static function isValidModuleName(string $moduleName): bool {
		if (!preg_match(self::REGEX_MODULE, $moduleName)) {
			return false;
		}
		if (self::$cachedModuleNames === null) {
			$dirname = __DIR__ . "/modules";
			$dir = dir($dirname);
			$moduleNames = [];
			while ($entry = $dir->read()) {
				if ((substr($entry, strlen($entry) - 4, 4) === '.inc')
					&& (is_file($dirname . '/' . $entry) || is_link($dirname . '/' . $entry))) {
					$entry = substr($entry, 0, -4);
					if (preg_match(self::REGEX_MODULE, $entry)) {
						$moduleNames[] = $entry;
					}
				}
			}
			self::$cachedModuleNames = $moduleNames;
		}
		return in_array($moduleName, self::$cachedModuleNames);
	}

}
