diff --git a/lam/HISTORY b/lam/HISTORY index b23072f01..56de6b0ea 100644 --- a/lam/HISTORY +++ b/lam/HISTORY @@ -1,3 +1,8 @@ +December 2024 9.0 + - Fixed bugs: + -> Windows: show more than 1000 LDAP entries when paged results is activated in server profile + + 24.09.2024 8.9 - Windows user: support for room number and personal title (needs to be activated in module settings) (343, 344) - Usability improvements (354) diff --git a/lam/lib/2factor.inc b/lam/lib/2factor.inc index fd032f116..2c14fec1a 100644 --- a/lam/lib/2factor.inc +++ b/lam/lib/2factor.inc @@ -7,25 +7,23 @@ use DateTime; use Duo\DuoUniversal\Client; use Duo\DuoUniversal\DuoException; use Exception; -use \htmlResponsiveRow; -use \LAM\LOGIN\WEBAUTHN\WebauthnManager; +use htmlResponsiveRow; +use LAM\LOGIN\WEBAUTHN\WebauthnManager; use SelfServiceLoginHandler; -use \selfServiceProfile; -use \LAMConfig; -use \htmlScript; -use \htmlIframe; -use \htmlImage; -use \htmlButton; -use \htmlJavaScript; -use \htmlStatusMessage; -use \htmlOutputText; -use \htmlDiv; -use \LAMException; -use \Webauthn\PublicKeyCredentialCreationOptions; +use selfServiceProfile; +use LAMConfig; +use htmlImage; +use htmlButton; +use htmlJavaScript; +use htmlStatusMessage; +use htmlOutputText; +use htmlDiv; +use LAMException; +use Webauthn\PublicKeyCredentialCreationOptions; /* This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) - Copyright (C) 2017 - 2023 Roland Gruber + Copyright (C) 2017 - 2024 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 @@ -114,7 +112,7 @@ abstract class BaseProvider implements TwoFactorProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::hasCustomInputForm() + * @see TwoFactorProvider::hasCustomInputForm */ public function hasCustomInputForm() { return false; @@ -122,7 +120,7 @@ abstract class BaseProvider implements TwoFactorProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::addCustomInput() + * @see TwoFactorProvider::addCustomInput */ public function addCustomInput(&$row, $userDn) { // must be filled by subclass if used @@ -150,7 +148,7 @@ abstract class BaseProvider implements TwoFactorProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::isShowSubmitButton() + * @see TwoFactorProvider::isShowSubmitButton */ public function isShowSubmitButton() { return true; @@ -174,7 +172,7 @@ class PrivacyIDEAProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::getSerials() + * @see TwoFactorProvider::getSerials */ public function getSerials($user, $password) { logNewMessage(LOG_DEBUG, 'PrivacyIDEAProvider: Getting serials for ' . $user); @@ -185,7 +183,7 @@ class PrivacyIDEAProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::verify2ndFactor() + * @see TwoFactorProvider::verify2ndFactor */ public function verify2ndFactor($user, $password, $serial, $twoFactorInput) { logNewMessage(LOG_DEBUG, 'PrivacyIDEAProvider: Checking 2nd factor for ' . $user); @@ -200,7 +198,7 @@ class PrivacyIDEAProvider extends BaseProvider { * @param string $user user name * @param string $password password * @return string token - * @throws \Exception error during authentication + * @throws Exception error during authentication */ private function authenticate($user, $password) { $curl = $this->getCurl(); @@ -224,8 +222,8 @@ class PrivacyIDEAProvider extends BaseProvider { } $status = $output->result->status; if ($status != 1) { - $errCode = isset($output->result->error) && isset($output->result->error->code) ? $output->result->error->code : ''; - $errMessage = isset($output->result->error) && isset($output->result->error->message) ? $output->result->error->message : ''; + $errCode = $output->result->error->code ?? ''; + $errMessage = $output->result->error->message ?? ''; throw new Exception("Unable to login: " . $errCode . ' ' . $errMessage); } if (!isset($output->result->value) || !isset($output->result->value->token)) { @@ -238,7 +236,7 @@ class PrivacyIDEAProvider extends BaseProvider { * Returns the curl object. * * @return object curl handle - * @throws \Exception error during curl creation + * @throws Exception error during curl creation */ private function getCurl() { $curl = curl_init(); @@ -275,8 +273,8 @@ class PrivacyIDEAProvider extends BaseProvider { } $status = $output->result->status; if (($status != 1) || !isset($output->result->value) || !isset($output->result->value->tokens)) { - $errCode = isset($output->result->error) && isset($output->result->error->code) ? $output->result->error->code : ''; - $errMessage = isset($output->result->error) && isset($output->result->error->message) ? $output->result->error->message : ''; + $errCode = $output->result->error->code ?? ''; + $errMessage = $output->result->error->message ?? ''; throw new Exception("Unable to get serials: " . $errCode . ' ' . $errMessage); } $serials = []; @@ -311,7 +309,7 @@ class PrivacyIDEAProvider extends BaseProvider { curl_close($curl); $output = json_decode($json); if (empty($output) || !isset($output->result) || !isset($output->result->status) || !isset($output->result->value)) { - throw new \Exception("Unable to get json from $url."); + throw new Exception("Unable to get json from $url."); } $status = $output->result->status; $value = $output->result->value; @@ -349,7 +347,7 @@ class YubicoProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::getSerials() + * @see TwoFactorProvider::getSerials */ public function getSerials($user, $password) { $keyAttributeName = strtolower($this->config->twoFactorAuthenticationSerialAttributeName); @@ -369,7 +367,7 @@ class YubicoProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::verify2ndFactor() + * @see TwoFactorProvider::verify2ndFactor */ public function verify2ndFactor($user, $password, $serial, $twoFactorInput) { include_once(__DIR__ . "/3rdParty/yubico/Yubico.php"); @@ -380,13 +378,13 @@ class YubicoProvider extends BaseProvider { $serials = explode(', ', $serialData[0]); $serialMatched = false; foreach ($serials as $serial) { - if (strpos($twoFactorInput, $serial) === 0) { + if (str_starts_with($twoFactorInput, $serial)) { $serialMatched = true; break; } } if (!$serialMatched) { - throw new \Exception(_('YubiKey id does not match allowed list of key ids.')); + throw new Exception(_('YubiKey id does not match allowed list of key ids.')); } $urls = $this->config->twoFactorAuthenticationURL; shuffle($urls); @@ -431,7 +429,7 @@ class DuoProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::getSerials() + * @see TwoFactorProvider::getSerials */ public function getSerials($user, $password) { return ['DUO']; @@ -439,7 +437,7 @@ class DuoProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::isShowSubmitButton() + * @see TwoFactorProvider::isShowSubmitButton */ public function isShowSubmitButton() { return false; @@ -447,7 +445,7 @@ class DuoProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::hasCustomInputForm() + * @see TwoFactorProvider::hasCustomInputForm */ public function hasCustomInputForm() { return true; @@ -455,7 +453,7 @@ class DuoProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\BaseProvider::addCustomInput() + * @see BaseProvider::addCustomInput */ public function addCustomInput(&$row, $userDn) { $pathPrefix = $this->config->isSelfService ? '../' : ''; @@ -482,7 +480,7 @@ class DuoProvider extends BaseProvider { $row->add(new htmlJavaScript($jsBlock)); } // start authentication - elseif (!empty($_GET['duoRedirect'])) { + else { include_once __DIR__ . '/3rdParty/composer/autoload.php'; try { $duoClient = new Client( @@ -512,7 +510,7 @@ class DuoProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::verify2ndFactor() + * @see TwoFactorProvider::verify2ndFactor */ public function verify2ndFactor($user, $password, $serial, $twoFactorInput) { logNewMessage(LOG_DEBUG, 'DuoProvider: Checking 2nd factor for ' . $user); @@ -571,7 +569,7 @@ class OktaProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::getSerials() + * @see TwoFactorProvider::getSerials */ public function getSerials($user, $password) { return ['OKTA']; @@ -579,7 +577,7 @@ class OktaProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::isShowSubmitButton() + * @see TwoFactorProvider::isShowSubmitButton */ public function isShowSubmitButton() { return false; @@ -587,7 +585,7 @@ class OktaProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::hasCustomInputForm() + * @see TwoFactorProvider::hasCustomInputForm */ public function hasCustomInputForm() { return true; @@ -596,7 +594,7 @@ class OktaProvider extends BaseProvider { /** * {@inheritDoc} * @throws LAMException error building custom input - * @see \LAM\LIB\TWO_FACTOR\BaseProvider::addCustomInput() + * @see BaseProvider::addCustomInput */ public function addCustomInput(&$row, $userDn) { if (($this->config->loginHandler === null) || !$this->config->loginHandler->managesAuthentication()) { @@ -636,7 +634,7 @@ class OktaProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::verify2ndFactor() + * @see TwoFactorProvider::verify2ndFactor */ public function verify2ndFactor($user, $password, $serial, $twoFactorInput) { $this->verificationFailed = true; @@ -755,7 +753,7 @@ class OpenIdProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::getSerials() + * @see TwoFactorProvider::getSerials */ public function getSerials($user, $password) { return ['OpenID']; @@ -763,7 +761,7 @@ class OpenIdProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::isShowSubmitButton() + * @see TwoFactorProvider::isShowSubmitButton */ public function isShowSubmitButton() { return false; @@ -771,7 +769,7 @@ class OpenIdProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::hasCustomInputForm() + * @see TwoFactorProvider::hasCustomInputForm */ public function hasCustomInputForm() { return true; @@ -780,7 +778,7 @@ class OpenIdProvider extends BaseProvider { /** * {@inheritDoc} * @throws LAMException error building custom input - * @see \LAM\LIB\TWO_FACTOR\BaseProvider::addCustomInput() + * @see BaseProvider::addCustomInput */ public function addCustomInput(&$row, $userDn) { $loginAttribute = ''; @@ -795,7 +793,7 @@ class OpenIdProvider extends BaseProvider { } $content = new htmlResponsiveRow(); $pathPrefix = $this->config->isSelfService ? '../' : ''; - $row->add(new htmlImage($pathPrefix . '../graphics/openid.png'), 12); + $row->add(new htmlImage($pathPrefix . '../graphics/openid.png')); include_once __DIR__ . '/3rdParty/composer/autoload.php'; try { $client = $this->getOpenIdClient(); @@ -863,7 +861,7 @@ class OpenIdProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::verify2ndFactor() + * @see TwoFactorProvider::verify2ndFactor */ public function verify2ndFactor($user, $password, $serial, $twoFactorInput) { $this->verificationFailed = true; @@ -927,7 +925,7 @@ class WebauthnProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::getSerials() + * @see TwoFactorProvider::getSerials */ public function getSerials($user, $password) { return ['WEBAUTHN']; @@ -935,7 +933,7 @@ class WebauthnProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::isShowSubmitButton() + * @see TwoFactorProvider::isShowSubmitButton */ public function isShowSubmitButton() { return false; @@ -943,7 +941,7 @@ class WebauthnProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::hasCustomInputForm() + * @see TwoFactorProvider::hasCustomInputForm */ public function hasCustomInputForm() { return true; @@ -951,26 +949,26 @@ class WebauthnProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\BaseProvider::addCustomInput() + * @see BaseProvider::addCustomInput */ public function addCustomInput(&$row, $userDn) { if (!extension_loaded('PDO')) { - $row->add(new htmlStatusMessage('ERROR', 'WebAuthn requires the PDO extension for PHP.'), 12); + $row->add(new htmlStatusMessage('ERROR', 'WebAuthn requires the PDO extension for PHP.')); return; } $pdoDrivers = \PDO::getAvailableDrivers(); if (!in_array('sqlite', $pdoDrivers)) { - $row->add(new htmlStatusMessage('ERROR', 'WebAuthn requires the sqlite PDO driver for PHP.'), 12); + $row->add(new htmlStatusMessage('ERROR', 'WebAuthn requires the sqlite PDO driver for PHP.')); return; } include_once __DIR__ . '/webauthn.inc'; $webauthnManager = $this->getWebauthnManager(); $hasTokens = $webauthnManager->isRegistered($userDn); if ($hasTokens) { - $row->add(new htmlStatusMessage('INFO', _('Please authenticate with your security device.')), 12); + $row->add(new htmlStatusMessage('INFO', _('Please authenticate with your security device.'))); } else { - $row->add(new htmlStatusMessage('INFO', _('Please register a security device.')), 12); + $row->add(new htmlStatusMessage('INFO', _('Please register a security device.'))); } $row->addVerticalSpacer('2rem'); $pathPrefix = $this->config->isSelfService ? '../' : ''; @@ -1006,7 +1004,7 @@ class WebauthnProvider extends BaseProvider { /** * {@inheritDoc} - * @see \LAM\LIB\TWO_FACTOR\TwoFactorProvider::verify2ndFactor() + * @see TwoFactorProvider::verify2ndFactor */ public function verify2ndFactor($user, $password, $serial, $twoFactorInput) { logNewMessage(LOG_DEBUG, 'WebauthnProvider: Checking 2nd factor for ' . $user); @@ -1050,22 +1048,22 @@ class WebauthnProvider extends BaseProvider { class TwoFactorProviderService { /** 2factor authentication disabled */ - const TWO_FACTOR_NONE = 'none'; + public const TWO_FACTOR_NONE = 'none'; /** 2factor authentication via privacyIDEA */ - const TWO_FACTOR_PRIVACYIDEA = 'privacyidea'; + public const TWO_FACTOR_PRIVACYIDEA = 'privacyidea'; /** 2factor authentication via YubiKey */ - const TWO_FACTOR_YUBICO = 'yubico'; + public const TWO_FACTOR_YUBICO = 'yubico'; /** 2factor authentication via DUO */ - const TWO_FACTOR_DUO = 'duo'; + public const TWO_FACTOR_DUO = 'duo'; /** 2factor authentication via webauthn */ - const TWO_FACTOR_WEBAUTHN = 'webauthn'; + public const TWO_FACTOR_WEBAUTHN = 'webauthn'; /** 2factor authentication via Okta */ - const TWO_FACTOR_OKTA = 'okta'; + public const TWO_FACTOR_OKTA = 'okta'; /** 2factor authentication via OpenId */ - const TWO_FACTOR_OPENID = 'openid'; + public const TWO_FACTOR_OPENID = 'openid'; /** date format when remembering devices */ - const DEVICE_REMEMBER_DATE_FORMAT = 'Y-m-d H:i:s'; + private const DEVICE_REMEMBER_DATE_FORMAT = 'Y-m-d H:i:s'; private TwoFactorConfiguration $config; diff --git a/lam/lib/account.inc b/lam/lib/account.inc index 9a961f67e..b2784a513 100644 --- a/lam/lib/account.inc +++ b/lam/lib/account.inc @@ -31,6 +31,7 @@ */ use LAM\PLUGINS\EXTRA_INVALID_CREDENTIALS\ExtraInvalidCredentials; +use LAM\TYPES\TypeManager; /** @@ -253,12 +254,12 @@ function generateSalt($len) { */ function pwd_enable($hash) { // check if password is disabled (old wrong LAM method) - if ((substr($hash, 0, 2) == "!{") || (substr($hash, 0, 2) == "*{")) { + if ((str_starts_with($hash, "!{")) || (str_starts_with($hash, "*{"))) { return substr($hash, 1, strlen($hash)); } // check for "!" or "*" at beginning of password hash else { - if (substr($hash, 0, 1) == "{") { + if (str_starts_with($hash, "{")) { $pos = strpos($hash, "}"); if ((substr($hash, $pos + 1, 1) == "!") || (substr($hash, $pos + 1, 1) == "*")) { // enable hash @@ -282,12 +283,12 @@ function pwd_enable($hash) { */ function pwd_disable($hash) { // check if password is disabled (old wrong LAM method) - if ((substr($hash, 0, 2) == "!{") || (substr($hash, 0, 2) == "*{")) { + if ((str_starts_with($hash, "!{")) || (str_starts_with($hash, "*{"))) { return $hash; } // check for "!" or "*" at beginning of password hash else { - if (substr($hash, 0, 1) == "{") { + if (str_starts_with($hash, "{")) { $pos = strpos($hash, "}"); if ((substr($hash, $pos + 1, 1) == "!") || (substr($hash, $pos + 1, 1) == "*")) { // hash already disabled @@ -315,10 +316,10 @@ function pwd_is_lockable($password) { return false; } // SASL is not lockable - if (strpos($password, '{SASL}') === 0) { + if (str_starts_with($password, '{SASL}')) { return false; } - return ((substr($password, 0, 1) == "{") || (substr($password, 1, 1) == "{")) && (strpos($password, "}") > 3); + return ((str_starts_with($password, "{")) || (substr($password, 1, 1) == "{")) && (strpos($password, "}") > 3); } /** @@ -329,10 +330,10 @@ function pwd_is_lockable($password) { */ function pwd_is_enabled($hash) { // disabled passwords have a "!" or "*" at the beginning (old wrong LAM method) - if ((substr($hash, 0, 2) == "!{") || (substr($hash, 0, 2) == "*{")) { + if ((str_starts_with($hash, "!{")) || (str_starts_with($hash, "*{"))) { return false; } - if (substr($hash, 0, 1) == "{") { + if (str_starts_with($hash, "{")) { $pos = strrpos($hash, "}"); // check if hash starts with "!" or "*" return ((substr($hash, $pos + 1, 1) !== "!") && (substr($hash, $pos + 1, 1) !== "*")); @@ -798,7 +799,7 @@ function searchLDAPByAttribute($name, $value, $objectClass, $attributes, $scopes elseif (sizeof($filterParts) > 1) { $filter = '(& ' . implode(' ', $filterParts) . ')'; } - $typeManager = new \LAM\TYPES\TypeManager(); + $typeManager = new TypeManager(); $activeTypes = $typeManager->getConfiguredTypes(); foreach ($activeTypes as $type) { if (!in_array($type->getScope(), $scopes)) { @@ -830,15 +831,15 @@ function searchLDAPByFilter($filter, $attributes, $scopes, $attrsOnly = false) { if ($attrsOnly) { $readAttributesOnly = 1; } - $typeManager = new \LAM\TYPES\TypeManager(); + $typeManager = new TypeManager(); $types = $typeManager->getConfiguredTypesForScopes($scopes); foreach ($types as $type) { $additionalFilter = $type->getAdditionalLdapFilter(); if (!empty($additionalFilter)) { - if (strpos($additionalFilter, '(') !== 0) { + if (!str_starts_with($additionalFilter, '(')) { $additionalFilter = '(' . $additionalFilter . ')'; } - if (strpos($filter, '(') !== 0) { + if (!str_starts_with($filter, '(')) { $filter = '(' . $filter . ')'; } $filter = '(&' . $additionalFilter . $filter . ')'; @@ -919,26 +920,35 @@ function searchLDAPPaged($server, $dn, $filter, $attributes, $attrsOnly, $limit) } $pageSize = 999; $cookie = ''; - $controls = [ - [ - 'oid' => LDAP_CONTROL_PAGEDRESULTS, - 'size' => $pageSize, - 'cookie' => $cookie] - ]; $return = []; do { + $controls = [ + [ + 'oid' => LDAP_CONTROL_PAGEDRESULTS, + 'value' => [ + 'size' => $pageSize, + 'cookie' => $cookie] + ] + ]; $sr = @ldap_search($server, $dn, $filter, $attributes, $attrsOnly, $limit, 0, LDAP_DEREF_NEVER, $controls); if (!$sr) { break; } + $errorCode = 0; + $matchedDn = ''; + $errorMessage = ''; + $referrals = []; + $resultControls = []; + ldap_parse_result($server, $sr, $errorCode , $matchedDn , $errorMessage , $referrals, $resultControls); $entries = ldap_get_entries($server, $sr); if (!$entries) { break; } $return = array_merge($return, $entries); + $cookie = $resultControls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? ''; } - while ($cookie !== null && $cookie != ''); + while ($cookie != ''); cleanLDAPResult($return); return $return; } @@ -1215,10 +1225,10 @@ function compareDN($a, $b): int { // get parts to compare $part_a = $array_a[$len_a - $i - 1]; $part_a = explode('=', $part_a); - $part_a = isset($part_a[1]) ? $part_a[1] : $part_a[0]; + $part_a = $part_a[1] ?? $part_a[0]; $part_b = $array_b[$len_b - $i - 1]; $part_b = explode('=', $part_b); - $part_b = isset($part_b[1]) ? $part_b[1] : $part_b[0]; + $part_b = $part_b[1] ?? $part_b[0]; // compare parts if ($part_a == $part_b) { // part is identical if ($i == ($len - 1)) { @@ -1315,7 +1325,7 @@ function isObfuscatedText($text) { return false; } $deob = base64_decode(str_rot13($text)); - return (strpos($deob, 'LAM_OBFUSCATE:') === 0); + return (str_starts_with($deob, 'LAM_OBFUSCATE:')); } /** @@ -1442,7 +1452,7 @@ function testSmtpConnection(string $server, string $user, string $password, stri * @return array list of arrays that can be used to create status messages */ function sendPasswordMail($pwd, $user, $recipient = null) { - $user = array_change_key_case($user, CASE_LOWER); + $user = array_change_key_case($user); // read mail data $cfgMain = $_SESSION['cfgMain']; $mailTo = null; @@ -1627,16 +1637,13 @@ class moduleCache { || (!empty($scope) && !ScopeAndModuleValidation::isValidScopeName($scope))) { return null; } - if (isset(self::$cache[$name . ':' . $scope])) { - return self::$cache[$name . ':' . $scope]; - } - else { + if (!isset(self::$cache[$name . ':' . $scope])) { if (!class_exists($name)) { return null; } self::$cache[$name . ':' . $scope] = new $name($scope); - return self::$cache[$name . ':' . $scope]; } + return self::$cache[$name . ':' . $scope]; } } @@ -1710,32 +1717,32 @@ function getExtendedLDAPErrorMessage($server) { function getDefaultLDAPErrorString($server) { $extError = htmlspecialchars(getExtendedLDAPErrorMessage($server)); // Active Directory message translations - if (strpos($extError, 'DSID') !== false) { - if (strpos($extError, '5003') !== false) { + if (str_contains($extError, 'DSID')) { + if (str_contains($extError, '5003')) { logNewMessage(LOG_DEBUG, 'Password change failed because of ' . $extError); $extError = _('Your password does not meet the password strength qualifications. Please retry with another one.'); } - elseif (strpos($extError, 'data 530,') !== false) { + elseif (str_contains($extError, 'data 530,')) { logNewMessage(LOG_DEBUG, 'Login failed because of ' . $extError); $extError = _('Logon not permitted at this time'); } - elseif (strpos($extError, 'data 532,') !== false) { + elseif (str_contains($extError, 'data 532,')) { logNewMessage(LOG_DEBUG, 'Login failed because of ' . $extError); $extError = _('Password expired'); } - elseif (strpos($extError, 'data 533,') !== false) { + elseif (str_contains($extError, 'data 533,')) { logNewMessage(LOG_DEBUG, 'Login failed because of ' . $extError); $extError = _('Account is deactivated'); } - elseif (strpos($extError, 'data 701,') !== false) { + elseif (str_contains($extError, 'data 701,')) { logNewMessage(LOG_DEBUG, 'Login failed because of ' . $extError); $extError = _('Account is expired'); } - elseif (strpos($extError, 'data 773,') !== false) { + elseif (str_contains($extError, 'data 773,')) { logNewMessage(LOG_DEBUG, 'Login failed because of ' . $extError); $extError = _('Password change required'); } - elseif (strpos($extError, 'data 775,') !== false) { + elseif (str_contains($extError, 'data 775,')) { logNewMessage(LOG_DEBUG, 'Login failed because of ' . $extError); $extError = _('Account is locked'); } @@ -1756,11 +1763,11 @@ function getDefaultLDAPErrorString($server) { */ function ldapIsPasswordExpired($server): bool { $extError = htmlspecialchars(getExtendedLDAPErrorMessage($server)); - if (strpos($extError, 'data 532,') !== false) { + if (str_contains($extError, 'data 532,')) { // password expired return true; } - elseif (strpos($extError, 'data 773,') !== false) { + elseif (str_contains($extError, 'data 773,')) { // password change required return true; } @@ -1946,7 +1953,7 @@ function printHeaderContents($title, $prefix) { $cssFiles = []; $cssEntry = $cssDir->read(); while ($cssEntry !== false) { - if (substr($cssEntry, strlen($cssEntry) - 4, 4) == '.css') { + if (str_ends_with($cssEntry, '.css')) { $cssFiles[] = $cssEntry; } $cssEntry = $cssDir->read(); @@ -1970,7 +1977,7 @@ function printJsIncludes($prefix) { $jsFiles = []; $jsEntry = $jsDir->read(); while ($jsEntry !== false) { - if ((substr($jsEntry, strlen($jsEntry) - 3, 3) == '.js') || (substr($jsEntry, strlen($jsEntry) - 4, 4) == '.php')) { + if ((str_ends_with($jsEntry, '.js')) || (str_ends_with($jsEntry, '.php'))) { $jsFiles[] = $jsEntry; } $jsEntry = $jsDir->read(); @@ -1991,7 +1998,7 @@ function convertUtf8ToUtf16Le($input) { return $input; } $output = iconv('UTF-8', 'UTF-16LE', $input); - if (($output === false) || ($output == '')) { + if (($output == '')) { $output = mb_convert_encoding($input, 'UTF-8', 'UTF-16LE'); } return $output; @@ -2017,7 +2024,7 @@ function getLAMVersionText() { * @return bool is developer version */ function isDeveloperVersion($version) { - return strpos($version, 'DEV') !== false; + return str_contains($version, 'DEV'); } /** diff --git a/lam/lib/adminHeader.inc b/lam/lib/adminHeader.inc index 2d67eea30..83833a06c 100644 --- a/lam/lib/adminHeader.inc +++ b/lam/lib/adminHeader.inc @@ -30,6 +30,7 @@ use htmlLink; use htmlOutputText; use htmlResponsiveRow; use htmlSpan; +use LAM\TYPES\TypeManager; use LAMException; use ServerProfilePersistenceManager; @@ -87,7 +88,7 @@ function printHeader(string $headerPrefix): void { continue; } // check if hidden by config - $toolClass = get_class($myTool); + $toolClass = $myTool::class; $toolName = substr($toolClass, strrpos($toolClass, '\\') + 1); if (!$_SESSION['config']->isToolActive($toolName)) { continue; @@ -140,7 +141,7 @@ function printHeader(string $headerPrefix): void {
getConfiguredTypes(); if (!empty($types)) { $accountTypesGroup = new htmlGroup(); diff --git a/lam/lib/baseModule.inc b/lam/lib/baseModule.inc index 94e61e9ab..c132749be 100644 --- a/lam/lib/baseModule.inc +++ b/lam/lib/baseModule.inc @@ -1,7 +1,7 @@ meta['ldap_filter'])) { - return $this->meta['ldap_filter']; - } - return ""; + return $this->meta['ldap_filter'] ?? ""; } /** @@ -500,10 +497,7 @@ abstract class baseModule { * @see baseModule::get_metaData() */ public function get_alias() { - if (isset($this->meta['alias'])) { - return $this->meta['alias']; - } - return static::class; + return $this->meta['alias'] ?? static::class; } /** @@ -523,10 +517,7 @@ abstract class baseModule { * @see baseModule::get_metaData() */ public function get_RDNAttributes($typeId) { - if (isset($this->meta['RDN'])) { - return $this->meta['RDN']; - } - return []; + return $this->meta['RDN'] ?? []; } /** @@ -548,10 +539,7 @@ abstract class baseModule { * @see baseModule::get_metaData() */ public function get_dependencies() { - if (isset($this->meta['dependencies'])) { - return $this->meta['dependencies']; - } - return ['depends' => [], 'conflicts' => []]; + return $this->meta['dependencies'] ?? ['depends' => [], 'conflicts' => []]; } /** @@ -571,10 +559,7 @@ abstract class baseModule { * @see htmlElement */ public function get_profileOptions($typeId) { - if (isset($this->meta['profile_options'])) { - return $this->meta['profile_options']; - } - return null; + return $this->meta['profile_options'] ?? null; } /** @@ -876,7 +861,7 @@ abstract class baseModule { * @see baseModule::get_metaData() */ public function get_pdfFields($typeId) { - return ((isset($this->meta['PDF_fields'])) ? $this->meta['PDF_fields'] : []); + return $this->meta['PDF_fields'] ?? []; } /** @@ -921,7 +906,7 @@ abstract class baseModule { * @param array $result result array (entry will be added here) * @param String $name ID * @param String $label label name - * @param mixed $value value as String or array + * @param string|array $value value as String or array * @param String $delimiter delimiter if value is array (default: ", ") */ public function addPDFKeyValue(&$result, $name, $label, $value, $delimiter = ', ') { @@ -985,10 +970,7 @@ abstract class baseModule { * @see baseModule::get_metaData() */ public function get_uploadColumns($selectedModules, &$type) { - if (isset($this->meta['upload_columns'])) { - return $this->meta['upload_columns']; - } - return []; + return $this->meta['upload_columns'] ?? []; } /** @@ -1003,10 +985,7 @@ abstract class baseModule { * @see baseModule::get_metaData() */ public function get_uploadPreDepends() { - if (isset($this->meta['upload_preDepends'])) { - return $this->meta['upload_preDepends']; - } - return []; + return $this->meta['upload_preDepends'] ?? []; } /** @@ -1091,7 +1070,7 @@ abstract class baseModule { } if (!$matched) { $errMsg = $message; - array_push($errMsg, [$position]); + $errMsg[] = [$position]; $errors[] = $errMsg; return false; } @@ -1350,7 +1329,7 @@ abstract class baseModule { * * @return array Array which contains status messages. Each entry is an array containing the status message parameters. */ - public abstract function process_attributes(); + abstract public function process_attributes(); /** * This function creates meta HTML code to display the module page. @@ -1361,7 +1340,7 @@ abstract class baseModule { * * @see htmlElement */ - public abstract function display_html_attributes(); + abstract public function display_html_attributes(); /** * Adds a simple text input field to the given htmlResponsiveRow. @@ -1442,7 +1421,7 @@ abstract class baseModule { } return; } - $this->attributes[$attrName][0] = isset($_POST[$attrName]) ? $_POST[$attrName] : ''; + $this->attributes[$attrName][0] = $_POST[$attrName] ?? ''; if ($required && (!isset($_POST[$attrName]) || ($_POST[$attrName] === ''))) { $errors[] = $this->messages[$attrName][0]; } @@ -1543,7 +1522,7 @@ abstract class baseModule { $container->addField($subContainer); } else { - $container->add($subContainer, 12); + $container->add($subContainer); } } @@ -1702,21 +1681,21 @@ abstract class baseModule { } // first select $firstRow = new htmlResponsiveRow(); - $firstRow->add(new htmlOutputText($labelFirst), 12); + $firstRow->add(new htmlOutputText($labelFirst)); $firstSelect = new htmlSelect($namePrefix . '_1', $optionsFirst, $selectedFirst, 15); $firstSelect->setHasDescriptiveElements(true); $firstSelect->setMultiSelect(true); $firstSelect->setRightToLeftTextDirection($rightToLeftText); $firstSelect->setSortElements(false); $firstSelect->enableDynamicScrolling(); - $firstRow->add($firstSelect, 12); + $firstRow->add($firstSelect); if ($showFilter) { $firstFilterGroup = new htmlGroup(); $firstFilterGroup->addElement(new htmlOutputText(_('Filter'))); $firstFilterInput = new htmlInputField($namePrefix . '_filterFirst'); $firstFilterInput->filterSelectBox($namePrefix . '_1'); $firstFilterGroup->addElement($firstFilterInput); - $firstRow->add($firstFilterGroup, 12); + $firstRow->add($firstFilterGroup); } $firstContainerDesktop = ($forceTablet) ? 12 : 5; $container->add($firstRow, 12, 12, $firstContainerDesktop); @@ -1734,21 +1713,21 @@ abstract class baseModule { $container->add($buttonRow, 12, 12, $buttonRowDesktop); // second select $secondRow = new htmlResponsiveRow(); - $secondRow->add(new htmlOutputText($labelSecond), 12); + $secondRow->add(new htmlOutputText($labelSecond)); $secondSelect = new htmlSelect($namePrefix . '_2', $optionsSecond, $selectedSecond, 15); $secondSelect->setHasDescriptiveElements(true); $secondSelect->setMultiSelect(true); $secondSelect->setRightToLeftTextDirection($rightToLeftText); $secondSelect->setSortElements(false); $secondSelect->enableDynamicScrolling(); - $secondRow->add($secondSelect, 12); + $secondRow->add($secondSelect); if ($showFilter) { $secondFilterGroup = new htmlGroup(); $secondFilterGroup->addElement(new htmlOutputText(_('Filter'))); $secondFilterInput = new htmlInputField($namePrefix . '_filterSecond'); $secondFilterInput->filterSelectBox($namePrefix . '_2'); $secondFilterGroup->addElement($secondFilterInput); - $secondRow->add($secondFilterGroup, 12); + $secondRow->add($secondFilterGroup); } $secondContainerDesktop = ($forceTablet) ? 12 : 6; $container->add($secondRow, 12, 12, $secondContainerDesktop); @@ -1772,7 +1751,7 @@ abstract class baseModule { if (!in_array($name, $fields)) { return; } - $ldapAttrName = ($attributeName === null) ? $name : $attributeName; + $ldapAttrName = $attributeName ?? $name; $value = ''; if (isset($attributes[$ldapAttrName][0])) { $value = $attributes[$ldapAttrName][0]; @@ -1822,7 +1801,7 @@ abstract class baseModule { $validationID = null, $validationMessage = null, $requiredMessage = null, $attributeName = null) { if (in_array($name, $fields) && !in_array($name, $readOnlyFields)) { $fieldName = static::class . '_' . $name; - $ldapAttrName = ($attributeName === null) ? $name : $attributeName; + $ldapAttrName = $attributeName ?? $name; if (!empty($_POST[$fieldName])) { if (($validationID != null) && !get_preg($_POST[$fieldName], $validationID)) { if ($validationMessage !== null) { @@ -1871,7 +1850,7 @@ abstract class baseModule { if (!in_array($name, $fields)) { return; } - $ldapAttrName = ($attributeName === null) ? $name : $attributeName; + $ldapAttrName = $attributeName ?? $name; $values = []; if (isset($attributes[$ldapAttrName][0])) { $values = $attributes[$ldapAttrName]; @@ -1922,9 +1901,9 @@ abstract class baseModule { } else { $inputField = new htmlOutputText($value); - $inputField->setPreformatted(true); + $inputField->setPreformatted(); } - $field->add($inputField, 12); + $field->add($inputField); } } $row = new htmlResponsiveRow(); @@ -1954,10 +1933,10 @@ abstract class baseModule { $validationID = null, $validationMessage = null, $requiredMessage = null, $attributeName = null) { if (in_array($name, $fields) && !in_array($name, $readOnlyFields)) { $fieldName = static::class . '_' . $name; - $ldapAttrName = ($attributeName === null) ? $name : $attributeName; + $ldapAttrName = $attributeName ?? $name; $valuesNew = []; foreach ($_POST as $postKey => $postValue) { - if (strpos($postKey, $fieldName) === false) { + if (!str_contains($postKey, $fieldName)) { continue; } if ($postValue === '') { @@ -1977,7 +1956,7 @@ abstract class baseModule { if (empty($valuesNew) && ($requiredMessage !== null)) { $container['messages'][] = $requiredMessage; } - $valuesOld = isset($attributes[$ldapAttrName]) ? $attributes[$ldapAttrName] : []; + $valuesOld = $attributes[$ldapAttrName] ?? []; $intersect = array_intersect($valuesOld, $valuesNew); if ((sizeof($valuesOld) != sizeof($valuesNew)) || (sizeof($intersect) != sizeof($valuesOld))) { $container['mod'][$ldapAttrName] = $valuesNew; @@ -2206,12 +2185,7 @@ abstract class baseModule { * @see htmlElement */ public function getSelfServiceSettings($profile) { - if (isset($this->meta['selfServiceSettings'])) { - return $this->meta['selfServiceSettings']; - } - else { - return null; - } + return $this->meta['selfServiceSettings'] ?? null; } /** diff --git a/lam/lib/baseType.inc b/lam/lib/baseType.inc index ee3b33663..2c00b13ac 100644 --- a/lam/lib/baseType.inc +++ b/lam/lib/baseType.inc @@ -253,17 +253,17 @@ class baseType { if (!$radioDisabled) { $radio = new htmlRadio('lam_accountStatusAction', [_('Lock') => 'lock', _('Unlock') => 'unlock'], $selectedRadio); $radio->setOnchangeEvent($onchange); - $container->add($radio, 12); + $container->add($radio); } else { $radio = new htmlRadio('lam_accountStatusActionDisabled', [_('Lock') => 'lock', _('Unlock') => 'unlock'], $selectedRadio); $radio->setIsEnabled(false); - $container->add($radio, 12); - $container->add(new htmlHiddenInput('lam_accountStatusAction', $selectedRadio), 12); + $container->add($radio); + $container->add(new htmlHiddenInput('lam_accountStatusAction', $selectedRadio)); } $container->addVerticalSpacer('1rem'); - $container->add(new htmlHiddenInput('lam_accountStatusResult', 'cancel'), 12); + $container->add(new htmlHiddenInput('lam_accountStatusResult', 'cancel')); // locking part if ($hasLockOptions) { @@ -349,7 +349,7 @@ class baseType { if ($_POST['lam_accountStatusAction'] == 'lock') { $lockIds = []; foreach ($_POST as $key => $value) { - if (($value === 'on') && (strpos($key, 'lam_accountStatusLock_') === 0)) { + if (($value === 'on') && (str_starts_with($key, 'lam_accountStatusLock_'))) { $lockIds[] = substr($key, strlen('lam_accountStatusLock_')); } } @@ -366,7 +366,7 @@ class baseType { elseif ($_POST['lam_accountStatusAction'] == 'unlock') { $unlockIds = []; foreach ($_POST as $key => $value) { - if (($value === 'on') && (strpos($key, 'lam_accountStatusUnlock_') === 0)) { + if (($value === 'on') && (str_starts_with($key, 'lam_accountStatusUnlock_'))) { $unlockIds[] = substr($key, strlen('lam_accountStatusUnlock_')); } } diff --git a/lam/lib/checkEnvironment.inc b/lam/lib/checkEnvironment.inc index 2830ee277..84a282f95 100644 --- a/lam/lib/checkEnvironment.inc +++ b/lam/lib/checkEnvironment.inc @@ -129,8 +129,7 @@ if (ini_get("session.auto_start") == "1") { } // check memory limit $memLimit = ini_get('memory_limit'); -if (isset($memLimit) - && ($memLimit != '') +if (($memLimit != '') && (substr(strtoupper($memLimit), strlen($memLimit) - 1) == 'M') && (intval(substr($memLimit, 0, strlen($memLimit) - 1)) < 128)) { $criticalErrors[] = ["ERROR", "Please increase the \"memory_limit\" parameter in your php.ini to at least \"128M\".", @@ -168,9 +167,6 @@ if (!empty($criticalErrors)) { echo "\n"; printHeaderContents('LDAP Account Manager', '..'); echo "\n"; - if (empty($criticalErrors)) { - displayLoginHeader(); - } foreach ($criticalErrors as $criticalError) { call_user_func_array("StatusMessage", $criticalError); echo "

"; diff --git a/lam/lib/config.inc b/lam/lib/config.inc index 62144308e..fa49cdfb1 100644 --- a/lam/lib/config.inc +++ b/lam/lib/config.inc @@ -1,12 +1,13 @@ getSSLCaCertPath(); if ($sslCaPath != null) { @@ -101,11 +96,8 @@ function setlanguage() { if (!is_string($bindTextResult)) { logNewMessage(LOG_WARNING, "Unable to bind text domain, check if 'locale -a' returns $code"); } - $textDomainResult = textdomain("messages"); - if (!is_string($textDomainResult)) { - logNewMessage(LOG_WARNING, "Unable to set text domain, check if 'locale -a' returns $code"); - } - header("Content-type: text/html; charset=" . $encoding, true); + textdomain("messages"); + header("Content-type: text/html; charset=" . $encoding); } /** @@ -404,7 +396,7 @@ class ServerProfilePersistenceManager { } $copyFromTemplate = true; $existingTemplateNames = $this->getConfigTemplates(); - if (strpos($templateName, '.sample') !== false) { + if (str_contains($templateName, '.sample')) { $templateNameShort = str_replace('.sample', '', $templateName); if (!in_array($templateNameShort, $existingTemplateNames)) { throw new LAMException(_("Profile name is invalid!")); @@ -558,7 +550,7 @@ class ServerProfilePersistenceStrategyFiles implements ServerProfilePersistenceS $ext = substr($entry, strlen($entry) - 5, 5); $name = substr($entry, 0, strlen($entry) - 5); // check if extension is right, add to profile list - if (($ext == ".conf") && (strpos($name, '.sample') === false) && is_readable($dirName . '/' . $entry)) { + if (($ext == ".conf") && (!str_contains($name, '.sample')) && is_readable($dirName . '/' . $entry)) { $ret[] = $name; } } @@ -601,7 +593,7 @@ class ServerProfilePersistenceStrategyFiles implements ServerProfilePersistenceS $property->setAccessible(true); $property->setValue($config, ''); } - catch (ReflectionException $e) { + catch (ReflectionException) { // ignore } } @@ -612,7 +604,7 @@ class ServerProfilePersistenceStrategyFiles implements ServerProfilePersistenceS $property->setAccessible(true); $property->setValue($config, substr($line, $startIndex)); } - catch (ReflectionException $e) { + catch (ReflectionException) { // ignore } } @@ -1237,7 +1229,7 @@ class LAMConfig { $allTypes = LAM\TYPES\getTypes(); $activeTypes = $this->get_ActiveTypes(); for ($i = 0; $i < sizeof($activeTypes); $i++) { - if (!in_array(\LAM\TYPES\getScopeFromTypeId($activeTypes[$i]), $allTypes)) { + if (!in_array(getScopeFromTypeId($activeTypes[$i]), $allTypes)) { unset($activeTypes[$i]); } } @@ -1252,7 +1244,7 @@ class LAMConfig { $types = $this->get_ActiveTypes(); $availableByScope = []; foreach ($types as $type) { - $scope = \LAM\TYPES\getScopeFromTypeId($type); + $scope = getScopeFromTypeId($type); $moduleVar = "modules_" . $type; if (isset($this->typeSettings[$moduleVar])) { $modules = explode(",", $this->typeSettings[$moduleVar]); @@ -1513,14 +1505,14 @@ class LAMConfig { * @return boolean true, if matches */ public function check_Passwd($password) { - if (strpos($this->Passwd, "{SSHA}") === 0) { + if (str_starts_with($this->Passwd, "{SSHA}")) { $value = substr($this->Passwd, strlen("{SSHA}")); $parts = explode(" ", $value); $salt = base64_decode($parts[1]); $hash = "{SSHA}" . base64_encode(hex2bin(sha1($password . $salt))) . " " . base64_encode($salt); return ($hash === $this->Passwd); } - elseif (strpos($this->Passwd, "{CRYPT-SHA512}") === 0) { + elseif (str_starts_with($this->Passwd, "{CRYPT-SHA512}")) { $value = substr($this->Passwd, strlen("{CRYPT-SHA512}")); $parts = explode(" ", $value); $salt = base64_decode($parts[1]); @@ -1740,8 +1732,8 @@ class LAMConfig { } $serverSettings = explode(':', $serverChunk); $serverName = $serverSettings[0]; - $serverLabel = isset($serverSettings[1]) ? $serverSettings[1] : null; - $serverHomedirPrefix = isset($serverSettings[2]) ? $serverSettings[2] : null; + $serverLabel = $serverSettings[1] ?? null; + $serverHomedirPrefix = $serverSettings[2] ?? null; $servers[] = new RemoteServerConfiguration($serverName, $serverLabel, $serverHomedirPrefix, $scriptPath, $userName, $sshKey, $sshKeyPassword); } return $servers; @@ -1795,18 +1787,18 @@ class LAMConfig { $valid_ips = []; foreach ($array_string as $arr_value) { // Explode name and IP, if a name exists - if (preg_match("/:/", $arr_value)) { + if (str_contains($arr_value, ":")) { $arr_value_explode = explode(":", $arr_value); $servername = $arr_value_explode[0]; $label = $arr_value_explode[1]; - $homedirPrefix = isset($arr_value_explode[2]) ? $arr_value_explode[2] : ''; + $homedirPrefix = $arr_value_explode[2] ?? ''; } else { $servername = $arr_value; $label = ''; $homedirPrefix = ''; } - if (isset($servername) && is_string($servername) && preg_match("/^[a-z0-9-]+(\\.[a-z0-9-]+)*(,[0-9]+)?$/i", $servername)) { + if (preg_match("/^[a-z0-9-]+(\\.[a-z0-9-]+)*(,[0-9]+)?$/i", $servername)) { $serverData = [$servername]; if (!empty($label)) { $serverData[] = $label; @@ -3423,7 +3415,7 @@ class LAMCfgMain { if (($configLine === false) || ($configLine === "") || ($configLine === "\n") || ($configLine[0] == "#")) { continue; // ignore comments and empty lines } - array_push($file_array, $configLine); + $file_array[] = $configLine; } fclose($file); // generate new configuration file @@ -3451,116 +3443,116 @@ class LAMCfgMain { if (!$persistenceOnly) { // check if we have to add new entries (e.g. if user upgraded LAM and has an old config file) if (!in_array("password", $saved)) { - array_push($file_array, "password: " . $this->password . "\n"); + $file_array[] = "password: " . $this->password . "\n"; } if (!in_array("default", $saved)) { - array_push($file_array, "default: " . $this->default . "\n"); + $file_array[] = "default: " . $this->default . "\n"; } if (!in_array("sessionTimeout", $saved)) { - array_push($file_array, "sessionTimeout: " . $this->sessionTimeout . "\n"); + $file_array[] = "sessionTimeout: " . $this->sessionTimeout . "\n"; } if (!in_array("hideLoginErrorDetails", $saved)) { - array_push($file_array, "hideLoginErrorDetails: " . $this->hideLoginErrorDetails . "\n"); + $file_array[] = "hideLoginErrorDetails: " . $this->hideLoginErrorDetails . "\n"; } if (!in_array("logLevel", $saved)) { - array_push($file_array, "logLevel: " . $this->logLevel . "\n"); + $file_array[] = "logLevel: " . $this->logLevel . "\n"; } if (!in_array("logDestination", $saved)) { - array_push($file_array, "logDestination: " . $this->logDestination . "\n"); + $file_array[] = "logDestination: " . $this->logDestination . "\n"; } if (!in_array("allowedHosts", $saved)) { - array_push($file_array, "allowedHosts: " . $this->allowedHosts . "\n"); + $file_array[] = "allowedHosts: " . $this->allowedHosts . "\n"; } if (!in_array("allowedHostsSelfService", $saved)) { - array_push($file_array, "allowedHostsSelfService: " . $this->allowedHostsSelfService . "\n"); + $file_array[] = "allowedHostsSelfService: " . $this->allowedHostsSelfService . "\n"; } if (!in_array("passwordMinLength", $saved)) { - array_push($file_array, "passwordMinLength: " . $this->passwordMinLength . "\n"); + $file_array[] = "passwordMinLength: " . $this->passwordMinLength . "\n"; } if (!in_array("passwordMinUpper", $saved)) { - array_push($file_array, "passwordMinUpper: " . $this->passwordMinUpper . "\n"); + $file_array[] = "passwordMinUpper: " . $this->passwordMinUpper . "\n"; } if (!in_array("passwordMinLower", $saved)) { - array_push($file_array, "passwordMinLower: " . $this->passwordMinLower . "\n"); + $file_array[] = "passwordMinLower: " . $this->passwordMinLower . "\n"; } if (!in_array("passwordMinNumeric", $saved)) { - array_push($file_array, "passwordMinNumeric: " . $this->passwordMinNumeric . "\n"); + $file_array[] = "passwordMinNumeric: " . $this->passwordMinNumeric . "\n"; } if (!in_array("passwordMinSymbol", $saved)) { - array_push($file_array, "passwordMinSymbol: " . $this->passwordMinSymbol . "\n"); + $file_array[] = "passwordMinSymbol: " . $this->passwordMinSymbol . "\n"; } if (!in_array("passwordMinClasses", $saved)) { - array_push($file_array, "passwordMinClasses: " . $this->passwordMinClasses . "\n"); + $file_array[] = "passwordMinClasses: " . $this->passwordMinClasses . "\n"; } if (!in_array("checkedRulesCount", $saved)) { - array_push($file_array, "checkedRulesCount: " . $this->checkedRulesCount . "\n"); + $file_array[] = "checkedRulesCount: " . $this->checkedRulesCount . "\n"; } if (!in_array("passwordMustNotContain3Chars", $saved)) { - array_push($file_array, "passwordMustNotContain3Chars: " . $this->passwordMustNotContain3Chars . "\n"); + $file_array[] = "passwordMustNotContain3Chars: " . $this->passwordMustNotContain3Chars . "\n"; } if (!in_array("passwordMustNotContainUser", $saved)) { - array_push($file_array, "passwordMustNotContainUser: " . $this->passwordMustNotContainUser . "\n"); + $file_array[] = "passwordMustNotContainUser: " . $this->passwordMustNotContainUser . "\n"; } if (!in_array("externalPwdCheckUrl", $saved)) { - array_push($file_array, "externalPwdCheckUrl: " . $this->externalPwdCheckUrl . "\n"); + $file_array[] = "externalPwdCheckUrl: " . $this->externalPwdCheckUrl . "\n"; } if (!in_array("errorReporting", $saved)) { - array_push($file_array, "errorReporting: " . $this->errorReporting . "\n"); + $file_array[] = "errorReporting: " . $this->errorReporting . "\n"; } if (!in_array("license", $saved)) { - array_push($file_array, "license: " . $this->license . "\n"); + $file_array[] = "license: " . $this->license . "\n"; } if (!in_array("licenseEmailFrom", $saved)) { - array_push($file_array, "licenseEmailFrom: " . $this->licenseEmailFrom . "\n"); + $file_array[] = "licenseEmailFrom: " . $this->licenseEmailFrom . "\n"; } if (!in_array("licenseEmailTo", $saved)) { - array_push($file_array, "licenseEmailTo: " . $this->licenseEmailTo . "\n"); + $file_array[] = "licenseEmailTo: " . $this->licenseEmailTo . "\n"; } if (!in_array("licenseEmailDateSent", $saved)) { - array_push($file_array, "licenseEmailDateSent: " . $this->licenseEmailDateSent . "\n"); + $file_array[] = "licenseEmailDateSent: " . $this->licenseEmailDateSent . "\n"; } if (!in_array("licenseWarningType", $saved)) { - array_push($file_array, "licenseWarningType: " . $this->licenseWarningType . "\n"); + $file_array[] = "licenseWarningType: " . $this->licenseWarningType . "\n"; } if (!in_array("mailServer", $saved)) { - array_push($file_array, "mailServer: " . $this->mailServer . "\n"); + $file_array[] = "mailServer: " . $this->mailServer . "\n"; } if (!in_array("mailUser", $saved)) { - array_push($file_array, "mailUser: " . $this->mailUser . "\n"); + $file_array[] = "mailUser: " . $this->mailUser . "\n"; } if (!in_array("mailPassword", $saved)) { - array_push($file_array, "mailPassword: " . $this->mailPassword . "\n"); + $file_array[] = "mailPassword: " . $this->mailPassword . "\n"; } if (!in_array("mailEncryption", $saved)) { - array_push($file_array, "mailEncryption: " . $this->mailEncryption . "\n"); + $file_array[] = "mailEncryption: " . $this->mailEncryption . "\n"; } if (!in_array("mailAttribute", $saved)) { - array_push($file_array, "mailAttribute: " . $this->mailAttribute . "\n"); + $file_array[] = "mailAttribute: " . $this->mailAttribute . "\n"; } if (!in_array("mailBackupAttribute", $saved)) { - array_push($file_array, "mailBackupAttribute: " . $this->mailBackupAttribute . "\n"); + $file_array[] = "mailBackupAttribute: " . $this->mailBackupAttribute . "\n"; } } if (!in_array("configDatabaseType", $saved)) { - array_push($file_array, "configDatabaseType: " . $this->configDatabaseType . "\n"); + $file_array[] = "configDatabaseType: " . $this->configDatabaseType . "\n"; } if (!in_array("configDatabaseServer", $saved)) { - array_push($file_array, "configDatabaseServer: " . $this->configDatabaseServer . "\n"); + $file_array[] = "configDatabaseServer: " . $this->configDatabaseServer . "\n"; } if (!in_array("configDatabasePort", $saved)) { - array_push($file_array, "configDatabasePort: " . $this->configDatabasePort . "\n"); + $file_array[] = "configDatabasePort: " . $this->configDatabasePort . "\n"; } if (!in_array("configDatabaseName", $saved)) { - array_push($file_array, "configDatabaseName: " . $this->configDatabaseName . "\n"); + $file_array[] = "configDatabaseName: " . $this->configDatabaseName . "\n"; } if (!in_array("configDatabaseUser", $saved)) { - array_push($file_array, "configDatabaseUser: " . $this->configDatabaseUser . "\n"); + $file_array[] = "configDatabaseUser: " . $this->configDatabaseUser . "\n"; } if (!in_array("configDatabasePassword", $saved)) { - array_push($file_array, "configDatabasePassword: " . $this->configDatabasePassword . "\n"); + $file_array[] = "configDatabasePassword: " . $this->configDatabasePassword . "\n"; } if (!in_array("moduleSettings", $saved)) { - array_push($file_array, "moduleSettings: " . $this->moduleSettings . "\n"); + $file_array[] = "moduleSettings: " . $this->moduleSettings . "\n"; } $file = @fopen($this->conffile, "w"); @@ -3591,14 +3583,14 @@ class LAMCfgMain { * @return boolean true, if password matches */ public function checkPassword($password) { - if (strpos($this->password, "{SSHA}") === 0) { + if (str_starts_with($this->password, "{SSHA}")) { $value = substr($this->password, strlen("{SSHA}")); $parts = explode(" ", $value); $salt = base64_decode($parts[1]); $hash = "{SSHA}" . base64_encode(hex2bin(sha1($password . $salt))) . " " . base64_encode($salt); return ($hash === $this->password); } - elseif (strpos($this->password, "{CRYPT-SHA512}") === 0) { + elseif (str_starts_with($this->password, "{CRYPT-SHA512}")) { $value = substr($this->password, strlen("{CRYPT-SHA512}")); $parts = explode(" ", $value); $salt = base64_decode($parts[1]); @@ -3678,7 +3670,7 @@ class LAMCfgMain { * @return mixed TRUE if format is correct, error message if file is not accepted */ public function uploadSSLCaCert($cert) { - if (strpos($cert, '-----BEGIN CERTIFICATE-----') === false) { + if (!str_contains($cert, '-----BEGIN CERTIFICATE-----')) { $pem = @chunk_split(@base64_encode($cert), 64, "\n"); $cert = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n"; } @@ -3817,14 +3809,14 @@ class LAMCfgMain { if (empty($content)) { return []; } - if (!(strpos($content, '-----BEGIN CERTIFICATE-----') === 0)) { + if (!(str_starts_with($content, '-----BEGIN CERTIFICATE-----'))) { return []; } $lines = explode("\n", $content); $list = []; $pos = -1; foreach ($lines as $line) { - if (strpos($line, '-----BEGIN CERTIFICATE-----') === 0) { + if (str_starts_with($line, '-----BEGIN CERTIFICATE-----')) { $pos++; } if (!isset($list[$pos])) { diff --git a/lam/lib/export.inc b/lam/lib/export.inc index 609efd18c..0b1cae01d 100644 --- a/lam/lib/export.inc +++ b/lam/lib/export.inc @@ -2,8 +2,8 @@ namespace LAM\TOOLS\IMPORT_EXPORT; -use \htmlStatusMessage; -use \LAMException; +use htmlStatusMessage; +use LAMException; use LamTemporaryFilesManager; /* @@ -45,10 +45,10 @@ include_once('ldap.inc'); */ class Exporter { - const DATA = 'data'; - const STATUS = 'status'; - const FILE = 'file'; - const OUTPUT = 'output'; + private const DATA = 'data'; + private const STATUS = 'status'; + private const FILE = 'file'; + private const OUTPUT = 'output'; private $baseDn; private $searchScope; @@ -94,10 +94,10 @@ class Exporter { return $this->writeDataAndReturnJson($results); } catch (LAMException $e) { - $data = Exporter::formatMessage('ERROR', $e->getTitle(), $e->getMessage()); + $data = self::formatMessage('ERROR', $e->getTitle(), $e->getMessage()); $status = [ - Exporter::STATUS => 'failed', - Exporter::DATA => $data + self::STATUS => 'failed', + self::DATA => $data ]; return json_encode($status); } @@ -184,13 +184,13 @@ class Exporter { fwrite($handle, $output); fclose($handle); return json_encode([ - Exporter::FILE => $temporaryFilesManager->getDownloadLink($filename), - Exporter::STATUS => 'done' + self::FILE => $temporaryFilesManager->getDownloadLink($filename), + self::STATUS => 'done' ]); } return json_encode([ - Exporter::OUTPUT => htmlspecialchars($output, ENT_NOQUOTES), - Exporter::STATUS => 'done' + self::OUTPUT => htmlspecialchars($output, ENT_NOQUOTES), + self::STATUS => 'done' ]); } @@ -214,7 +214,7 @@ class Exporter { sort($attributeNames); array_unshift($attributeNames, 'dn'); - $attributeNamesQuoted = array_map([$this, 'escapeCsvAndAddQuotes'], $attributeNames); + $attributeNamesQuoted = array_map($this->escapeCsvAndAddQuotes(...), $attributeNames); $output = ''; // header $output .= implode(',', $attributeNamesQuoted) . $lineEnding; @@ -250,12 +250,11 @@ class Exporter { /** * Converts the given LDAP entries to LDIF format. * - * @param string $entries entries + * @param array $entries entries * @param string $lineEnding line ending */ private function getLdifOutput(&$entries, $lineEnding) { - $output = ''; - $output .= '#' . $lineEnding; + $output = '#' . $lineEnding; $output .= '# ' . _('Base DN') . ': ' . $this->baseDn . $lineEnding; $output .= '# ' . _('Search scope') . ': ' . $this->searchScope . $lineEnding; $output .= '# ' . _('Search filter') . ': ' . $this->filter . $lineEnding; diff --git a/lam/lib/html.inc b/lam/lib/html.inc index 1feb00be8..b5475f3a4 100644 --- a/lam/lib/html.inc +++ b/lam/lib/html.inc @@ -267,39 +267,33 @@ class htmlTable extends htmlElement { /** * Adds an element to the table. * - * @param mixed $element htmlElement object or a simple string - * @param boolean $newLine adds a new line after the element (optional, default false) - * @param boolean $isTableHeadElement specifies if this is a head or body element (default: body) - */ - public function addElement($element, $newLine = false, $isTableHeadElement = false) { - // add cell element - if ($element instanceof htmlElement) { - // check if a row needs to be opened - if (!$this->rowOpen) { - $this->elements[] = "\n"; - $this->rowOpen = true; - } - // check if alignment option was given - $align = $element->getAlignmentString(); - $colspan = $element->getColspanString(); - $rowspan = $element->getRowspanString(); - $css = ''; - if (sizeof($element->getTableCellCSSClasses()) > 0) { - $css = 'class="' . implode(' ', $element->getTableCellCSSClasses()) . '"'; - } - $tagName = 'td'; - if ($isTableHeadElement) { - $tagName = 'th'; - } - $this->elements[] = "<$tagName $align $colspan $rowspan $css>\n"; - $this->elements[] = $element; - $this->elements[] = "\n"; - if ($newLine) { - $this->addNewLine(); - } + * @param htmlElement $element htmlElement object or a simple string + * @param bool $newLine adds a new line after the element (optional, default false) + * @param bool $isTableHeadElement specifies if this is a head or body element (default: body) + */ + public function addElement(htmlElement $element, bool $newLine = false, bool $isTableHeadElement = false): void { + // check if a row needs to be opened + if (!$this->rowOpen) { + $this->elements[] = "\n"; + $this->rowOpen = true; } - else { - StatusMessage('ERROR', 'Invalid element', print_r($element, true)); + // check if alignment option was given + $align = $element->getAlignmentString(); + $colspan = $element->getColspanString(); + $rowspan = $element->getRowspanString(); + $css = ''; + if (sizeof($element->getTableCellCSSClasses()) > 0) { + $css = 'class="' . implode(' ', $element->getTableCellCSSClasses()) . '"'; + } + $tagName = 'td'; + if ($isTableHeadElement) { + $tagName = 'th'; + } + $this->elements[] = "<$tagName $align $colspan $rowspan $css>\n"; + $this->elements[] = $element; + $this->elements[] = "\n"; + if ($newLine) { + $this->addNewLine(); } } @@ -382,12 +376,9 @@ class htmlTable extends htmlElement { /** * Merges the content of another htmlTable object into this table. * - * @param $table table to get elements + * @param htmlTable $table table to get elements */ - public function mergeTableElements($table) { - if (is_null($table) || !($table instanceof htmlTable)) { - return; - } + public function mergeTableElements(htmlTable $table) { // remove obsolete new lines at the end if ($table->elements[sizeof($table->elements) - 1] == self::NEWLINE) { unset($table->elements[sizeof($table->elements) - 1]); @@ -1220,18 +1211,16 @@ class htmlAccountPageButton extends htmlButton { /** * Constructor * - * @param String $targetModule module name which renders next page - * @param String $targetPage name of next page - * @param String $identifier identifier for button - * @param String $value button text or image (16x16px, relative to graphics folder) - * @param String $isImageButton image or text button (default text) - * @param String $title title to show + * @param string $targetModule module name which renders next page + * @param string $targetPage name of next page + * @param string $identifier identifier for button + * @param string $value button text or image (16x16px, relative to graphics folder) + * @param bool $isImageButton image or text button (default text) + * @param string|null $title title to show */ - function __construct($targetModule, $targetPage, $identifier, $value, $isImageButton = false, $title = null) { - $this->name = htmlspecialchars('form_subpage_' . $targetModule . '_' . $targetPage . '_' . $identifier); - $this->value = $value; - $this->isImageButton = $isImageButton; - if ($title != null) { + public function __construct(string $targetModule, string $targetPage, string $identifier, string $value, bool $isImageButton = false, ?string $title = null) { + parent::__construct('form_subpage_' . $targetModule . '_' . $targetPage . '_' . $identifier, $value, $isImageButton); + if ($title !== null) { $this->setTitle($title); } } @@ -1431,16 +1420,13 @@ class htmlSelect extends htmlElement { if (isset($this->optionCssClasses[$value])) { $optionClass = 'class="' . $this->optionCssClasses[$value] . '"'; } + if (in_array($value, $this->selectedElements) || (empty($this->selectedElements) && empty($value))) { + $selected = ' selected'; + } if ($this->hasDescriptiveElements) { - if (in_array($value, $this->selectedElements) || (empty($this->selectedElements) && empty($value))) { - $selected = ' selected'; - } echo "\n"; } else { - if (in_array($value, $this->selectedElements) || (empty($this->selectedElements) && empty($value))) { - $selected = ' selected'; - } echo "" . htmlspecialchars($value) . "\n"; } } @@ -1790,12 +1776,12 @@ class htmlRadio extends htmlElement { * Creates the JavaScript code to hide/show table rows based on the select value. * * @param int $counter index - * @return String onChange code + * @return string onChange code */ - private function getOnchangeCodeForShowHideTableRows($counter) { + private function getOnchangeCodeForShowHideTableRows($counter): string { $onChange = ''; if ((sizeof($this->tableRowsToHide) == 0) && (sizeof($this->tableRowsToShow) == 0)) { - return; + return $onChange; } $values = []; if (!empty($this->tableRowsToHide)) { @@ -3132,8 +3118,7 @@ class htmlLink extends htmlElement { } $idAttr = ''; if (!empty($this->id)) { - $id = !empty($this->id) ? $this->id : 'a_' . preg_replace('/[^a-zA-Z0-9_]+/', '_', $this->target); - $idAttr = ' id="' . $id . '"'; + $idAttr = ' id="' . $this->id . '"'; } $classAttr = ''; if (sizeof($this->cssClasses) > 0) { @@ -3734,9 +3719,9 @@ class htmlAccordion extends htmlElement { * * @param String $id HTML ID * @param array $elements list of content elements array('title' => htmlElement) - * @param String $openInitial index of element that is initially opened (default: 0), set to 'false' to close all + * @param mixed $openInitial index of element that is initially opened (default: 0), set to 'false' to close all */ - function __construct($id, $elements, $openInitial = 0) { + function __construct($id, $elements, mixed $openInitial = 0) { $this->id = $id; $this->elements = $elements; $this->openInitial = $openInitial; @@ -3950,7 +3935,7 @@ class htmlResponsiveRow extends htmlElement { * @param string $space space in px or rem */ public function addVerticalSpacer($space) { - $this->add(new htmlSpacer(null, $space), 12); + $this->add(new htmlSpacer(null, $space)); } /** diff --git a/lam/lib/modules/fixed_ip.inc b/lam/lib/modules/fixed_ip.inc index c0d1175e2..2aa5af725 100644 --- a/lam/lib/modules/fixed_ip.inc +++ b/lam/lib/modules/fixed_ip.inc @@ -1,8 +1,8 @@ get_scope(), ['dhcp']); + return $this->get_scope() === 'dhcp'; } /** @@ -404,7 +404,7 @@ class fixed_ip extends baseModule { public function display_html_attributes() { $return = new htmlResponsiveRow(); if ($this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0] == "") { - $return->add(new htmlStatusMessage('ERROR', _("Please fill out the DHCP settings first.")), 12); + $return->add(new htmlStatusMessage('ERROR', _("Please fill out the DHCP settings first."))); return $return; } $this->initCache(); @@ -508,17 +508,17 @@ class fixed_ip extends baseModule { $table = new htmlResponsiveTable($titles, $data); $table->setWidths(['20%', '20%', '20%', '25%', '10%', '5%']); $table->colspan = 100; - $return->add($table, 12); + $return->add($table); foreach ($messages as $message) { - $return->add($message, 12); + $return->add($message); } // add existing host entry if (!empty($this->hostCache)) { $return->addVerticalSpacer('2rem'); $addHostButton = new htmlAccountPageButton(static::class, 'addHost', 'add', _('Add existing host')); - $return->add($addHostButton, 12); + $return->add($addHostButton); } return $return; } @@ -534,7 +534,7 @@ class fixed_ip extends baseModule { foreach ($this->existingDhcpHostsCache as &$host) { if ($name === $host['name']) { $dn = $host['dn']; - if ($this->getAccountContainer()->isNewAccount || strpos($dn, $this->getAccountContainer()->dn_orig) === false) { + if ($this->getAccountContainer()->isNewAccount || !str_contains($dn, $this->getAccountContainer()->dn_orig)) { return [$dn, $this->getHostNameSuggestion($name)]; } } @@ -602,7 +602,7 @@ class fixed_ip extends baseModule { } $select = new htmlResponsiveSelect('host', $hostNames, [], _('Host')); $select->setHasDescriptiveElements(true); - $return->add($select, 12); + $return->add($select); $return->addVerticalSpacer('2rem'); $return->addLabel(new htmlAccountPageButton(static::class, 'attributes', 'addHost', _('Add'))); $return->addField(new htmlAccountPageButton(static::class, 'attributes', 'cancel', _('Cancel'))); @@ -648,7 +648,7 @@ class fixed_ip extends baseModule { *
"info" are values with informational value (e.g. to be used later by pre/postModify actions) */ public function save_attributes() { - + return []; } /** @@ -719,24 +719,24 @@ class fixed_ip extends baseModule { ldap_delete($_SESSION['ldap']->server(), 'cn=' . $cn . $ldapSuffix); } - foreach ($add as $id => $arr) { + foreach ($add as $arr) { $attr = []; - $attr['cn'] = $add[$id]['cn']; + $attr['cn'] = $arr['cn']; $attr['objectClass'][0] = 'top'; $attr['objectClass'][1] = 'dhcpHost'; - $attr['dhcpHWAddress'] = 'ethernet ' . $add[$id]['mac']; - if ($add[$id]['ip'] != '') { - $attr['dhcpStatements'][] = 'fixed-address ' . $add[$id]['ip']; + $attr['dhcpHWAddress'] = 'ethernet ' . $arr['mac']; + if ($arr['ip'] != '') { + $attr['dhcpStatements'][] = 'fixed-address ' . $arr['ip']; } - if ($add[$id]['active'] === false) { + if ($arr['active'] === false) { $attr['dhcpStatements'][] = 'deny booting'; } - $attr['dhcpOption'] = 'host-name "' . $add[$id]['cn'] . '"'; + $attr['dhcpOption'] = 'host-name "' . $arr['cn'] . '"'; if (!empty($arr['description'])) { $attr['dhcpComments'][] = $arr['description']; } if ($attr['cn'] != "") { - ldap_add($_SESSION['ldap']->server(), 'cn=' . $add[$id]['cn'] . $ldapSuffix, $attr); + ldap_add($_SESSION['ldap']->server(), 'cn=' . $arr['cn'] . $ldapSuffix, $attr); } } // entries to modify @@ -793,7 +793,7 @@ class fixed_ip extends baseModule { $return = null; if (is_array($dhcpStatements)) { for ($i = 0; $i < sizeof($dhcpStatements); $i++) { - if (strpos($dhcpStatements[$i], 'fixed-address ') === 0) { + if (str_starts_with($dhcpStatements[$i], 'fixed-address ')) { $return = substr($dhcpStatements[$i], strlen('fixed-address') + 1); break; } @@ -810,7 +810,7 @@ class fixed_ip extends baseModule { */ private function setIP(&$dhcpStatements, $ip) { for ($i = 0; $i < sizeof($dhcpStatements); $i++) { - if (strpos($dhcpStatements[$i], 'fixed-address ') === 0) { + if (str_starts_with($dhcpStatements[$i], 'fixed-address ')) { unset($dhcpStatements[$i]); $dhcpStatements = array_values($dhcpStatements); } @@ -848,7 +848,7 @@ class fixed_ip extends baseModule { */ private function setActive(&$dhcpStatements, $active) { for ($i = 0; $i < sizeof($dhcpStatements); $i++) { - if (strpos($dhcpStatements[$i], ' booting') !== false) { + if (str_contains($dhcpStatements[$i], ' booting')) { unset($dhcpStatements[$i]); $dhcpStatements = array_values($dhcpStatements); } @@ -891,7 +891,7 @@ class fixed_ip extends baseModule { */ private function fillExistingDhcpHosts() { if ($this->existingDhcpHostsCache != null) { - return $this->existingDhcpHostsCache; + return; } $entries = searchLDAPByAttribute('cn', '*', 'dhcpHost', ['cn'], ['dhcp']); $this->existingDhcpHostsCache = []; diff --git a/lam/lib/modules/freeRadius.inc b/lam/lib/modules/freeRadius.inc index 822ca84ee..64a93c088 100644 --- a/lam/lib/modules/freeRadius.inc +++ b/lam/lib/modules/freeRadius.inc @@ -65,7 +65,7 @@ class freeRadius extends baseModule { * @return boolean true if module fits */ public function can_manage() { - return in_array($this->get_scope(), ['user']); + return $this->get_scope() === 'user'; } /** @@ -189,7 +189,7 @@ class freeRadius extends baseModule { } $profileContainer = new htmlResponsiveRow(); for ($i = 0; $i < sizeof($profileElements); $i++) { - $profileContainer->add($profileElements[$i], 12); + $profileContainer->add($profileElements[$i]); } $return['profile_options'] = $profileContainer; // upload fields @@ -304,12 +304,12 @@ class freeRadius extends baseModule { */ public function get_configOptions($scopes, $allScopes) { $configContainer = new htmlResponsiveRow(); - $configContainer->add(new htmlResponsiveInputField(_('Profile DN'), 'freeRadius_profileDN', '', 'profileDN'), 12); + $configContainer->add(new htmlResponsiveInputField(_('Profile DN'), 'freeRadius_profileDN', '', 'profileDN')); $configContainer->addVerticalSpacer('1rem'); $hiddenGroup = new htmlGroup(); $hiddenGroup->addElement(new htmlOutputText(_('Hidden options'))); $hiddenGroup->addElement(new htmlHelpLink('hiddenOptions')); - $configContainer->add($hiddenGroup, 12); + $configContainer->add($hiddenGroup); $configContainer->addVerticalSpacer('0.5rem'); $configContainer->add(new htmlResponsiveInputCheckbox('freeRadius_hideRadiusFramedIPAddress', false, _('IP address'), null, true), 12, 4); $configContainer->add(new htmlResponsiveInputCheckbox('freeRadius_hideRadiusFramedIPNetmask', false, _('Net mask'), null, true), 12, 4); @@ -407,7 +407,7 @@ class freeRadius extends baseModule { } $profileSelect = new htmlResponsiveSelect('radiusProfileDn', $profiles, $profile, _('Profile'), 'radiusProfileDn'); $profileSelect->setHasDescriptiveElements(true); - $return->add($profileSelect, 12); + $return->add($profileSelect); } // enabled if (!$this->isBooleanConfigOptionSet('freeRadius_hideDialupAccess')) { @@ -422,7 +422,7 @@ class freeRadius extends baseModule { $enabledOptions = ['-' => '', _('Yes') => 'true', _('No') => 'false']; $enabledSelect = new htmlResponsiveSelect('dialupAccess', $enabledOptions, $enabled, _('Enabled'), 'dialupAccess'); $enabledSelect->setHasDescriptiveElements(true); - $return->add($enabledSelect, 12); + $return->add($enabledSelect); } // button to remove extension $return->addVerticalSpacer('2rem'); @@ -431,7 +431,7 @@ class freeRadius extends baseModule { $return->add($remButton, 12, 12, 12, 'text-center'); } else { - $return->add(new htmlButton('addObjectClass', _('Add FreeRadius extension')), 12); + $return->add(new htmlButton('addObjectClass', _('Add FreeRadius extension'))); } return $return; } @@ -543,7 +543,7 @@ class freeRadius extends baseModule { $buttons->addElement(new htmlSpacer('0.5rem', null)); } $buttons->addElement(new htmlAccountPageButton(static::class, 'attributes', 'back' . $attr, _('Cancel'))); - $return->add($buttons, 12); + $return->add($buttons); return $return; } @@ -558,29 +558,29 @@ class freeRadius extends baseModule { $buttonName = ''; $postKeys = array_keys($_POST); for ($i = 0; $i < sizeof($postKeys); $i++) { - if (strpos($postKeys[$i], 'form_subpage_freeRadius_attributes_') !== false) { + if (str_contains($postKeys[$i], 'form_subpage_freeRadius_attributes_')) { $buttonName = $postKeys[$i]; } } - if (($buttonName == '') || (strpos($buttonName, '_back') !== false)) { + if (($buttonName == '') || (str_contains($buttonName, '_back'))) { return []; } // get attribute name $attr = ''; - if (strpos($buttonName, 'radiusExpiration') !== false) { + if (str_contains($buttonName, 'radiusExpiration')) { $attr = 'radiusExpiration'; } if ($attr == '') { return []; } // determine action - if (strpos($buttonName, '_change') !== false) { + if (str_contains($buttonName, '_change')) { // set new expiration date $date = DateTime::createFromFormat('Y-m-d H:i', $_POST['expirationTime'], getTimeZone()); $date->setTimezone(new DateTimeZone('UTC')); $this->attributes[$attr][0] = $date->format('d M Y H:i'); } - elseif (strpos($buttonName, '_del') !== false) { + elseif (str_contains($buttonName, '_del')) { // remove attribute value unset($this->attributes[$attr]); } @@ -634,11 +634,11 @@ class freeRadius extends baseModule { $date = DateTime::createFromFormat('Y-m-d H:i', $rawAccounts[$i][$ids['freeRadius_radiusExpiration']], getTimeZone()); if ($date !== false) { $date->setTimezone(new DateTimeZone('UTC')); - $partialAccounts[$i]['radiusExpiration'] = $date->format('d M Y H:i');; + $partialAccounts[$i]['radiusExpiration'] = $date->format('d M Y H:i'); } else { $errMsg = $this->messages['radiusExpiration'][1]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } } @@ -652,7 +652,7 @@ class freeRadius extends baseModule { } else { $errMsg = $this->messages['dialupAccess'][0]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } } @@ -735,7 +735,7 @@ class freeRadius extends baseModule { * @param String $date date value */ private function formatExpirationDate($date) { - if (is_null($date) || ($date == '')) { + if (empty($date)) { return $date; } $dateTime = DateTime::createFromFormat('d M Y H:i', $date, new DateTimeZone('UTC')); diff --git a/lam/lib/modules/imapAccess.inc b/lam/lib/modules/imapAccess.inc index 05ca8fbc9..d89ce6bf6 100644 --- a/lam/lib/modules/imapAccess.inc +++ b/lam/lib/modules/imapAccess.inc @@ -39,8 +39,8 @@ use Webklex\PHPIMAP\ClientManager; */ class imapAccess extends baseModule { - const QUOTA_USAGE = 'usage'; - const QUOTA_LIMIT = 'limit'; + private const QUOTA_USAGE = 'usage'; + private const QUOTA_LIMIT = 'limit'; /** quota limit from profile */ private $profileQuotaLimit; @@ -56,7 +56,7 @@ class imapAccess extends baseModule { * @return boolean true if module fits */ public function can_manage() { - return in_array($this->get_scope(), ['user']); + return $this->get_scope() === 'user'; } /** @@ -140,7 +140,7 @@ class imapAccess extends baseModule { 'error_message' => $this->messages['config'][1]]; // profile options $profileContainer = new htmlResponsiveRow(); - $profileContainer->add(new htmlResponsiveInputField(_('Quota'), 'ImapAccess_QuotaLimit', null, 'ImapUserQuotaLimit'), 12); + $profileContainer->add(new htmlResponsiveInputField(_('Quota'), 'ImapAccess_QuotaLimit', null, 'ImapUserQuotaLimit')); $return['profile_options'] = $profileContainer; $return['profile_checks']['ImapAccess_QuotaLimit'] = [ 'type' => 'ext_preg', @@ -224,7 +224,7 @@ class imapAccess extends baseModule { } $msg = $this->extractUserAndEmail(); if ($msg != null) { - $return->add($msg, 12); + $return->add($msg); return $return; } $prefix = $this->getMailboxPrefix(); @@ -266,7 +266,7 @@ class imapAccess extends baseModule { $return->add($mailboxMessage, 12, 12, 12, 'text-center'); $return->addVerticalSpacer('2rem'); if ($this->isWrongDomain($email_domain)) { - $return->add(new htmlStatusMessage('INFO', $this->messages['managemailbox'][4][1]), 12); + $return->add(new htmlStatusMessage('INFO', $this->messages['managemailbox'][4][1])); $return->addVerticalSpacer('1rem'); } else { @@ -287,14 +287,14 @@ class imapAccess extends baseModule { function display_html_password($message = null) { $return = new htmlResponsiveRow(); if ($message !== null) { - $return->add($message, 12); + $return->add($message); $return->addVerticalSpacer('1rem'); } $passwordInput = new htmlResponsiveInputField(_("Password of IMAP admin user"), 'ImapAdminPassword', '', 'ImapAdminPassword_Sess'); $passwordInput->setIsPassword(true); $passwordInput->setRequired(true); $passwordInput->setOnKeyPress('SubmitForm(\'enterPasswordButton\', event);'); - $return->add($passwordInput, 12); + $return->add($passwordInput); $return->addVerticalSpacer('2rem'); $return->add(new htmlButton('enterPasswordButton', _('Ok')), 12, 12, 12, 'text-center'); return $return; @@ -519,14 +519,14 @@ class imapAccess extends baseModule { $configContainer = new htmlResponsiveRow(); $configServer = new htmlResponsiveInputField(_('Server address'), 'ImapAccess_ImapServerAddress', '', 'ImapServerAddress'); $configServer->setRequired(true); - $configContainer->add($configServer, 12); - $configContainer->add(new htmlResponsiveSelect('ImapAccess_ImapServerEncriptionProtocol', ['TLS', 'SSL'], ['TLS'], _("Encryption protocol"), 'ImapServerEncryptionProtocol'), 12); + $configContainer->add($configServer); + $configContainer->add(new htmlResponsiveSelect('ImapAccess_ImapServerEncriptionProtocol', ['TLS', 'SSL'], ['TLS'], _("Encryption protocol"), 'ImapServerEncryptionProtocol')); $configCertValidate = new htmlResponsiveSelect('ImapAccess_ImapValidateServerCert', [_('Yes') => 'validate-cert', _('No') => 'novalidate-cert'], ['validate-cert'], _("Validate server certificate"), 'ImapValidateServerCert'); $configCertValidate->setHasDescriptiveElements(true); - $configContainer->add($configCertValidate, 12); + $configContainer->add($configCertValidate); $configUser = new htmlResponsiveInputField(_('IMAP admin user'), 'ImapAccess_ImapAdmin', '', 'ImapAdmin'); $configUser->setRequired(true); - $configContainer->add($configUser, 12); + $configContainer->add($configUser); $pwdSelectOptions = [ _('LAM user password') => 'lam_user_pass', _('Ask') => 'ask_pass', @@ -535,20 +535,20 @@ class imapAccess extends baseModule { $configPasswordType->setHasDescriptiveElements(true); $configPasswordType->setTableRowsToShow(['config' => ['ImapAccess_ImapAdminPassword']]); $configPasswordType->setTableRowsToHide(['lam_user_pass' => ['ImapAccess_ImapAdminPassword'], 'ask_pass' => ['ImapAccess_ImapAdminPassword']]); - $configContainer->add($configPasswordType, 12); + $configContainer->add($configPasswordType); $adminPwdInput = new htmlResponsiveInputField(_('Admin password'), 'ImapAccess_ImapAdminPassword', null, 'ImapAdminPasswordSelect'); $adminPwdInput->setIsPassword(true); $adminPwdInput->setObfuscate(true); - $configContainer->add($adminPwdInput, 12); + $configContainer->add($adminPwdInput); $mailDomainsInput = new htmlResponsiveInputField(_('Mail domains'), 'ImapAccess_ImapDomain', '', 'ImapMailDomain'); $mailDomainsInput->setRequired(true); - $configContainer->add($mailDomainsInput, 12); - $configContainer->add(new htmlResponsiveInputField(_('Prefix for mailboxes'), 'ImapAccess_ImapUserPrefix', '', 'ImapUserPrefix'), 12); - $configContainer->add(new htmlResponsiveInputTextarea('ImapAccess_initialFolders', '', 10, 3, _('Initial folders'), 'initialFolders'), 12); + $configContainer->add($mailDomainsInput); + $configContainer->add(new htmlResponsiveInputField(_('Prefix for mailboxes'), 'ImapAccess_ImapUserPrefix', '', 'ImapUserPrefix')); + $configContainer->add(new htmlResponsiveInputTextarea('ImapAccess_initialFolders', '', 10, 3, _('Initial folders'), 'initialFolders')); $configUserName = new htmlResponsiveSelect('ImapAccess_UserNameAttribute', ['mail', 'uid', 'userPrincipalName'], ['mail'], _("User name attribute"), 'ImapUserNameAttr'); - $configContainer->add($configUserName, 12); + $configContainer->add($configUserName); $configPathSeparator = new htmlResponsiveSelect('ImapAccess_pathSeparator', ['.', '/'], ['.'], _("Path separator"), 'pathSeparator'); - $configContainer->add($configPathSeparator, 12); + $configContainer->add($configPathSeparator); return $configContainer; } @@ -575,7 +575,7 @@ class imapAccess extends baseModule { return $_SESSION['imapAdmUser']; } $user = $this->moduleSettings['ImapAccess_ImapAdmin'][0]; - // check if user name contains any wildcards that need to be replaced with LDAP attribute values + // check if username contains any wildcards that need to be replaced with LDAP attribute values $matches = []; preg_match_all('/\\$[a-z0-9_-]+\\$/i', $this->moduleSettings['ImapAccess_ImapAdmin'][0], $matches); if (sizeof($matches) > 0) { @@ -587,7 +587,7 @@ class imapAccess extends baseModule { } } $attrNames = array_values(array_unique($attrNames)); - $attrNames = array_change_key_case($attrNames, CASE_LOWER); + $attrNames = array_change_key_case($attrNames); // read LAM login user data $dn = $_SESSION['ldap']->getUserName(); $sr = @ldap_read($_SESSION['ldap']->server(), $dn, '(objectclass=*)', $attrNames, 0, 0, 0, LDAP_DEREF_NEVER); @@ -818,7 +818,7 @@ class imapAccess extends baseModule { if (isset($rawAccounts[$i][$ids['imapAccess_createMailbox']]) && !in_array($rawAccounts[$i][$ids['imapAccess_createMailbox']], ['true', 'false'])) { $errMsg = $this->messages['createMailbox'][0]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } if (isset($rawAccounts[$i][$ids['imapAccess_createMailbox']]) @@ -827,7 +827,7 @@ class imapAccess extends baseModule { && isset($rawAccounts[$i][$ids['imapAccess_quota']]) && !get_preg($rawAccounts[$i][$ids['imapAccess_quota']], 'digit')) { $errMsg = $this->messages['managemailbox'][9]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } } diff --git a/lam/lib/modules/nisMailAlias.inc b/lam/lib/modules/nisMailAlias.inc index 40295fcff..7b1edcf41 100644 --- a/lam/lib/modules/nisMailAlias.inc +++ b/lam/lib/modules/nisMailAlias.inc @@ -48,7 +48,7 @@ class nisMailAlias extends baseModule { * @return boolean true if module fits */ public function can_manage() { - return in_array($this->get_scope(), ['mailAlias']); + return $this->get_scope() === 'mailAlias'; } /** @@ -164,7 +164,7 @@ class nisMailAlias extends baseModule { $nameInput = new htmlResponsiveInputField(_('Alias name'), 'cn', $alias, 'alias'); $nameInput->setRequired(true); $nameInput->setCSSClasses(['maxwidth20']); - $return->add($nameInput, 12); + $return->add($nameInput); // list current recipients $mailList = $this->getMailList(); $userList = $this->getUserList(); @@ -177,7 +177,7 @@ class nisMailAlias extends baseModule { natcasesort($this->attributes['rfc822MailMember']); $this->attributes['rfc822MailMember'] = array_values($this->attributes['rfc822MailMember']); $recipientCount = sizeof($this->attributes['rfc822MailMember']); - if ($recipientCount < nisMailAlias::DISPLAY_LIMIT) { + if ($recipientCount < self::DISPLAY_LIMIT) { for ($i = 0; $i < $recipientCount; $i++) { if (($i == 0) && ($recipientCount == 1)) { $return->addLabel(new htmlOutputText(_('Recipient'))); @@ -204,10 +204,10 @@ class nisMailAlias extends baseModule { } else { $memberText = implode("\r\n", $this->attributes['rfc822MailMember']); - $return->add(new htmlResponsiveInputTextarea('rfc822MailMember', $memberText, 50, 30, _('Recipients'), 'recipient'), 12); + $return->add(new htmlResponsiveInputTextarea('rfc822MailMember', $memberText, 50, 30, _('Recipients'), 'recipient')); } } - if ($recipientCount < nisMailAlias::DISPLAY_LIMIT) { + if ($recipientCount < self::DISPLAY_LIMIT) { // input box for new recipient $return->addLabel(new htmlOutputText(_('New recipient'))); $newMailField = new htmlInputField('rfc822MailMember'); @@ -240,16 +240,13 @@ class nisMailAlias extends baseModule { $recipientCount = !empty($this->attributes['rfc822MailMember']) ? sizeof($this->attributes['rfc822MailMember']) : 0; $this->attributes['rfc822MailMember'] = []; // check alias name - if (isset($_POST['cn']) && ($_POST['cn'] != "") && get_preg($_POST['cn'], 'nis_alias')) { - $this->attributes['cn'][] = $_POST['cn']; - } - else { - $this->attributes['cn'][] = $_POST['cn']; + $this->attributes['cn'][] = $_POST['cn']; + if (!isset($_POST['cn']) || ($_POST['cn'] == "") || !get_preg($_POST['cn'], 'nis_alias')) { $message = $this->messages['alias'][0]; $message[] = $_POST['cn']; $errors[] = $message; } - if ($recipientCount < nisMailAlias::DISPLAY_LIMIT) { + if ($recipientCount < self::DISPLAY_LIMIT) { // check old recipients if (isset($_POST['rec_number'])) { for ($i = 0; $i < $_POST['rec_number']; $i++) { @@ -361,7 +358,7 @@ class nisMailAlias extends baseModule { $postKeys = array_keys($_POST); $position = 'New'; for ($i = 0; $i < sizeof($postKeys); $i++) { - if (strpos($postKeys[$i], 'form_subpage_' . static::class . '_select' . $suffix . '_recipient') === 0) { + if (str_starts_with($postKeys[$i], 'form_subpage_' . static::class . '_select' . $suffix . '_recipient')) { $position = substr($postKeys[$i], strlen('form_subpage_' . static::class . '_select' . $suffix . '_recipient')); break; } @@ -390,7 +387,7 @@ class nisMailAlias extends baseModule { $return->addVerticalSpacer('2rem'); $return->addLabel(new htmlAccountPageButton(static::class, 'attributes', 'select', _('Ok'))); $return->addField(new htmlAccountPageButton(static::class, 'attributes', 'back', _('Cancel'))); - $return->add(new htmlHiddenInput('position', $position), 12); + $return->add(new htmlHiddenInput('position', $position)); return $return; } @@ -457,7 +454,7 @@ class nisMailAlias extends baseModule { } else { $errMsg = $this->messages['recipient'][1]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $messages[] = $errMsg; } } diff --git a/lam/lib/modules/nisMailAliasUser.inc b/lam/lib/modules/nisMailAliasUser.inc index ebf371776..576fc2ed9 100644 --- a/lam/lib/modules/nisMailAliasUser.inc +++ b/lam/lib/modules/nisMailAliasUser.inc @@ -1,6 +1,6 @@ get_scope(), ['user']); + return $this->get_scope() === 'user'; } /** @@ -122,7 +122,7 @@ class nisMailAliasUser extends baseModule { function display_html_attributes() { $return = new htmlResponsiveRow(); if (!$this->isMailAliasTypeActive()) { - $return->add(new htmlStatusMessage('ERROR', _('Please activate the mail aliases type for this server profile.')), 12); + $return->add(new htmlStatusMessage('ERROR', _('Please activate the mail aliases type for this server profile.'))); return $return; } $aliases = $this->getMailAliasList(); @@ -130,7 +130,7 @@ class nisMailAliasUser extends baseModule { $userName = $this->getUserName(); $mails = $this->getMailAddresses(); if (!$this->isBooleanConfigOptionSet('nisMailAliasUser_hideUserAliases') && ($userName != null)) { - $return->add(new htmlSubTitle(_('Aliases for user name')), 12); + $return->add(new htmlSubTitle(_('Aliases for user name'))); for ($i = 0; $i < $count; $i++) { if (empty($aliases[$i]['rfc822mailmember'])) { continue; @@ -156,11 +156,11 @@ class nisMailAliasUser extends baseModule { $return->add($addButton, 12, 12, 12, 'text-center'); } if (!$this->isBooleanConfigOptionSet('nisMailAliasUser_hideMailAliases') && !empty($mails)) { - $return->add(new htmlSubTitle(_('Aliases for email')), 12); + $return->add(new htmlSubTitle(_('Aliases for email'))); for ($m = 0; $m < sizeof($mails); $m++) { if (sizeof($mails) > 1) { $label = new htmlOutputText($mails[$m]); - $return->add($label, 12); + $return->add($label); } for ($i = 0; $i < $count; $i++) { if (empty($aliases[$i]['rfc822mailmember'])) { @@ -206,22 +206,22 @@ class nisMailAliasUser extends baseModule { } $mails = $this->getMailAddresses(); foreach ($_POST as $key => $value) { - if (strpos($key, 'rem_') === 0) { + if (str_starts_with($key, 'rem_')) { $index = substr($key, strlen('rem_')); $dn = $this->cachedAliasList[$index]['dn']; $this->removeRecipient($this->getUserName(), $dn); } - elseif (strpos($key, 'del_') === 0) { + elseif (str_starts_with($key, 'del_')) { $index = substr($key, strlen('del_')); $dn = $this->cachedAliasList[$index]['dn']; $this->deleteAlias($dn); } - elseif (strpos($key, 'remMail_') === 0) { + elseif (str_starts_with($key, 'remMail_')) { $parts = substr($key, strlen('remMail_')); $parts = explode('_', $parts); $this->removeRecipient($mails[$parts[1]], $this->cachedAliasList[$parts[0]]['dn']); } - elseif (strpos($key, 'delMail_') === 0) { + elseif (str_starts_with($key, 'delMail_')) { $parts = substr($key, strlen('remMail_')); $parts = explode('_', $parts); $this->deleteAlias($this->cachedAliasList[$parts[0]]['dn']); @@ -335,10 +335,10 @@ class nisMailAliasUser extends baseModule { } $return->addLabel(new htmlOutputText(_('Recipient'))); $return->addField(new htmlOutputText($recipient)); - $return->add(new htmlHiddenInput('recipient', $recipient), 12); + $return->add(new htmlHiddenInput('recipient', $recipient)); // new mail alias - $return->add(new htmlSubTitle(_('Create new alias')), 12); - $typeManager = new \LAM\TYPES\TypeManager(); + $return->add(new htmlSubTitle(_('Create new alias'))); + $typeManager = new TypeManager(); $mailAliasTypes = $typeManager->getConfiguredTypesForScope('mailAlias'); $ous = []; foreach ($mailAliasTypes as $type) { @@ -349,9 +349,9 @@ class nisMailAliasUser extends baseModule { $suffixSelect = new htmlResponsiveSelect('new_ou', $ous, [], _('Suffix'), 'suffix'); $suffixSelect->setRightToLeftTextDirection(true); $suffixSelect->setSortElements(false); - $return->add($suffixSelect, 12); + $return->add($suffixSelect); $newAliasCn = empty($_POST['new_cn']) ? '' : $_POST['new_cn']; - $return->add(new htmlResponsiveInputField(_('Alias name'), 'new_cn', $newAliasCn, 'newAlias'), 12); + $return->add(new htmlResponsiveInputField(_('Alias name'), 'new_cn', $newAliasCn, 'newAlias')); $return->addVerticalSpacer('1rem'); $addButton = new htmlAccountPageButton(static::class, 'attributes', 'create', _('Create')); $return->add($addButton, 12, 12, 12, 'text-center'); @@ -359,7 +359,7 @@ class nisMailAliasUser extends baseModule { $return->addVerticalSpacer('2rem'); // add to existing alias - $return->add(new htmlSubTitle(_('Add to existing alias')), 12); + $return->add(new htmlSubTitle(_('Add to existing alias'))); $aliasesToAdd = []; foreach ($aliases as $index => $attrs) { if (!empty($attrs['rfc822mailmember']) && in_array($recipient, $attrs['rfc822mailmember'])) { @@ -370,14 +370,14 @@ class nisMailAliasUser extends baseModule { $aliasSelect = new htmlResponsiveSelect('ex_cn', $aliasesToAdd, [], _('Alias names'), 'aliasNames', 20); $aliasSelect->setHasDescriptiveElements(true); $aliasSelect->setMultiSelect(true); - $return->add($aliasSelect, 12); + $return->add($aliasSelect); $return->addVerticalSpacer('1rem'); $addButton = new htmlAccountPageButton(static::class, 'attributes', 'recipient', _('Add')); $return->add($addButton, 12, 12, 12, 'text-center'); $return->addVerticalSpacer('2rem'); $cancelButton = new htmlAccountPageButton(static::class, 'attributes', 'back', _('Cancel')); - $return->add($cancelButton, 12); + $return->add($cancelButton); return $return; } @@ -549,8 +549,8 @@ class nisMailAliasUser extends baseModule { $configContainer->addLabel($hiddenGroup); $configContainer->addField(new htmlOutputText('')); $configContainer->addVerticalSpacer('0.5rem'); - $configContainer->add(new htmlResponsiveInputCheckbox('nisMailAliasUser_hideUserAliases', false, _('Aliases for user name')), 12); - $configContainer->add(new htmlResponsiveInputCheckbox('nisMailAliasUser_hideMailAliases', false, _('Aliases for email')), 12); + $configContainer->add(new htmlResponsiveInputCheckbox('nisMailAliasUser_hideUserAliases', false, _('Aliases for user name'))); + $configContainer->add(new htmlResponsiveInputCheckbox('nisMailAliasUser_hideMailAliases', false, _('Aliases for email'))); return $configContainer; } @@ -591,7 +591,7 @@ class nisMailAliasUser extends baseModule { /** * Returns the email addresses of this account. * - * @return String mail addresses + * @return string[]|null mail addresses */ private function getMailAddresses() { if ($this->getAccountContainer()->getAccountModule('inetOrgPerson') != null) { diff --git a/lam/lib/modules/nisNetGroupUser.inc b/lam/lib/modules/nisNetGroupUser.inc index aa144a6fd..2a0803b25 100644 --- a/lam/lib/modules/nisNetGroupUser.inc +++ b/lam/lib/modules/nisNetGroupUser.inc @@ -1,9 +1,9 @@ get_scope(), ['user']); + return $this->get_scope() === 'user'; } /** @@ -130,7 +130,7 @@ class nisNetGroupUser extends baseModule { $filter = '(&(objectClass=nisNetgroup)(nisnetgrouptriple=*))'; $typeFilter = $type->getAdditionalLdapFilter(); if (!empty($typeFilter)) { - if (strpos($typeFilter, '(') !== 0) { + if (!str_starts_with($typeFilter, '(')) { $typeFilter = '(' . $typeFilter . ')'; } $filter = '(&' . $filter . $typeFilter . ')'; @@ -160,7 +160,7 @@ class nisNetGroupUser extends baseModule { } } } - usort($this->groupsOrig, [$this, 'sortTriple']); + usort($this->groupsOrig, $this->sortTriple(...)); $this->groups = $this->groupsOrig; } @@ -276,7 +276,7 @@ class nisNetGroupUser extends baseModule { $counter++; } $this->groups = array_values($this->groups); - usort($this->groups, [$this, 'sortTriple']); + usort($this->groups, $this->sortTriple(...)); return $errors; } @@ -404,7 +404,7 @@ class nisNetGroupUser extends baseModule { foreach ($changes as $dn => $changeSet) { $current = ldapGetDN($dn, ['nisnetgrouptriple']); if (empty($current)) { - $messages[] = ['ERROR', sprintf(_('Was unable to modify attributes of DN: %s.'), $dn)]; + $return[$this->getAccountContainer()->dn_orig]['errors'][] = ['ERROR', sprintf(_('Was unable to modify attributes of DN: %s.'), $dn)]; continue; } $triples = empty($current['nisnetgrouptriple']) ? [] : $current['nisnetgrouptriple']; @@ -416,7 +416,7 @@ class nisNetGroupUser extends baseModule { $success = @ldap_mod_replace($_SESSION['ldap']->server(), $dn, $attributes); if (!$success) { logNewMessage(LOG_ERR, 'Unable to modify attributes of DN: ' . $dn . ' (' . ldap_error($_SESSION['ldap']->server()) . ').'); - $messages[] = ['ERROR', sprintf(_('Was unable to modify attributes of DN: %s.'), $dn), getDefaultLDAPErrorString($_SESSION['ldap']->server())]; + $return[$this->getAccountContainer()->dn_orig]['errors'][] = ['ERROR', sprintf(_('Was unable to modify attributes of DN: %s.'), $dn), getDefaultLDAPErrorString($_SESSION['ldap']->server())]; } } return $return; @@ -441,7 +441,7 @@ class nisNetGroupUser extends baseModule { $data[$i][] = new htmlInputField('nisNetGroupUser_host' . $i); $data[$i][] = new htmlInputField('nisNetGroupUser_domain' . $i); } - $return->add(new htmlResponsiveTable($labels, $data), 12); + $return->add(new htmlResponsiveTable($labels, $data)); return $return; } @@ -463,7 +463,7 @@ class nisNetGroupUser extends baseModule { ]; } } - usort($this->groups, [$this, 'sortTriple']); + usort($this->groups, $this->sortTriple(...)); } /** @@ -567,7 +567,11 @@ class nisNetGroupUser extends baseModule { if (empty($current)) { $errors[] = ['ERROR', sprintf(_('Was unable to modify attributes of DN: %s.'), $dn)]; $temp['counter']++; - return; + return [ + 'status' => 'inProgress', + 'progress' => ($temp['counter'] * 100) / sizeof($temp['groupDNs']), + 'errors' => $errors + ]; } $triples = empty($current['nisnetgrouptriple']) ? [] : $current['nisnetgrouptriple']; $triples = array_merge($temp['groups'][$dn], $triples); @@ -630,7 +634,7 @@ class nisNetGroupUser extends baseModule { $filter = '(objectClass=nisNetgroup)'; $typeFilter = $type->getAdditionalLdapFilter(); if (!empty($typeFilter)) { - if (strpos($typeFilter, '(') !== 0) { + if (!str_starts_with($typeFilter, '(')) { $typeFilter = '(' . $typeFilter . ')'; } $filter = '(&' . $filter . $typeFilter . ')'; @@ -666,5 +670,3 @@ class nisNetGroupUser extends baseModule { } } - -?> diff --git a/lam/lib/modules/nisnetgroup.inc b/lam/lib/modules/nisnetgroup.inc index 36029b474..15991c95a 100644 --- a/lam/lib/modules/nisnetgroup.inc +++ b/lam/lib/modules/nisnetgroup.inc @@ -1,8 +1,8 @@ get_scope(), ['netgroup']); + return $this->get_scope() === 'netgroup'; } /** @@ -200,12 +200,12 @@ class nisnetgroup extends baseModule { $nameInput = new htmlResponsiveInputField(_("Group name"), 'cn', $groupName, 'cn'); $nameInput->setRequired(true); $nameInput->setFieldMaxLength(20); - $return->add($nameInput, 12); + $return->add($nameInput); $description = ''; if (isset($this->attributes['description'][0])) { $description = $this->attributes['description'][0]; } - $return->add(new htmlResponsiveInputField(_('Description'), 'description', $description, 'description'), 12); + $return->add(new htmlResponsiveInputField(_('Description'), 'description', $description, 'description')); $subgroupsContainer = new htmlTable(); if (isset($this->attributes['memberNisNetgroup']) && is_array($this->attributes['memberNisNetgroup'])) { $membergroups = $this->attributes['memberNisNetgroup']; @@ -225,7 +225,7 @@ class nisnetgroup extends baseModule { // members $membersLabel = new htmlSubTitle(_('Members')); $membersLabel->setHelpId('members'); - $return->add($membersLabel, 12); + $return->add($membersLabel); $titles = [_('Host'), _('User'), _('Domain'), '']; $data = []; if (isset($this->attributes['nisNetgroupTriple']) && (sizeof($this->attributes['nisNetgroupTriple']) > 0)) { @@ -306,7 +306,7 @@ class nisnetgroup extends baseModule { $data[] = $dataRowNew; $memberTable = new htmlResponsiveTable($titles, $data); - $return->add($memberTable, 12); + $return->add($memberTable); return $return; } @@ -409,13 +409,13 @@ class nisnetgroup extends baseModule { } $return = new htmlResponsiveRow(); - $return->add(new htmlSubTitle(_("Subgroups")), 12); + $return->add(new htmlSubTitle(_("Subgroups"))); $this->addDoubleSelectionArea($return, _("Selected groups"), _("Available groups"), $selectedGroups, [], $availableGroups, [], 'subgroup', false, true); $return->addVerticalSpacer('2rem'); $backButton = new htmlAccountPageButton(static::class, 'attributes', 'back', _('Back')); - $return->add($backButton, 12); + $return->add($backButton); return $return; } @@ -450,12 +450,12 @@ class nisnetgroup extends baseModule { $postKeys = array_keys($_POST); $position = 'New'; for ($i = 0; $i < sizeof($postKeys); $i++) { - if (substr($postKeys[$i], 0, 36) == 'form_subpage_nisnetgroup_select_user') { + if (str_starts_with($postKeys[$i], 'form_subpage_nisnetgroup_select_user')) { $selectHost = false; $position = substr($postKeys[$i], 36); break; } - if (substr($postKeys[$i], 0, 36) == 'form_subpage_nisnetgroup_select_host') { + if (str_starts_with($postKeys[$i], 'form_subpage_nisnetgroup_select_host')) { $position = substr($postKeys[$i], 36); break; } @@ -469,13 +469,12 @@ class nisnetgroup extends baseModule { unset($options[$i]); } } - $options = array_values($options); } else { // load list with all users $options = $this->getUserList(); - $options = array_values($options); } + $options = array_values($options); $return->addLabel(new htmlOutputText(_('Filter'))); $filterInput = new htmlInputField('filter'); $filterInput->filterSelectBox('selectBox'); @@ -493,11 +492,11 @@ class nisnetgroup extends baseModule { } $return->addLabel(new htmlAccountPageButton(static::class, 'attributes', 'select', _('Ok'))); $return->addField(new htmlAccountPageButton(static::class, 'attributes', 'back', _('Cancel'))); - $return->add(new htmlHiddenInput('host_new', $_POST['host_new']), 12); - $return->add(new htmlHiddenInput('user_new', $_POST['user_new']), 12); - $return->add(new htmlHiddenInput('domain_new', $_POST['domain_new']), 12); - $return->add(new htmlHiddenInput('type', $type), 12); - $return->add(new htmlHiddenInput('position', $position), 12); + $return->add(new htmlHiddenInput('host_new', $_POST['host_new'])); + $return->add(new htmlHiddenInput('user_new', $_POST['user_new'])); + $return->add(new htmlHiddenInput('domain_new', $_POST['domain_new'])); + $return->add(new htmlHiddenInput('type', $type)); + $return->add(new htmlHiddenInput('position', $position)); return $return; } diff --git a/lam/lib/modules/posixAccount.inc b/lam/lib/modules/posixAccount.inc index 237282d39..cc94a7dff 100644 --- a/lam/lib/modules/posixAccount.inc +++ b/lam/lib/modules/posixAccount.inc @@ -2,7 +2,7 @@ use LAM\REMOTE\Remote; use LAM\REMOTE\RemoteServerConfiguration; -use \LAM\TYPES\TypeManager; +use LAM\TYPES\TypeManager; use function LAM\TYPES\getScopeFromTypeId; use LAM\TYPES\ConfiguredType; @@ -52,17 +52,17 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP /** * ID for locked password status. */ - const STATUS_PASSWORD_LOCKED = "POSIX_ACCOUNT_PASSWORD_LOCKED"; + private const STATUS_PASSWORD_LOCKED = "POSIX_ACCOUNT_PASSWORD_LOCKED"; /** * ID for removing Unix groups of user. */ - const STATUS_REMOVE_UNIX_GROUPS = "POSIX_ACCOUNT_REMOVE_UNIX_GROUPS"; + private const STATUS_REMOVE_UNIX_GROUPS = "POSIX_ACCOUNT_REMOVE_UNIX_GROUPS"; /** * ID for removing group of names groups of user. */ - const STATUS_REMOVE_GON_GROUPS = "POSIX_ACCOUNT_REMOVE_GON_GROUPS"; + private const STATUS_REMOVE_GON_GROUPS = "POSIX_ACCOUNT_REMOVE_GON_GROUPS"; /* These two variables keep an array of groups the user is also member of. */ /** current group list */ @@ -202,10 +202,10 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP // self service configuration settings $selfServiceContainer = new htmlResponsiveRow(); $selfServiceContainer->add(new htmlResponsiveSelect('posixAccount_pwdHash', getSupportedHashTypes(), - ['CRYPT-SHA512'], _("Password hash type"), ['pwdHash', static::class]), 12); - $selfServiceContainer->add(new htmlResponsiveInputTextarea('posixAccount_shells', implode("\r\n", $this->getShells()), 30, 4, _('Login shells'), ['loginShells', static::class]), 12); - $selfServiceContainer->add(new htmlResponsiveInputField(_('Group DN'), 'posixAccount_groupDn', '', ['groupDn', static::class]), 12); - $selfServiceContainer->add(new htmlResponsiveInputCheckbox('posixAccount_useOldPwd', false, _('Password change with old password'), ['useOldPwd', static::class]), 12); + ['CRYPT-SHA512'], _("Password hash type"), ['pwdHash', static::class])); + $selfServiceContainer->add(new htmlResponsiveInputTextarea('posixAccount_shells', implode("\r\n", $this->getShells()), 30, 4, _('Login shells'), ['loginShells', static::class])); + $selfServiceContainer->add(new htmlResponsiveInputField(_('Group DN'), 'posixAccount_groupDn', '', ['groupDn', static::class])); + $selfServiceContainer->add(new htmlResponsiveInputCheckbox('posixAccount_useOldPwd', false, _('Password change with old password'), ['useOldPwd', static::class])); $return['selfServiceSettings'] = $selfServiceContainer; } // profile checks @@ -513,7 +513,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP // list of all group names $groups = $this->findGroups($modules); if (count($groups) == 0) { - StatusMessage("ERROR", _('No Unix groups found in LDAP! Please create one first.'), ''); + StatusMessage("ERROR", _('No Unix groups found in LDAP! Please create one first.')); return; } $this->gonList = []; @@ -596,7 +596,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $groupFilter = '(&(objectClass=posixGroup)(memberUid=' . $uid . '))'; if (!empty($typeSettings['filter_group'])) { $typeFilter = $typeSettings['filter_group']; - if (strpos($typeFilter, '(') !== 0) { + if (!str_starts_with($typeFilter, '(')) { $typeFilter = '(' . $typeFilter . ')'; } $groupFilter = '(&' . $groupFilter . $typeFilter . ')'; @@ -623,7 +623,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $gonFilter = '(|(&(objectClass=groupOfNames)(member=' . ldap_escape($dn, '', LDAP_ESCAPE_FILTER) . '))(&(objectClass=groupOfMembers)(member=' . ldap_escape($dn) . '))(&(objectClass=groupOfUniqueNames)(uniquemember=' . ldap_escape($dn) . ')))'; if (!empty($typeSettings['filter_' . $type])) { $typeFilter = $typeSettings['filter_' . $type]; - if (strpos($typeFilter, '(') !== 0) { + if (!str_starts_with($typeFilter, '(')) { $typeFilter = '(' . $typeFilter . ')'; } $gonFilter = '(&' . $gonFilter . $typeFilter . ')'; @@ -783,7 +783,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP if (!in_array($lamdaemonServer->getServer(), $this->lamdaemonServers)) { continue; } - $remote = new \LAM\REMOTE\Remote(); + $remote = new Remote(); try { $remote->connect($lamdaemonServer); } @@ -811,7 +811,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP if (!empty($this->orig[$homeDirAttr][0]) && !empty($this->attributes[$homeDirAttr][0]) && ($this->orig[$homeDirAttr][0] != $this->attributes[$homeDirAttr][0])) { foreach ($lamdaemonServerList as $lamdaemonServer) { - $remote = new \LAM\REMOTE\Remote(); + $remote = new Remote(); try { $remote->connect($lamdaemonServer); } @@ -844,7 +844,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP if (!empty($this->orig[$homeDirAttr][0]) && !empty($this->attributes[$homeDirAttr][0]) && ($this->orig['gidNumber'][0] != $this->attributes['gidNumber'][0])) { foreach ($lamdaemonServerList as $lamdaemonServer) { - $remote = new \LAM\REMOTE\Remote(); + $remote = new Remote(); try { $remote->connect($lamdaemonServer); } @@ -962,7 +962,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP if ($rights == '') { $rights = '750'; } - if (strpos($rights, '0') !== 0) { + if (!str_starts_with($rights, '0')) { $rights = '0' . $rights; } return $remote->execute( @@ -1042,7 +1042,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers(); // try to delete directory on all servers foreach ($lamdaemonServers as $lamdaemonServer) { - $remote = new \LAM\REMOTE\Remote(); + $remote = new Remote(); try { $remote->connect($lamdaemonServer); $result = $remote->execute( @@ -1642,7 +1642,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $homeDirAttr = $this->getHomedirAttrName($modules); for ($i = 0; $i < sizeof($lamdaemonServers); $i++) { if (isset($_POST['form_subpage_' . static::class . '_homedir_create_' . $i])) { - $remote = new \LAM\REMOTE\Remote(); + $remote = new Remote(); try { $remote->connect($lamdaemonServers[$i]); } @@ -1663,7 +1663,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } } elseif (isset($_POST['form_subpage_' . static::class . '_homedir_delete_' . $i])) { - $remote = new \LAM\REMOTE\Remote(); + $remote = new Remote(); try { $remote->connect($lamdaemonServers[$i]); } @@ -1715,7 +1715,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $groups[$groupList[$i][1]] = $groupList[$i][0]; } if (count($groups) == 0) { - $return->add(new htmlStatusMessage("ERROR", _('No Unix groups found in LDAP! Please create one first.')), 12); + $return->add(new htmlStatusMessage("ERROR", _('No Unix groups found in LDAP! Please create one first.'))); return $return; } $shelllist = $this->getShells(); // list of all valid shells @@ -1735,7 +1735,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $msg = new htmlStatusMessage($this->messages['uid'][5][0], $this->messages['uid'][5][1], $this->messages['uid'][5][2], [htmlspecialchars($users[$firstSuggestion])]); - $return->add($msg, 12); + $return->add($msg); } } elseif ($this->getAccountContainer()->getAccountModule('windowsUser') != null) { @@ -1750,7 +1750,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP if ($this->manageCn($modules) && (!isset($this->attributes['cn'][0]) || ($this->attributes['cn'][0] == ''))) { // set a default value for common name if (($this->get_scope() == 'host') && isset($_POST['uid'])) { - if (substr($_POST['uid'], -1, 1) == '$') { + if (str_ends_with($_POST['uid'], '$')) { $this->attributes['cn'][0] = substr($_POST['uid'], 0, strlen($_POST['uid']) - 1); } else { @@ -1785,7 +1785,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $uidInput = new htmlResponsiveInputField($uidLabel, 'uid', $userName, 'uid'); $uidInput->setRequired(true); $uidInput->setFieldMaxLength(100); - $return->add($uidInput, 12); + $return->add($uidInput); if ($this->manageCn($modules)) { $this->addMultiValueInputTextField($return, 'cn', _("Common name")); } @@ -1802,7 +1802,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP if (isset($this->attributes['gecos'][0])) { $gecos = $this->attributes['gecos'][0]; } - $return->add(new htmlResponsiveInputField(_('Gecos'), 'gecos', $gecos, 'gecos'), 12); + $return->add(new htmlResponsiveInputField(_('Gecos'), 'gecos', $gecos, 'gecos')); } $primaryGroup = []; if (isset($this->attributes['gidNumber'][0])) { @@ -1810,7 +1810,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } $gidNumberSelect = new htmlResponsiveSelect('gidNumber', $groups, $primaryGroup, _('Primary group'), 'gidNumber'); $gidNumberSelect->setHasDescriptiveElements(true); - $return->add($gidNumberSelect, 12); + $return->add($gidNumberSelect); if ($this->get_scope() == 'user') { // new Unix group with same name @@ -1831,10 +1831,10 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $return->addField($additionalGroups); } // home directory - $homeDir = isset($this->attributes[$homeDirAttr][0]) ? $this->attributes[$homeDirAttr][0] : ''; + $homeDir = $this->attributes[$homeDirAttr][0] ?? ''; $homedirInput = new htmlResponsiveInputField(_('Home directory'), 'homeDirectory', $homeDir, 'homeDirectory'); $homedirInput->setRequired(true); - $return->add($homedirInput, 12); + $return->add($homedirInput); if (($_SESSION['config']->get_scriptPath() != null) && ($_SESSION['config']->get_scriptPath() != '')) { if ($this->getAccountContainer()->isNewAccount) { // get list of lamdaemon servers @@ -1864,7 +1864,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP if (isset($this->attributes['loginShell'][0])) { $selectedShell = [$this->attributes['loginShell'][0]]; } - $return->add(new htmlResponsiveSelect('loginShell', $shelllist, $selectedShell, _('Login shell'), 'loginShell'), 12); + $return->add(new htmlResponsiveSelect('loginShell', $shelllist, $selectedShell, _('Login shell'), 'loginShell')); } // password buttons if (checkIfWriteAccessIsAllowed($this->get_scope()) @@ -1891,7 +1891,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } else { // add button - $return->add(new htmlButton('addObjectClass', _('Add Unix extension')), 12); + $return->add(new htmlButton('addObjectClass', _('Add Unix extension'))); } return $return; } @@ -1911,7 +1911,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } if (empty($this->moduleSettings[$generatorOption])) { $message = new htmlStatusMessage('ERROR', _('Invalid configuration detected. Please edit your server profile (module settings) and fill all required fields.')); - $content->add($message, 12); + $content->add($message); } } @@ -1923,12 +1923,12 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP function display_html_delete() { $return = new htmlResponsiveRow(); if ($this->get_scope() == 'user' && ($_SESSION['config']->get_scriptPath() != null)) { - $return->add(new htmlResponsiveInputCheckbox('deletehomedir', true, _('Delete home directory'), 'deletehomedir'), 12); + $return->add(new htmlResponsiveInputCheckbox('deletehomedir', true, _('Delete home directory'), 'deletehomedir')); } $typeManager = new TypeManager(); $sudoTypes = $typeManager->getConfiguredTypesForScope('sudo'); if (($this->get_scope() == 'user') && !empty($sudoTypes)) { - $return->add(new htmlResponsiveInputCheckbox('deleteSudoers', true, _('Delete sudo rights'), 'deleteSudoers'), 12); + $return->add(new htmlResponsiveInputCheckbox('deleteSudoers', true, _('Delete sudo rights'), 'deleteSudoers')); } return $return; } @@ -2018,8 +2018,8 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $moduleList = $this->getAccountContainer()->get_type()->getModules(); $showWindowsSync = $this->isWindows($moduleList); if ($showUnixSync && ($showGonSync || $showWindowsSync)) { - $return->add(new htmlSubTitle(_('Sync groups')), 12); - $return->add(new htmlResponsiveInputCheckbox('syncDeleteGroups', true, _('Delete non-matching entries')), 12); + $return->add(new htmlSubTitle(_('Sync groups'))); + $return->add(new htmlResponsiveInputCheckbox('syncDeleteGroups', true, _('Delete non-matching entries'))); $return->addVerticalSpacer('1rem'); if ($showGonSync) { $syncButtons = new htmlGroup(); @@ -2043,7 +2043,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $return->addVerticalSpacer('2rem'); $backButton = new htmlAccountPageButton(static::class, 'attributes', 'back', _('Back')); - $return->add($backButton, 12); + $return->add($backButton); return $return; } @@ -2063,12 +2063,12 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers(); for ($i = 0; $i < sizeof($lamdaemonServers); $i++) { $label = $lamdaemonServers[$i]->getLabel(); - $remote = new \LAM\REMOTE\Remote(); + $remote = new Remote(); try { $remote->connect($lamdaemonServers[$i]); } catch (LAMException $e) { - $return->add(new htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage()), 12); + $return->add(new htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage())); continue; } $result = $remote->execute( @@ -2111,7 +2111,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP else { $message = new htmlStatusMessage('WARN', htmlspecialchars($messageParams[0])); } - $return->add($message, 12); + $return->add($message); } } } @@ -2135,12 +2135,12 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP if ($this->get_scope() == 'user') { $shelllist = $this->getShells(); // list of all valid shells // primary Unix group - $return->add(new htmlResponsiveSelect('posixAccount_primaryGroup', $groups, [], _('Primary group'), 'gidNumber'), 12); + $return->add(new htmlResponsiveSelect('posixAccount_primaryGroup', $groups, [], _('Primary group'), 'gidNumber')); // additional group memberships $addGroupSelect = new htmlResponsiveSelect('posixAccount_additionalGroup', $groups, [], _('Additional groups'), 'addgroup', 10); $addGroupSelect->setMultiSelect(true); $addGroupSelect->setTransformSingleSelect(false); - $return->add($addGroupSelect, 12); + $return->add($addGroupSelect); // group of names if (self::areGroupOfNamesActive()) { $gons = $this->findGroupOfNames(); @@ -2152,35 +2152,35 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $gonSelect->setHasDescriptiveElements(true); $gonSelect->setMultiSelect(true); $gonSelect->setTransformSingleSelect(false); - $return->add($gonSelect, 12); + $return->add($gonSelect); } // common name if ($this->manageCn($modules)) { - $return->add(new htmlResponsiveInputField(_('Common name'), 'posixAccount_cn', '', 'cn'), 12); + $return->add(new htmlResponsiveInputField(_('Common name'), 'posixAccount_cn', '', 'cn')); } // gecos - $return->add(new htmlResponsiveInputField(_('Gecos'), 'posixAccount_gecos', '$firstname $lastname', 'gecos'), 12); + $return->add(new htmlResponsiveInputField(_('Gecos'), 'posixAccount_gecos', '$firstname $lastname', 'gecos')); // home directory - $return->add(new htmlResponsiveInputField(_('Home directory'), 'posixAccount_homeDirectory', '/home/$user', 'homeDirectory'), 12); + $return->add(new htmlResponsiveInputField(_('Home directory'), 'posixAccount_homeDirectory', '/home/$user', 'homeDirectory')); // login shell - $return->add(new htmlResponsiveSelect('posixAccount_loginShell', $shelllist, ["/bin/bash"], _('Login shell'), 'loginShell'), 12); + $return->add(new htmlResponsiveSelect('posixAccount_loginShell', $shelllist, ["/bin/bash"], _('Login shell'), 'loginShell')); // lamdaemon settings if ($_SESSION['config']->get_scriptPath() != null) { - $return->add(new htmlSubTitle(_('Create home directory')), 12); + $return->add(new htmlSubTitle(_('Create home directory'))); $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers(); for ($h = 0; $h < sizeof($lamdaemonServers); $h++) { $server = $lamdaemonServers[$h]->getServer(); $label = $lamdaemonServers[$h]->getLabel(); - $return->add(new htmlResponsiveInputCheckbox('posixAccount_createHomedir_' . $h, in_array($server, $this->lamdaemonServers), $label, 'createhomedir', false), 12); + $return->add(new htmlResponsiveInputCheckbox('posixAccount_createHomedir_' . $h, in_array($server, $this->lamdaemonServers), $label, 'createhomedir', false)); } } } elseif ($this->get_scope() == 'host') { // primary Unix group - $return->add(new htmlResponsiveSelect('posixAccount_primaryGroup', $groups, [], _('Primary group'), 'gidNumber'), 12); + $return->add(new htmlResponsiveSelect('posixAccount_primaryGroup', $groups, [], _('Primary group'), 'gidNumber')); } if ($this->isOptional($modules)) { - $return->add(new htmlResponsiveInputCheckbox('posixAccount_addExt', false, _('Automatically add this extension'), 'autoAdd'), 12); + $return->add(new htmlResponsiveInputCheckbox('posixAccount_addExt', false, _('Automatically add this extension'), 'autoAdd')); } return $return; } @@ -2334,7 +2334,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP if ($hasUserConfig) { // user options $configUserContainer = new htmlResponsiveRow(); - $configUserContainer->add(new htmlSubTitle(_("Users")), 12); + $configUserContainer->add(new htmlSubTitle(_("Users"))); foreach ($allScopes[static::class] as $typeId) { if (!(getScopeFromTypeId($typeId) === 'user')) { continue; @@ -2363,29 +2363,29 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP 'windowsDomain' => ['posixAccount_' . $typeId . '_windowsIDPoolDNUsers'], 'magicNumber' => ['posixAccount_' . $typeId . '_magicNumberUser'] ]); - $configUserContainer->add($uidGeneratorSelect, 12); + $configUserContainer->add($uidGeneratorSelect); $uidUsersGeneratorDN = new htmlResponsiveInputField(_('Samba ID pool DN'), 'posixAccount_' . $typeId . '_sambaIDPoolDNUsers', null, 'sambaIDPoolDN'); $uidUsersGeneratorDN->setRequired(true); - $configUserContainer->add($uidUsersGeneratorDN, 12); + $configUserContainer->add($uidUsersGeneratorDN); $uidUsersGeneratorWinDN = new htmlResponsiveInputField(_('Windows domain info DN'), 'posixAccount_' . $typeId . '_windowsIDPoolDNUsers', null, 'windowsIDPoolDN'); $uidUsersGeneratorWinDN->setRequired(true); - $configUserContainer->add($uidUsersGeneratorWinDN, 12); + $configUserContainer->add($uidUsersGeneratorWinDN); $minUid = new htmlResponsiveInputField(_('Minimum UID number'), 'posixAccount_' . $typeId . '_minUID', null, 'minMaxUser'); $minUid->setRequired(true); - $configUserContainer->add($minUid, 12); + $configUserContainer->add($minUid); $maxUid = new htmlResponsiveInputField(_('Maximum UID number'), 'posixAccount_' . $typeId . '_maxUID', null, 'minMaxUser'); $maxUid->setRequired(true); - $configUserContainer->add($maxUid, 12); + $configUserContainer->add($maxUid); $magicNumberUser = new htmlResponsiveInputField(_('Magic number'), 'posixAccount_' . $typeId . '_magicNumberUser', null, 'magicNumber'); $magicNumberUser->setRequired(true); - $configUserContainer->add($magicNumberUser, 12); - $configUserContainer->add(new htmlResponsiveInputField(_('Suffix for UID/user name check'), 'posixAccount_' . $typeId . '_uidCheckSuffixUser', '', 'uidCheckSuffix'), 12); - $configUserContainer->add(new htmlResponsiveInputField(_('User name suggestion'), 'posixAccount_' . $typeId . '_userNameSuggestion', '@givenname@%sn%', 'userNameSuggestion'), 12); + $configUserContainer->add($magicNumberUser); + $configUserContainer->add(new htmlResponsiveInputField(_('Suffix for UID/user name check'), 'posixAccount_' . $typeId . '_uidCheckSuffixUser', '', 'uidCheckSuffix')); + $configUserContainer->add(new htmlResponsiveInputField(_('User name suggestion'), 'posixAccount_' . $typeId . '_userNameSuggestion', '@givenname@%sn%', 'userNameSuggestion')); $configUserContainer->addVerticalSpacer('2rem'); $hiddenOptionsContainerHead = new htmlGroup(); $hiddenOptionsContainerHead->addElement(new htmlOutputText(_('Hidden options'))); $hiddenOptionsContainerHead->addElement(new htmlHelpLink('hiddenOptions')); - $configUserContainer->add($hiddenOptionsContainerHead, 12); + $configUserContainer->add($hiddenOptionsContainerHead); $configUserContainer->addVerticalSpacer('0.5rem'); $configUserContainer->add(new htmlResponsiveInputCheckbox('posixAccount_' . $typeId . '_hidegecos', false, _('Gecos'), null, true), 12, 4, 4); $configUserContainer->add(new htmlResponsiveInputCheckbox('posixAccount_' . $typeId . '_hidepassword', false, _('Password'), null, true), 12, 4, 4); @@ -2397,7 +2397,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $syncGroupsCheckbox = new htmlResponsiveInputCheckbox('posixAccount_' . $typeId . '_syncGroups', false, _('Sync groups'), null, true); $syncGroupsCheckbox->setTableRowsToHide(['posixAccount_' . $typeId . '_syncGroupsExclusions']); $configUserContainer->add($syncGroupsCheckbox, 12, 4, 4); - $configUserContainer->add(new htmlResponsiveInputTextarea('posixAccount_' . $typeId . '_syncGroupsExclusions', '', 20, 4, _('Exclude from group sync'), 'excludeFromGroupSync'), 12); + $configUserContainer->add(new htmlResponsiveInputTextarea('posixAccount_' . $typeId . '_syncGroupsExclusions', '', 20, 4, _('Exclude from group sync'), 'excludeFromGroupSync')); } } $return[] = $configUserContainer; @@ -2405,7 +2405,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP // host options if ($hasHostConfig) { $configHostContainer = new htmlResponsiveRow(); - $configHostContainer->add(new htmlSubTitle(_("Hosts")), 12); + $configHostContainer->add(new htmlSubTitle(_("Hosts"))); foreach ($allScopes[static::class] as $typeId) { if (!(getScopeFromTypeId($typeId) === 'host')) { continue; @@ -2434,43 +2434,43 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP 'windowsDomain' => ['posixAccount_' . $typeId . '_windowsIDPoolDNHosts'], 'magicNumber' => ['posixAccount_' . $typeId . '_magicNumberHost'] ]); - $configHostContainer->add($uidHostGeneratorSelect, 12); + $configHostContainer->add($uidHostGeneratorSelect); $uidHostsGeneratorDN = new htmlResponsiveInputField(_('Samba ID pool DN'), 'posixAccount_' . $typeId . '_sambaIDPoolDNHosts', null, 'sambaIDPoolDN'); $uidHostsGeneratorDN->setRequired(true); - $configHostContainer->add($uidHostsGeneratorDN, 12); + $configHostContainer->add($uidHostsGeneratorDN); $uidHostsGeneratorWinDN = new htmlResponsiveInputField(_('Windows domain info DN'), 'posixAccount_' . $typeId . '_windowsIDPoolDNHosts', null, 'windowsIDPoolDN'); $uidHostsGeneratorWinDN->setRequired(true); - $configHostContainer->add($uidHostsGeneratorWinDN, 12); + $configHostContainer->add($uidHostsGeneratorWinDN); $minUid = new htmlResponsiveInputField(_('Minimum UID number'), 'posixAccount_' . $typeId . '_minMachine', null, 'minMaxHost'); $minUid->setRequired(true); - $configHostContainer->add($minUid, 12); + $configHostContainer->add($minUid); $maxUid = new htmlResponsiveInputField(_('Maximum UID number'), 'posixAccount_' . $typeId . '_maxMachine', null, 'minMaxHost'); $maxUid->setRequired(true); - $configHostContainer->add($maxUid, 12); + $configHostContainer->add($maxUid); $magicNumberHost = new htmlResponsiveInputField(_('Magic number'), 'posixAccount_' . $typeId . '_magicNumberHost', null, 'magicNumber'); $magicNumberHost->setRequired(true); - $configHostContainer->add($magicNumberHost, 12); - $configHostContainer->add(new htmlResponsiveInputField(_('Suffix for UID/user name check'), 'posixAccount_' . $typeId . '_uidCheckSuffixHost', '', 'uidCheckSuffix'), 12); + $configHostContainer->add($magicNumberHost); + $configHostContainer->add(new htmlResponsiveInputField(_('Suffix for UID/user name check'), 'posixAccount_' . $typeId . '_uidCheckSuffixHost', '', 'uidCheckSuffix')); $hiddenOptionsContainerHead = new htmlGroup(); $hiddenOptionsContainerHead->addElement(new htmlOutputText(_('Hidden options'))); $hiddenOptionsContainerHead->addElement(new htmlHelpLink('hiddenOptions')); $configHostContainer->addLabel($hiddenOptionsContainerHead, 12); $configHostContainer->addField(new htmlOutputText('')); $configHostContainer->addVerticalSpacer('0.5rem'); - $configHostContainer->add(new htmlResponsiveInputCheckbox('posixAccount_' . $typeId . '_hidegecos', false, _('Gecos'), null, false), 12); + $configHostContainer->add(new htmlResponsiveInputCheckbox('posixAccount_' . $typeId . '_hidegecos', false, _('Gecos'), null, false)); $configHostContainer->addVerticalSpacer('2rem'); } $return[] = $configHostContainer; } // common options $configOptionsContainer = new htmlResponsiveRow(); - $configOptionsContainer->add(new htmlSubTitle(_('Options')), 12); + $configOptionsContainer->add(new htmlSubTitle(_('Options'))); $configOptionsContainer->add(new htmlResponsiveSelect('posixAccount_pwdHash', getSupportedHashTypes(), - ['CRYPT-SHA512'], _("Password hash type"), 'pwdHash'), 12); - $configOptionsContainer->add(new htmlResponsiveInputTextarea('posixAccount_shells', implode("\r\n", $this->getShells()), 30, 4, _('Login shells'), 'loginShells'), 12); - $configOptionsContainer->add(new htmlResponsiveInputCheckbox('posixAccount_primaryGroupAsSecondary', false, _('Set primary group as memberUid'), 'primaryGroupAsSecondary'), 12); + ['CRYPT-SHA512'], _("Password hash type"), 'pwdHash')); + $configOptionsContainer->add(new htmlResponsiveInputTextarea('posixAccount_shells', implode("\r\n", $this->getShells()), 30, 4, _('Login shells'), 'loginShells')); + $configOptionsContainer->add(new htmlResponsiveInputCheckbox('posixAccount_primaryGroupAsSecondary', false, _('Set primary group as memberUid'), 'primaryGroupAsSecondary')); if ($isWindows) { - $configOptionsContainer->add(new htmlResponsiveInputCheckbox('posixAccount_noObjectClass', false, _('Do not add object class'), 'noObjectClass'), 12); + $configOptionsContainer->add(new htmlResponsiveInputCheckbox('posixAccount_noObjectClass', false, _('Do not add object class'), 'noObjectClass')); } $return[] = $configOptionsContainer; @@ -2483,10 +2483,8 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP */ public function check_configOptions($typeIds, &$options) { $return = []; - $scopes = []; $ranges = []; foreach ($typeIds as $typeId) { - $scopes[] = getScopeFromTypeId($typeId); // user settings if (getScopeFromTypeId($typeId) === 'user') { if ($options['posixAccount_' . $typeId . '_uidGeneratorUsers'][0] == 'range') { @@ -2660,7 +2658,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } else { $errMsg = $this->messages['uidNumber'][4]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } } @@ -2671,14 +2669,14 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } else { $errMsg = $this->messages['uidNumber'][4]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } } } else { $errMsg = $this->messages['uidNumber'][4]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } // GID number @@ -2696,13 +2694,13 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } else { $errMsg = $this->messages['gidNumber'][0]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } } else { $errMsg = $this->messages['gidNumber'][1]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } // GECOS @@ -2713,7 +2711,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } else { $errMsg = $this->messages['gecos'][0]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } } @@ -2760,8 +2758,8 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $userName = $this->getNextUserName($userName, $selectedModules); } $errMsg = $this->messages['uid'][9]; - array_push($errMsg, [$i, $userName, $rawAccount[$ids['posixAccount_userName']], - htmlspecialchars($existingUsers[$rawAccount[$ids['posixAccount_userName']]])]); + $errMsg[] = [$i, $userName, $rawAccount[$ids['posixAccount_userName']], + htmlspecialchars($existingUsers[$rawAccount[$ids['posixAccount_userName']]])]; $errors[] = $errMsg; } if (get_preg($rawAccount[$ids['posixAccount_userName']], 'username')) { @@ -2769,7 +2767,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } else { $errMsg = $this->messages['uid'][7]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } // home directory @@ -2781,7 +2779,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } else { $errMsg = $this->messages['homeDirectory'][2]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } // create home directory @@ -2795,7 +2793,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } if (!$lamdaemonServerValid) { $errMsg = $this->messages['homeDirectory'][4]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } } @@ -2808,7 +2806,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } else { $errMsg = $this->messages['shell'][0]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } if ($this->isPasswordManaged($typeId)) { @@ -2824,7 +2822,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } else { $errMsg = $this->messages['passwordDisabled'][0]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } // password @@ -2849,7 +2847,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP elseif ($rawAccount[$ids['posixAccount_password']] != "") { $errMsg = $this->messages['userPassword'][4]; $errMsg[2] = str_replace('%', '%%', $errMsg[2]); // double "%" because of later sprintf - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } } @@ -2862,7 +2860,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } else { $errMsg = $this->messages['cn'][1]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } } @@ -2888,8 +2886,8 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP $userName = $this->getNextUserName($userName, $selectedModules); } $errMsg = $this->messages['uid'][10]; - array_push($errMsg, [$i, $userName, $rawAccount[$ids['posixAccount_hostName']], - htmlspecialchars($existingUsers[$rawAccount[$ids['posixAccount_hostName']]])]); + $errMsg[] = [$i, $userName, $rawAccount[$ids['posixAccount_hostName']], + htmlspecialchars($existingUsers[$rawAccount[$ids['posixAccount_hostName']]])]; $errors[] = $errMsg; } if (get_preg($rawAccount[$ids['posixAccount_hostName']], 'hostname')) { @@ -2898,7 +2896,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } else { $errMsg = $this->messages['uid'][8]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $errors[] = $errMsg; } // description @@ -3075,7 +3073,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP elseif ($temp['counter'] < (sizeof($temp['groups']) + sizeof($temp['createHomes']))) { $pos = $temp['createHomes'][$temp['counter'] - sizeof($temp['groups'])]; try { - $remote = new \LAM\REMOTE\Remote(); + $remote = new Remote(); $remoteServer = $_SESSION['config']->getScriptServerByName($data[$pos][$ids['posixAccount_createHomeDir']]); $remote->connect($remoteServer); $result = self::createHomeDirectory($remote, $remoteServer, $data[$pos][$ids['posixAccount_userName']], @@ -3237,7 +3235,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } // find free numbers between existing ones else { - $k = intval($minID); + $k = $minID; while (in_array($k, $uids)) { $k++; } @@ -3346,15 +3344,15 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP if (!empty($this->selfServiceSettings->moduleSettings['posixAccount_useOldPwd']) && ($this->selfServiceSettings->moduleSettings['posixAccount_useOldPwd'][0] == 'true')) { $pwd0 = new htmlResponsiveInputField(_('Old password'), 'posixAccount_passwordOld'); $pwd0->setIsPassword(true, true); - $row->add($pwd0, 12); + $row->add($pwd0); } $pwd1 = new htmlResponsiveInputField($this->getSelfServiceLabel('password', _('New password')), 'posixAccount_password'); $pwd1->setIsPassword(true, true); - $row->add($pwd1, 12); + $row->add($pwd1); $pwd2 = new htmlResponsiveInputField(_('Reenter password'), 'posixAccount_password2'); $pwd2->setIsPassword(true); $pwd2->setSameValueFieldID('posixAccount_password'); - $row->add($pwd2, 12); + $row->add($pwd2); $return['password'] = $row; } if ($passwordChangeOnly) { @@ -3648,7 +3646,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP } $typeFilter = $type->getAdditionalLdapFilter(); if (!empty($typeFilter)) { - if (strpos($typeFilter, '(') !== 0) { + if (!str_starts_with($typeFilter, '(')) { $typeFilter = '(' . $typeFilter . ')'; } $filter = '(&' . $filter . $typeFilter . ')'; @@ -3835,7 +3833,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP * @return String user name */ protected function getUserNameSuggestion($attrs, $typeId) { - $attributes = array_change_key_case($attrs, CASE_LOWER); + $attributes = array_change_key_case($attrs); $format = '@givenname@%sn%'; if (isset($this->moduleSettings['posixAccount_' . $typeId . '_userNameSuggestion'][0])) { $format = strtolower($this->moduleSettings['posixAccount_' . $typeId . '_userNameSuggestion'][0]); @@ -3846,7 +3844,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP for ($i = 0; $i < sizeof($wildcards[0]); $i++) { $wc = substr($wildcards[0][$i], 1, strlen($wildcards[0][$i]) - 2); $value = ''; - if (isset($attributes[$wc][0]) && !empty($attributes[$wc][0])) { + if (!empty($attributes[$wc][0])) { $value = $this->cleanSuggestionPart($attributes[$wc][0][0]); } $format = str_replace('@' . $wc . '@', $value, $format); @@ -3902,7 +3900,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP */ public function isLocked($modules, ?array $attributes = null) { if ($attributes === null) { - $attributes = array_change_key_case($this->attributes, CASE_LOWER); + $attributes = array_change_key_case($this->attributes); } $passwordAttribute = strtolower($this->getPasswordAttrName($modules)); return isset($attributes[$passwordAttribute][0]) @@ -4221,10 +4219,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP * @inheritDoc */ public function getPasswordQuickChangePasswordStrengthUserName(): ?string { - if (isset($this->attributes['uid'][0])) { - return $this->attributes['uid'][0]; - } - return null; + return $this->attributes['uid'][0] ?? null; } /** diff --git a/lam/lib/modules/pykotaPrinter.inc b/lam/lib/modules/pykotaPrinter.inc index e6e343197..1f05e8d37 100644 --- a/lam/lib/modules/pykotaPrinter.inc +++ b/lam/lib/modules/pykotaPrinter.inc @@ -67,7 +67,7 @@ class pykotaPrinter extends baseModule { * @return boolean true if module fits */ public function can_manage() { - return in_array($this->get_scope(), ['pykotaPrinterType']); + return $this->get_scope() === 'pykotaPrinterType'; } /** @@ -138,7 +138,7 @@ class pykotaPrinter extends baseModule { ]; // profile options $profileContainer = new htmlResponsiveRow(); - $profileContainer->add(new htmlResponsiveInputField(_('Maximum job size'), 'pykotaPrinter_pykotaMaxJobSize', '', 'pykotaMaxJobSize'), 12); + $profileContainer->add(new htmlResponsiveInputField(_('Maximum job size'), 'pykotaPrinter_pykotaMaxJobSize', '', 'pykotaMaxJobSize')); $return['profile_options'] = $profileContainer; $return['profile_mappings']['pykotaPrinter_pykotaMaxJobSize'] = 'pykotaMaxJobSize'; $return['profile_checks']['pykotaPrinter_pykotaMaxJobSize'] = [ @@ -256,7 +256,7 @@ class pykotaPrinter extends baseModule { } $pykotaPassThroughSelect = new htmlResponsiveSelect('pykotaPassThrough', $this->passThroughOptions, [$pykotaPassThroughOption], _('Passthrough'), 'pykotaPassThrough'); $pykotaPassThroughSelect->setHasDescriptiveElements(true); - $container->add($pykotaPassThroughSelect, 12); + $container->add($pykotaPassThroughSelect); // description $this->addMultiValueInputTextField($container, 'description', _('Description'), false, null, true); // printer groups @@ -352,7 +352,7 @@ class pykotaPrinter extends baseModule { if (isset($_POST['pykotaPricePerJob']) && ($_POST['pykotaPricePerJob'] != '')) { $pykotaPricePerJob = $_POST['pykotaPricePerJob']; $pykotaPricePerJob = str_replace(',', '.', $pykotaPricePerJob); - if (strpos($pykotaPricePerJob, '.') === false) { + if (!str_contains($pykotaPricePerJob, '.')) { $pykotaPricePerJob .= '.0'; } if (!get_preg($pykotaPricePerJob, 'float')) { @@ -365,7 +365,7 @@ class pykotaPrinter extends baseModule { if (isset($_POST['pykotaPricePerPage']) && ($_POST['pykotaPricePerPage'] != '')) { $pykotaPricePerPage = $_POST['pykotaPricePerPage']; $pykotaPricePerPage = str_replace(',', '.', $pykotaPricePerPage); - if (strpos($pykotaPricePerPage, '.') === false) { + if (!str_contains($pykotaPricePerPage, '.')) { $pykotaPricePerPage .= '.0'; } if (!get_preg($pykotaPricePerPage, 'float')) { @@ -377,7 +377,7 @@ class pykotaPrinter extends baseModule { $this->attributes['pykotaPassThrough'][0] = $_POST['pykotaPassThrough']; // delete members foreach ($_POST as $key => $value) { - if (strpos($key, 'uniqueMemberDel_') === 0) { + if (str_starts_with($key, 'uniqueMemberDel_')) { $index = substr($key, strlen('uniqueMemberDel_')); unset($this->attributes['uniqueMember'][$index]); $this->attributes['uniqueMember'] = array_values($this->attributes['uniqueMember']); @@ -421,7 +421,7 @@ class pykotaPrinter extends baseModule { $membersSelect->setHasDescriptiveElements(true); $membersSelect->setMultiSelect(true); $membersSelect->setTransformSingleSelect(false); - $return->add($membersSelect, 12); + $return->add($membersSelect); $filterGroup = new htmlGroup(); $filterGroup->addElement(new htmlOutputText(_('Filter'))); $filterInput = new htmlInputField('newFilter', null); @@ -429,13 +429,13 @@ class pykotaPrinter extends baseModule { $filterInput->filterSelectBox('members'); $filterGroup->addElement($filterInput); $filterGroup->addElement(new htmlHelpLink('filter')); - $return->add($filterGroup, 12); + $return->add($filterGroup); $return->addVerticalSpacer('2rem'); $buttonTable = new htmlGroup(); $buttonTable->addElement(new htmlAccountPageButton(static::class, 'attributes', 'addMembers', _('Add'))); $buttonTable->addElement(new htmlSpacer('0.5rem', null)); $buttonTable->addElement(new htmlAccountPageButton(static::class, 'attributes', 'cancel', _('Cancel'))); - $return->add($buttonTable, 12); + $return->add($buttonTable); return $return; } @@ -474,12 +474,12 @@ class pykotaPrinter extends baseModule { if (!empty($rawAccounts[$i][$ids['pykotaPrinter_cn']])) { if (!get_preg($rawAccounts[$i][$ids['pykotaPrinter_cn']], 'username')) { $errMsg = $this->messages['cn'][1]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $messages[] = $errMsg; } elseif ($this->cnExists($rawAccounts[$i][$ids['pykotaPrinter_cn']])) { $errMsg = $this->messages['cn'][3]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $messages[] = $errMsg; } else { @@ -497,12 +497,12 @@ class pykotaPrinter extends baseModule { if (!empty($rawAccounts[$i][$ids['pykotaPrinter_pykotaPricePerJob']])) { $pykotaPricePerJob = $rawAccounts[$i][$ids['pykotaPrinter_pykotaPricePerJob']]; $pykotaPricePerJob = str_replace(',', '.', $pykotaPricePerJob); - if (strpos($pykotaPricePerJob, '.') === false) { + if (!str_contains($pykotaPricePerJob, '.')) { $pykotaPricePerJob .= '.0'; } if (!get_preg($pykotaPricePerJob, 'float')) { $errMsg = $this->messages['pykotaPricePerJob'][1]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $messages[] = $errMsg; } else { @@ -516,12 +516,12 @@ class pykotaPrinter extends baseModule { if (!empty($rawAccounts[$i][$ids['pykotaPrinter_pykotaPricePerPage']])) { $pykotaPricePerPage = $rawAccounts[$i][$ids['pykotaPrinter_pykotaPricePerPage']]; $pykotaPricePerPage = str_replace(',', '.', $pykotaPricePerPage); - if (strpos($pykotaPricePerPage, '.') === false) { + if (!str_contains($pykotaPricePerPage, '.')) { $pykotaPricePerPage .= '.0'; } if (!get_preg($pykotaPricePerPage, 'float')) { $errMsg = $this->messages['pykotaPricePerPage'][1]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $messages[] = $errMsg; } else { @@ -538,7 +538,7 @@ class pykotaPrinter extends baseModule { } else { $errMsg = $this->messages['pykotaPassThrough'][0]; - array_push($errMsg, [$i]); + $errMsg[] = [$i]; $messages[] = $errMsg; } } @@ -564,7 +564,7 @@ class pykotaPrinter extends baseModule { } if (!$found) { $errMsg = $this->messages['uniqueMember'][0]; - array_push($errMsg, [$i, htmlspecialchars($cn)]); + $errMsg[] = [$i, htmlspecialchars($cn)]; $messages[] = $errMsg; } } diff --git a/lam/lib/persistence.inc b/lam/lib/persistence.inc index b51b43b4a..e12ac2e57 100644 --- a/lam/lib/persistence.inc +++ b/lam/lib/persistence.inc @@ -248,7 +248,7 @@ class ConfigDataExporter { public function _getWebauthn() { $data = []; if (extension_loaded('PDO') - && in_array('sqlite', \PDO::getAvailableDrivers())) { + && in_array('sqlite', PDO::getAvailableDrivers())) { include_once __DIR__ . '/webauthn.inc'; $webauthnManager = new WebauthnManager(); $webauthnDatabase = $webauthnManager->getDatabase(); @@ -430,43 +430,20 @@ class ConfigDataImporter { continue; } $key = $step->getKey(); - switch ($key) { - case 'mainConfig': - $this->importMainConfig($step->getValue()); - break; - case 'certificates': - $this->importCertificates($step->getValue()); - break; - case 'serverProfiles': - $this->importServerProfiles($step); - break; - case 'accountProfiles': - $this->importAccountProfiles($step); - break; - case 'accountProfileTemplates': - $this->importAccountProfileTemplates($step); - break; - case 'pdfProfiles': - $this->importPdfProfiles($step); - break; - case 'pdfProfileTemplates': - $this->importPdfProfileTemplates($step); - break; - case 'selfServiceProfiles': - $this->importSelfServiceProfiles($step); - break; - case 'webauthn': - $this->importWebauthn($step); - break; - case 'cronJobs': - $this->importCronJobs($step); - break; - case 'requestAccess': - $this->importRequestAccess($step); - break; - default: - logNewMessage(LOG_WARNING, 'Unknown import type: ' . $key); - } + match ($key) { + 'mainConfig' => $this->importMainConfig($step->getValue()), + 'certificates' => $this->importCertificates($step->getValue()), + 'serverProfiles' => $this->importServerProfiles($step), + 'accountProfiles' => $this->importAccountProfiles($step), + 'accountProfileTemplates' => $this->importAccountProfileTemplates($step), + 'pdfProfiles' => $this->importPdfProfiles($step), + 'pdfProfileTemplates' => $this->importPdfProfileTemplates($step), + 'selfServiceProfiles' => $this->importSelfServiceProfiles($step), + 'webauthn' => $this->importWebauthn($step), + 'cronJobs' => $this->importCronJobs($step), + 'requestAccess' => $this->importRequestAccess($step), + default => logNewMessage(LOG_WARNING, 'Unknown import type: ' . $key), + }; } } @@ -544,7 +521,7 @@ class ConfigDataImporter { try { $accountProfilePersistenceManager->writeAccountProfile($typeId, $accountProfileName, $serverProfileName, $accountProfileData); } - catch (LAMException $e) { + catch (LAMException) { $failedProfiles[] = $serverProfileName . ':' . $typeId . ':' . $accountProfileName; } } @@ -878,13 +855,13 @@ class ImporterStep { class ConfigurationDatabase { /** table for schema versions */ - const TABLE_SCHEMA_VERSIONS = 'schema_versions'; + public const TABLE_SCHEMA_VERSIONS = 'schema_versions'; /** row name for system schema version */ - const ROW_VERSION_SYSTEM = 'system'; + private const ROW_VERSION_SYSTEM = 'system'; /** table for main configuration */ - const TABLE_MAIN_CONFIG = 'main_configuration'; + public const TABLE_MAIN_CONFIG = 'main_configuration'; /** row name for main config schema version */ - const ROW_VERSION_MAIN_CONFIG = 'main_configuration'; + private const ROW_VERSION_MAIN_CONFIG = 'main_configuration'; private $cfgMain; @@ -1000,9 +977,9 @@ class ConfigurationDatabase { function dbTableExists(PDO $pdo, string $tableName): bool { try { $result = $pdo->query("SELECT 1 FROM $tableName LIMIT 1"); - return ($result === false) ? false : true; + return ($result !== false); } - catch (PDOException $e) { + catch (PDOException) { return false; } } diff --git a/lam/lib/schema.inc b/lam/lib/schema.inc index 787836a77..7a7e1067f 100644 --- a/lam/lib/schema.inc +++ b/lam/lib/schema.inc @@ -44,9 +44,9 @@ namespace LAM\SCHEMA; */ class SchemaItem { /** The OID of this schema item. */ - var $oid; + protected $oid; /** The description of this schema item. */ - var $description; + protected $description; /** Initialize class members to default values. */ function initVars() { @@ -83,19 +83,19 @@ class SchemaItem { */ class ObjectClass extends SchemaItem { /** This objectClass' name, ie "inetOrgPerson" */ - var $name; + protected $name; /** array of objectClass names from which this objectClass inherits */ - var $sup_classes; + protected $sup_classes; /** one of STRUCTURAL, ABSTRACT, or AUXILIARY */ - var $type; + protected $type; /** arrays of attribute names that this objectClass requires */ - var $must_attrs; + protected $must_attrs; /** arrays of attribute names that this objectClass allows, but does not require */ - var $may_attrs; + protected $may_attrs; /** boolean value indicating whether this objectClass is obsolete */ - var $is_obsolete; + protected $is_obsolete; /** array of objectClasses which inherit from this one (must be set at runtime explicitly by the caller) */ - var $children_objectclasses; + protected $children_objectclasses; /** Initialize the class' member variables */ function initVars() { @@ -135,7 +135,7 @@ class ObjectClass extends SchemaItem { $this->name .= " " . $strings[$i]; } } - while (!preg_match('/\'$/s', $strings[$i])); + while (!str_ends_with($strings[$i], '\'')); } else { $i++; @@ -148,7 +148,7 @@ class ObjectClass extends SchemaItem { $this->name .= " " . $strings[$i]; } } - while (!preg_match('/\'$/s', $strings[$i])); + while (!str_ends_with($strings[$i], '\'')); do { $i++; } @@ -167,7 +167,7 @@ class ObjectClass extends SchemaItem { $this->description = $this->description . " " . $strings[$i]; } } - while (!preg_match('/\'$/s', $strings[$i])); + while (!str_ends_with($strings[$i], '\'')); break; case 'OBSOLETE': $this->is_obsolete = TRUE; @@ -175,14 +175,14 @@ class ObjectClass extends SchemaItem { case 'SUP': if ($strings[$i + 1] != "(") { $i++; - array_push($this->sup_classes, preg_replace("/'/", "", $strings[$i])); + $this->sup_classes[] = preg_replace("/'/", "", $strings[$i]); } else { $i++; do { $i++; if ($strings[$i] != "$") { - array_push($this->sup_classes, preg_replace("/'/", "", $strings[$i])); + $this->sup_classes[] = preg_replace("/'/", "", $strings[$i]); } } while (!preg_match('/\)+\)?/', $strings[$i + 1])); @@ -201,12 +201,12 @@ class ObjectClass extends SchemaItem { if (preg_match('/^\(./', $strings[$i + 1])) { $i++; $attr = new ObjectClassAttribute(preg_replace('/^\(/', "", $strings[$i]), $this->name); - array_push($this->must_attrs, $attr); + $this->must_attrs[] = $attr; do { $i++; if ($strings[$i] != "$") { $attr = new ObjectClassAttribute($strings[$i], $this->name); - array_push($this->must_attrs, $attr); + $this->must_attrs[] = $attr; } } while (!preg_match('/\)+\)?/', $strings[$i + 1])); @@ -214,7 +214,7 @@ class ObjectClass extends SchemaItem { elseif ($strings[$i + 1] != "(") { $i++; $attr = new ObjectClassAttribute($strings[$i], $this->name); - array_push($this->must_attrs, $attr); + $this->must_attrs[] = $attr; } else { $i++; @@ -222,7 +222,7 @@ class ObjectClass extends SchemaItem { $i++; if ($strings[$i] != "$") { $attr = new ObjectClassAttribute($strings[$i], $this->name); - array_push($this->must_attrs, $attr); + $this->must_attrs[] = $attr; } } while (!preg_match('/\)+\)?/', $strings[$i + 1])); @@ -233,12 +233,12 @@ class ObjectClass extends SchemaItem { if (preg_match('/^\(./', $strings[$i + 1])) { $i++; $attr = new ObjectClassAttribute(preg_replace('/^\(/', "", $strings[$i]), $this->name); - array_push($this->may_attrs, $attr); + $this->may_attrs[] = $attr; do { $i++; if ($strings[$i] != "$") { $attr = new ObjectClassAttribute($strings[$i], $this->name); - array_push($this->may_attrs, $attr); + $this->may_attrs[] = $attr; } } while (!preg_match('/\)+\)?/', $strings[$i + 1])); @@ -246,7 +246,7 @@ class ObjectClass extends SchemaItem { elseif ($strings[$i + 1] != "(") { $i++; $attr = new ObjectClassAttribute($strings[$i], $this->name); - array_push($this->may_attrs, $attr); + $this->may_attrs[] = $attr; } else { $i++; @@ -254,7 +254,7 @@ class ObjectClass extends SchemaItem { $i++; if ($strings[$i] != "$") { $attr = new ObjectClassAttribute($strings[$i], $this->name); - array_push($this->may_attrs, $attr); + $this->may_attrs[] = $attr; } } while (!preg_match('/\)+\)?/', $strings[$i + 1])); @@ -487,9 +487,9 @@ class ObjectClass extends SchemaItem { */ class ObjectClassAttribute { /** This Attribute's name */ - var $name; + protected $name; /** This Attribute's root */ - var $source; + protected $source; /** * Creates a new ObjectClassAttribute with specified name and source objectClass. @@ -521,39 +521,39 @@ class ObjectClassAttribute { */ class AttributeType extends SchemaItem { /** The name of this attributeType */ - var $name; + protected $name; /** string: the description */ - var $is_obsolete; + protected $is_obsolete; /** The attribute from which this attribute inherits (if any) */ - var $sup_attribute; + protected $sup_attribute; /** The equality rule used */ - var $equality; + protected $equality; /** The ordering of the attributeType */ - var $ordering; + protected $ordering; /** Boolean: supports substring matching? */ - var $sub_str; + protected $sub_str; /** The full syntax string, ie 1.2.3.4{16} */ - var $syntax; + protected $syntax; /** syntax OID */ - var $syntax_oid; + protected $syntax_oid; /** boolean: is single valued only? */ - var $is_single_value; + protected $is_single_value; /** boolean: is collective? */ - var $is_collective; + protected $is_collective; /** boolean: can use modify? */ - var $is_no_user_modification; + protected $is_no_user_modification; /** The usage string set by the LDAP schema */ - var $usage; + protected $usage; /** An array of alias attribute names, strings */ - var $aliases; + protected $aliases; /** The max number of characters this attribute can be */ - var $max_length; + protected $max_length; /** A string description of the syntax type (taken from the LDAPSyntaxes) */ - var $type; + protected $type; /** An array of objectClasses which use this attributeType (must be set by caller) */ - var $used_in_object_classes; + protected $used_in_object_classes; /** A list of object class names that require this attribute type. */ - var $required_by_object_classes = []; + protected $required_by_object_classes = []; /** * Initialize the class' member variables @@ -603,7 +603,7 @@ class AttributeType extends SchemaItem { $this->name .= " " . $strings[$i]; } } - while (!preg_match("/\'$/s", $strings[$i])); + while (!preg_match("/\'$/", $strings[$i])); // this attribute has no aliases $this->aliases = []; } @@ -618,7 +618,7 @@ class AttributeType extends SchemaItem { $this->name .= " " . $strings[$i]; } } - while (!preg_match("/\'$/s", $strings[$i])); + while (!preg_match("/\'$/", $strings[$i])); // add alias names for this attribute while ($strings[++$i] != ")") { $alias = $strings[$i]; @@ -638,7 +638,7 @@ class AttributeType extends SchemaItem { $this->description = $this->description . " " . $strings[$i]; } } - while (!preg_match("/\'$/s", $strings[$i])); + while (!preg_match("/\'$/", $strings[$i])); break; case 'OBSOLETE': $this->is_obsolete = TRUE; @@ -1027,7 +1027,7 @@ class Syntax extends SchemaItem { $this->description = $this->description . " " . $strings[$i]; } } - while (!preg_match("/\'$/s", $strings[$i])); + while (!preg_match("/\'$/", $strings[$i])); break; default: if (preg_match("/[\d\.]+/i", $strings[$i]) && $i == 1) { @@ -1047,13 +1047,13 @@ class Syntax extends SchemaItem { */ class MatchingRule extends SchemaItem { /** This rule's name */ - var $name; + protected $name; /** This rule's syntax OID */ - var $syntax; + protected $syntax; /** Boolean value indicating whether this MatchingRule is obsolete */ - var $is_obsolete; + protected $is_obsolete; /** An array of attribute names who use this MatchingRule */ - var $used_by_attrs; + protected $used_by_attrs; /** Initialize the class' member variables */ function initVars() { @@ -1087,7 +1087,7 @@ class MatchingRule extends SchemaItem { $this->name .= " " . $strings[$i]; } } - while (!preg_match("/\'$/s", $strings[$i])); + while (!preg_match("/\'$/", $strings[$i])); } else { $i++; @@ -1100,7 +1100,7 @@ class MatchingRule extends SchemaItem { $this->name .= " " . $strings[$i]; } } - while (!preg_match("/\'$/s", $strings[$i])); + while (!preg_match("/\'$/", $strings[$i])); do { $i++; } @@ -1119,7 +1119,7 @@ class MatchingRule extends SchemaItem { $this->description = $this->description . " " . $strings[$i]; } } - while (!preg_match("/\'$/s", $strings[$i])); + while (!preg_match("/\'$/", $strings[$i])); break; case 'OBSOLETE': $this->is_obsolete = TRUE; @@ -1190,10 +1190,10 @@ class MatchingRule extends SchemaItem { */ class MatchingRuleUse extends SchemaItem { /** The name of the MathingRule this applies to */ - var $name; + protected $name; /** An array of attributeType names who make use of the mathingRule * identified by $this->oid and $this->name */ - var $used_by_attrs; + protected $used_by_attrs; /** Initialize the class' member variables */ function initVars() { @@ -1221,7 +1221,7 @@ class MatchingRuleUse extends SchemaItem { $this->name .= " " . $strings[$i]; } } - while (!preg_match("/\'$/s", $strings[$i])); + while (!preg_match("/\'$/", $strings[$i])); } else { $i++; @@ -1234,7 +1234,7 @@ class MatchingRuleUse extends SchemaItem { $this->name .= " " . $strings[$i]; } } - while (!preg_match("/\'$/s", $strings[$i])); + while (!preg_match("/\'$/", $strings[$i])); do { $i++; } @@ -1342,7 +1342,7 @@ function _get_schema_dn($dn, $debug = false) { return false; } - $entry = isset($entries[0]) ? $entries[0] : false; + $entry = $entries[0] ?? false; if (!$entry) { if ($debug) { echo "_get_schema_dn() returning false (entry val is false)\n"; @@ -1350,7 +1350,7 @@ function _get_schema_dn($dn, $debug = false) { return false; } - $sub_schema_sub_entry = isset($entry[0]) ? $entry[0] : false; + $sub_schema_sub_entry = $entry[0] ?? false; if (!$sub_schema_sub_entry) { if ($debug) { echo "_get_schema_dn() returning false (sub_schema_sub_entry val is false)\n"; @@ -1358,9 +1358,7 @@ function _get_schema_dn($dn, $debug = false) { return false; } - $schema_dn = isset($entry[$sub_schema_sub_entry][0]) ? - $entry[$sub_schema_sub_entry][0] : - false; + $schema_dn = $entry[$sub_schema_sub_entry][0] ?? false; if ($debug) { echo "_get_schema_dn() returning: \"" . $schema_dn . "\"\n"; @@ -1385,7 +1383,7 @@ function _get_schema_dn($dn, $debug = false) { * this will try to retrieve the schema from the RootDSE subschemaSubentry. * Failing that, we use some commonly known schema DNs. Default * value is the Root DSE DN (zero-length string) - * @return an array of strings of this form: + * @return array an array of strings of this form: * Array ( * [0] => "( 1.3.6.1.4.1.7165.1.2.2.4 NAME 'gidPool' DESC 'Pool ... * [1] => "( 1.3.6.1.4.1.7165.2.2.3 NAME 'sambaAccount' DESC 'Sa ... @@ -1513,9 +1511,7 @@ function _get_raw_schema($schema_to_fetch, $dn = '') { if ($schema_search == null) { // try again, with a different schema DN global $servers; - $base_dn = isset($servers['base']) ? - $servers['base'] : - null; + $base_dn = $servers['base'] ?? null; if ($debug) { echo "Attempting with cn=schema,cn=configuration,$base_dn (ActiveDirectory)...\n"; } @@ -1532,9 +1528,7 @@ function _get_raw_schema($schema_to_fetch, $dn = '') { if ($schema_search == null) { // try again, with a different schema DN global $servers; - $base_dn = isset($servers['base']) ? - $servers['base'] : - null; + $base_dn = $servers['base'] ?? null; if ($debug) { echo "Attempting with cn=Schema,ou=Admin,$base_dn (ActiveDirectory)...\n"; } @@ -1599,7 +1593,7 @@ function _get_raw_schema($schema_to_fetch, $dn = '') { } $schema = @ldap_get_entries($ds, $schema_search); - if ($schema == false) { + if ($schema === false) { if ($debug) { echo "Returning false since ldap_get_entries() returned false.\n"; } @@ -1650,7 +1644,7 @@ function _get_raw_schema($schema_to_fetch, $dn = '') { */ function get_schema_objectclasses($dn = null, $use_cache = true): array { if ($use_cache && cached_schema_available('objectclasses')) { - // return get_cached_schema('objectclasses' ); + return get_cached_schema('objectclasses' ); } $raw_oclasses = _get_raw_schema('objectclasses', $dn); @@ -1695,12 +1689,7 @@ function get_schema_objectclass($oclass_name, $dn = null, $use_cache = true) { if (!$oclasses) { return false; } - if (isset($oclasses[$oclass_name])) { - return $oclasses[$oclass_name]; - } - else { - return false; - } + return $oclasses[$oclass_name] ?? false; } /** @@ -1719,7 +1708,7 @@ function get_schema_attribute($attr_name, $dn = null, $use_cache = true) { $attr_name = real_attr_name($attr_name); $schema_attrs = get_schema_attributes($dn, $use_cache); $attr_name = strtolower($attr_name); - return isset($schema_attrs[$attr_name]) ? $schema_attrs[$attr_name] : false; + return $schema_attrs[$attr_name] ?? false; } /** @@ -1800,9 +1789,6 @@ function get_schema_attributes($dn = null, $use_cache = true): array { $attrs[strtolower($attr_name)]->addUsedInObjectClass( $object_class->getName()); } - else { - //echo "Warning, attr not set: $attr_name
"; - } } // Add Required By. @@ -1811,9 +1797,6 @@ function get_schema_attributes($dn = null, $use_cache = true): array { $attrs[strtolower($attr_name)]->addRequiredByObjectClass( $object_class->getName()); } - else { - //echo "Warning, attr not set: $attr_name
"; - } } } @@ -1953,7 +1936,7 @@ function add_sup_to_attrs(&$attrs, &$attrs_oid) { } // only overwrite the SINGLE-VALUE property if the child explicitly sets it // (note: All LDAP attributes default to multi-value if not explicitly set SINGLE-VALUE) - if (true == $tmp_single_val) { + if (true === $tmp_single_val) { $attr->setIsSingleValue(true); } @@ -2018,7 +2001,7 @@ function get_schema_matching_rules($dn = null, $use_cache = true) { // For each MatchingRuleUse entry, add the attributes who use it to the // MatchingRule in the $rules array. $raw_matching_rule_use = _get_raw_schema('matchingRuleUse'); - if ($raw_matching_rule_use != false) { + if ($raw_matching_rule_use !== false) { foreach ($raw_matching_rule_use as $rule_use_string) { if ($rule_use_string == null || 0 == strlen($rule_use_string)) { continue; @@ -2114,12 +2097,7 @@ function cached_schema_available($schema_type) { $cache_avail[$schema_type] = true; return true; } - elseif (isset($_SESSION['schema']['unavailable'])) { - return true; - } - else { - return false; - } + return false; } /** @@ -2193,5 +2171,3 @@ function set_schema_cache_unavailable() { $_SESSION['schema']['unavailable'] = true; return true; } - -?> diff --git a/lam/lib/security.inc b/lam/lib/security.inc index 2e9ab1d45..00381cf00 100644 --- a/lam/lib/security.inc +++ b/lam/lib/security.inc @@ -152,17 +152,12 @@ function isFileBasedSession(): bool { * The script is stopped if the host is not valid. */ function checkClientIP() { - if (isset($_SESSION['cfgMain'])) { - $cfg = $_SESSION['cfgMain']; - } - else { - $cfg = new LAMCfgMain(); - } + $cfg = $_SESSION['cfgMain'] ?? new LAMCfgMain(); $allowedHosts = $cfg->allowedHosts; $url = getCallingURL(); if (($url !== null) && - ((strpos($url, '/selfService/selfService') !== false) - || ((strpos($url, '/misc/ajax.php?') !== false) && strpos($url, 'selfservice=1') !== false))) { + ((str_contains($url, '/selfService/selfService')) + || ((str_contains($url, '/misc/ajax.php?')) && str_contains($url, 'selfservice=1')))) { // self service pages have separate IP list $allowedHosts = $cfg->allowedHostsSelfService; } @@ -197,7 +192,7 @@ function checkClientIP() { * Logs off the user and displays the login page. * */ -function logoffAndBackToLoginPage() { +function logoffAndBackToLoginPage(): void { // log message if (isset($_SESSION['ldap'])) { $ldapUser = $_SESSION['ldap']->getUserName(); @@ -205,7 +200,7 @@ function logoffAndBackToLoginPage() { // close LDAP connection @$_SESSION["ldap"]->destroy(); } - elseif (isset($_SESSION['selfService_clientDN']) || (strpos($_SERVER['REQUEST_URI'], '/selfService/') !== false)) { + elseif (isset($_SESSION['selfService_clientDN']) || (str_contains($_SERVER['REQUEST_URI'], '/selfService/'))) { logNewMessage(LOG_WARNING, 'Self service session of DN ' . lamDecrypt($_SESSION['selfService_clientDN'], 'SelfService') . ' expired.'); } // delete key and iv in cookie @@ -217,7 +212,7 @@ function logoffAndBackToLoginPage() { $paths = ['./', '../', '../../', '../../../', '../../../../']; $page = 'login.php'; $pageSuffix = '?expired=yes'; - if (isset($_SESSION['selfService_clientDN']) || (strpos($_SERVER['REQUEST_URI'], '/selfService/') !== false)) { + if (isset($_SESSION['selfService_clientDN']) || (str_contains($_SERVER['REQUEST_URI'], '/selfService/'))) { $scope = $_GET['scope']; $name = $_GET['name']; if (!preg_match('/^[0-9a-zA-Z _-]+$/', $scope) || !preg_match('/^[0-9a-zA-Z _-]+$/', $name)) { @@ -260,12 +255,7 @@ function logoffAndBackToLoginPage() { * @return boolean debug enabled */ function isDebugLoggingEnabled() { - if (isset($_SESSION['cfgMain'])) { - $cfg = $_SESSION['cfgMain']; - } - else { - $cfg = new LAMCfgMain(); - } + $cfg = $_SESSION['cfgMain'] ?? new LAMCfgMain(); return $cfg->logLevel >= LOG_DEBUG; } @@ -306,7 +296,7 @@ function logNewMessage($level, $message): void { syslog($level, $message); } // remote logging - elseif (strpos($cfg->logDestination, 'REMOTE') === 0) { + elseif (str_starts_with($cfg->logDestination, 'REMOTE')) { lamLogRemoteMessage($level, $message, $cfg); } // log to file @@ -421,12 +411,7 @@ function checkPasswordStrength($password, $userNames, $otherUserAttrs) { if ($password == null) { $password = ""; } - if (isset($_SESSION['cfgMain'])) { - $cfg = $_SESSION['cfgMain']; - } - else { - $cfg = new LAMCfgMain(); - } + $cfg = $_SESSION['cfgMain'] ?? new LAMCfgMain(); // check length $minLength = $cfg->passwordMinLength; if (isset($_SESSION['config']) && is_numeric($_SESSION['config']->getPwdPolicyMinLength())) { @@ -516,7 +501,7 @@ function checkPasswordStrength($password, $userNames, $otherUserAttrs) { if (($cfg->passwordMustNotContainUser == 'true') && !empty($userNames)) { foreach ($userNames as $userName) { $userLow = strtolower($userName); - if (strpos($pwdLow, $userLow) !== false) { + if (str_contains($pwdLow, $userLow)) { return _('The password is too weak. You may not use the user name as part of the password.'); } } @@ -529,7 +514,7 @@ function checkPasswordStrength($password, $userNames, $otherUserAttrs) { $userLow = strtolower($userName); for ($i = 0; $i < strlen($userLow) - 3; $i++) { $part = substr($userLow, 0, 3); - if (strpos($pwdLow, $part) !== false) { + if (str_contains($pwdLow, $part)) { return _('The password is too weak. You may not use parts of the user name for the password.'); } } @@ -542,7 +527,7 @@ function checkPasswordStrength($password, $userNames, $otherUserAttrs) { $low = strtolower($other); for ($i = 0; $i < strlen($low) - 3; $i++) { $part = substr($low, 0, 3); - if (strpos($pwdLow, $part) !== false) { + if (str_contains($pwdLow, $part)) { return _('The password is too weak. You may not use parts of user attributes for the password.'); } } @@ -682,7 +667,7 @@ function validateSecurityToken() { function addSecurityTokenToMetaHTML(&$container) { $token = new htmlHiddenInput(getSecurityTokenName(), $_SESSION[getSecurityTokenName()]); if ($container instanceof htmlResponsiveRow) { - $container->add($token, 12); + $container->add($token); return; } $container->addElement($token, true); @@ -811,7 +796,7 @@ function lamLogRemoteMessage($level, $message, $cfgMain) { */ class LamTemporaryFilesManager { - const SESSION_KEY = 'sec_registered_tmp_files'; + private const SESSION_KEY = 'sec_registered_tmp_files'; /** * Creates a temporary file and registers it for the current session. diff --git a/lam/lib/selfService.inc b/lam/lib/selfService.inc index e09cca1f4..c6abab651 100644 --- a/lam/lib/selfService.inc +++ b/lam/lib/selfService.inc @@ -1,6 +1,6 @@ strategy = new SelfServicePersistenceStrategyPdo($configDb->getPdo()); } catch (PDOException $e) { - logNewMessage(LOG_ERR, _('Unable to connect to configuration database.'), $e->getMessage()); + logNewMessage(LOG_ERR, _('Unable to connect to configuration database.') . ' ' . $e->getMessage()); throw new LAMException(_('Unable to connect to configuration database.')); } } @@ -502,9 +502,6 @@ class SelfServicePersistenceStrategyFileSystem implements SelfServicePersistence if (!preg_match("/^[0-9a-z _-]+$/i", $scope) || !preg_match("/^[0-9a-z _-]+$/i", $name)) { throw new LAMException(_("Profile name is invalid!")); } - if (!get_class($profile) === 'selfServiceProfile') { - throw new LAMException('Invalid data'); - } $path = __DIR__ . "/../config/selfService/" . $name . "." . $scope; $file = @fopen($path, "w"); if ($file) { @@ -550,7 +547,7 @@ class SelfServicePersistenceStrategyPdo implements SelfServicePersistenceStrateg */ private $pdo; - const TABLE_NAME = 'self_service_profiles'; + private const TABLE_NAME = 'self_service_profiles'; /** * Constructor @@ -815,10 +812,8 @@ class selfServiceProfile { /** * Constructor - * - * @return selfServiceProfile */ - function __construct() { + public function __construct() { // set default values $this->serverURL = "localhost"; $this->useTLS = false; @@ -908,6 +903,7 @@ class selfServiceProfile { if (preg_match('/^(http(s)?:\\/\\/[^\\/]+)\\/.+$/', $callingUrl, $matches)) { return $matches[1]; } + return ''; } /** @@ -917,7 +913,7 @@ class selfServiceProfile { */ public function setBaseUrl($url) { $this->baseUrl = $url; - if (!empty($url) && (substr($url, -1, 1) === '/')) { + if (!empty($url) && (str_ends_with($url, '/'))) { $this->baseUrl = substr($url, 0, -1); } } diff --git a/lam/lib/treeview.inc b/lam/lib/treeview.inc index 88ff9520f..990b2e2e7 100644 --- a/lam/lib/treeview.inc +++ b/lam/lib/treeview.inc @@ -5,7 +5,6 @@ namespace LAM\TOOLS\TREEVIEW; use htmlButton; use htmlDiv; use htmlElement; -use htmlForm; use htmlGroup; use htmlHiddenInput; use htmlImage; @@ -382,7 +381,7 @@ class TreeView { $highlighted = (empty($_POST['highlight'])) ? [] : explode(',', $_POST['highlight']); foreach ($attributes as $attributeName => $values) { $schemaAttribute = null; - if (strpos($attributeName, ';binary') !== false) { + if (str_contains($attributeName, ';binary')) { $attributeName = substr($attributeName, 0, -1 * strlen(';binary')); } if (isset($schemaAttributes[$attributeName])) { @@ -454,7 +453,7 @@ class TreeView { $internalAttributesContent = new htmlResponsiveRow(); $internalAttributesContent->add(new htmlSubTitle(_('Internal attributes'))); - $internalAttributesButton = new htmlLink(_('Show internal attributes'), '#', null, true); + $internalAttributesButton = new htmlLink(_('Show internal attributes'), '#', null); $internalAttributesButton->setOnClick('window.lam.treeview.getInternalAttributesContent(event, "' . getSecurityTokenName() . '", "' . getSecurityTokenValue() . '", @@ -890,7 +889,7 @@ class TreeView { */ private function getInternalAttributesContent(string $dn): string { $row = new htmlResponsiveRow(); - $row->add(new htmlSubTitle(_('Internal attributes')), 12); + $row->add(new htmlSubTitle(_('Internal attributes'))); $attributes = ldapGetDN($dn, ['+', 'creatorsName', 'createTimestamp', 'modifiersName', 'modifyTimestamp', 'hasSubordinates', 'pwdChangedTime', 'passwordRetryCount', 'accountUnlockTime', 'nsAccountLock', 'nsRoleDN', 'passwordExpirationTime']); @@ -917,13 +916,13 @@ class TreeView { $schemaAttributes = $this->getSchemaAttributes(); $attributes = ldapGetDN($dn, ['*']); unset($attributes['dn']); - $attributes = array_change_key_case($attributes, CASE_LOWER); + $attributes = array_change_key_case($attributes); $changes = json_decode($_POST['changes'], true); - $changes = array_change_key_case($changes, CASE_LOWER); + $changes = array_change_key_case($changes); logNewMessage(LOG_DEBUG, 'LDAP changes for ' . $dn . ': ' . print_r($changes, true)); $ldapChanges = []; foreach ($changes as $attrName => $change) { - $schemaAttribute = isset($schemaAttributes[$attrName]) ? $schemaAttributes[$attrName] : null; + $schemaAttribute = $schemaAttributes[$attrName] ?? null; if (isset($change['new'])) { $newValues = $change['new']; if (isset($change['hash'])) { @@ -968,7 +967,7 @@ class TreeView { // rename DN if RDN attribute changed $rdnAttribute = strtolower(extractRDNAttribute($dn)); $rdnValue = extractRDNValue($dn); - if (isset($ldapChanges[$rdnAttribute]) && isset($ldapChanges[$rdnAttribute][0]) && !in_array($rdnValue, $ldapChanges[$rdnAttribute])) { + if (isset($ldapChanges[$rdnAttribute][0]) && !in_array($rdnValue, $ldapChanges[$rdnAttribute])) { $pos = 0; $oldPos = array_search($rdnValue, $changes[$rdnAttribute]['old']); if (($oldPos !== false) && isset($ldapChanges[$rdnAttribute][$oldPos])) { @@ -1040,7 +1039,7 @@ class TreeView { } $schemaAttribute = $schemaAttributes[$attributeName]; if ($schemaAttribute->isBinary() - && (strpos($attributeName, ';binary') === false) + && (!str_contains($attributeName, ';binary')) && ($schemaAttribute->getSyntaxOID() === '1.3.6.1.4.1.1466.115.121.1.8')) { $ldapChanges[$attributeName . ';binary'] = $value; unset($ldapChanges[$attributeName]); @@ -1106,6 +1105,7 @@ class TreeView { return $this->createNewNodeCheckAttributesStep($dn); } logNewMessage(LOG_ERR, 'Invalid create new node step: ' . $step); + return ''; } /** @@ -1138,7 +1138,7 @@ class TreeView { $objectClassSelect->setHasDescriptiveElements(true); $objectClassSelect->setMultiSelect(true); $objectClassSelect->setOptionCssClasses($selectCssClasses); - $row->add($objectClassSelect, 12); + $row->add($objectClassSelect); $row->addVerticalSpacer('0.5rem'); $filterGroup = new htmlGroup(); $filterGroup->addElement(new htmlOutputText(_('Filter') . ' ')); @@ -1153,8 +1153,8 @@ class TreeView { $nextButton->setOnClick('window.lam.treeview.createNodeSelectObjectClassesStep(event, \'' . getSecurityTokenName() . '\', \'' . getSecurityTokenValue() . '\');'); $row->add($nextButton, 12, 12, 12, 'text-center'); $row->addVerticalSpacer('2rem'); - $row->add(new htmlOutputText(_('Hint: You must choose exactly one structural object class (shown in bold above)')), 12); - $row->add(new htmlHiddenInput('parentDn', base64_encode($dn)), 12); + $row->add(new htmlOutputText(_('Hint: You must choose exactly one structural object class (shown in bold above)'))); + $row->add(new htmlHiddenInput('parentDn', base64_encode($dn))); ob_start(); parseHtml(null, $row, [], false, ''); $content = ob_get_contents(); @@ -1391,7 +1391,7 @@ class TreeView { $rootDns = TreeViewTool::getRootDns(); foreach ($rootDns as $rootDn) { $rootDn = strtolower($rootDn); - if (substr($dn, -1 * strlen($rootDn)) === $rootDn) { + if (str_ends_with($dn, $rootDn)) { return; } } @@ -1420,7 +1420,7 @@ class TreeView { */ private function getSchemaAttributes(): array { if ($this->schemaAttributes === null) { - $this->schemaAttributes = get_schema_attributes(null); + $this->schemaAttributes = get_schema_attributes(); } return $this->schemaAttributes; } @@ -1519,15 +1519,10 @@ class TreeView { global $lamOrderByAttribute; $lamOrderByAttribute = empty($_POST['orderBy']) ? 'dn' : strtolower($_POST['orderBy']); $limit = empty($_POST['limit']) ? 0 : intval($_POST['limit']); - $results = []; - switch ($scope) { - case 'sub': - $results = searchLDAP($dn, $filter, $searchAttributes, $limit); - break; - case 'one': - $results = ldapListDN($dn, $filter, $searchAttributes, null, $limit); - break; - } + $results = match ($scope) { + 'sub' => searchLDAP($dn, $filter, $searchAttributes, $limit), + default => ldapListDN($dn, $filter, $searchAttributes, null, $limit), + }; usort($results, 'LAM\TOOLS\TREEVIEW\compareByAttributes'); $row = $this->searchResultsHeader($dn, $filter); if ($format === 'list') { @@ -1568,7 +1563,7 @@ class TreeView { $row->add(new htmlSubTitle(getAbstractDN($result['dn']), $this->getNodeIcon($result))); $row->addLabel(new htmlOutputText('dn')); $row->addField(new htmlLink(unescapeLdapSpecialCharacters($result['dn']), 'treeView.php?dn=' . base64_encode($result['dn']))); - $result = array_change_key_case($result, CASE_LOWER); + $result = array_change_key_case($result); foreach ($attributes as $attribute) { $attributeLower = strtolower($attribute); if (!empty($result[$attributeLower])) { @@ -1598,7 +1593,7 @@ class TreeView { $data = []; foreach ($results as $result) { $dataEntry = [$this->getNodeIcon($result), new htmlLink(unescapeLdapSpecialCharacters($result['dn']), 'treeView.php?dn=' . base64_encode($result['dn']))]; - $result = array_change_key_case($result, CASE_LOWER); + $result = array_change_key_case($result); foreach ($attributes as $attribute) { $attributeLower = strtolower($attribute); if (!empty($result[$attributeLower])) { @@ -1652,7 +1647,7 @@ class TreeView { if (!empty($errors)) { $row = new htmlResponsiveRow(); foreach ($errors as $error) { - $row->add(new htmlStatusMessage($error[0], $error[1], isset($error[2]) ? $error[2] : null)); + $row->add(new htmlStatusMessage($error[0], $error[1], $error[2] ?? null)); } ob_start(); parseHtml(null, $row, [], false, ''); @@ -1698,8 +1693,8 @@ function compareByAttributes($a, $b): int { if ($lamOrderByAttribute === 'dn') { return compareDN($a['dn'], $b['dn']); } - $a = array_change_key_case($a, CASE_LOWER); - $b = array_change_key_case($b, CASE_LOWER); + $a = array_change_key_case($a); + $b = array_change_key_case($b); if (!isset($a[$lamOrderByAttribute]) && !isset($b[$lamOrderByAttribute])) { return 0; } diff --git a/lam/lib/types.inc b/lam/lib/types.inc index f84a740d7..39063eed7 100644 --- a/lam/lib/types.inc +++ b/lam/lib/types.inc @@ -23,6 +23,7 @@ namespace LAM\TYPES; */ use baseType; +use LAMConfig; /** * This file is the interface to the different account types. @@ -46,7 +47,7 @@ $typesINC_dirname = substr(__FILE__, 0, strlen(__FILE__) - 10) . "/types"; $typesINC_dir = dir($typesINC_dirname); // get module names. while ($entry = $typesINC_dir->read()) { - if ((substr($entry, strlen($entry) - 4, 4) == '.inc') && is_file($typesINC_dirname . '/' . $entry)) { + if ((str_ends_with($entry, '.inc')) && is_file($typesINC_dirname . '/' . $entry)) { include_once($typesINC_dirname . '/' . $entry); } } @@ -55,15 +56,15 @@ while ($entry = $typesINC_dir->read()) { /** * Returns a list of available account types. * - * @return array list of types + * @return string[] list of types */ -function getTypes() { +function getTypes(): array { $dirname = substr(__FILE__, 0, strlen(__FILE__) - 10) . "/types"; $dir = dir($dirname); $return = []; // get type names. while ($entry = $dir->read()) { - if ((substr($entry, strlen($entry) - 4, 4) == '.inc') && is_file($dirname . '/' . $entry)) { + if ((str_ends_with($entry, '.inc')) && is_file($dirname . '/' . $entry)) { $entry = substr($entry, 0, strpos($entry, '.')); $return[] = $entry; } @@ -72,24 +73,13 @@ function getTypes() { return $return; } -/** - * Returns the description of an account type. - * - * @param string $type type name - * @return string type description - */ -function getTypeDescription($type) { - $obj = new $type(null); - return $obj->getDescription(); -} - /** * Returns the account type for a given type id. * * @param string $typeId type id (e.g. user_1) * @return string scope (e.g. user) */ -function getScopeFromTypeId($typeId) { +function getScopeFromTypeId(string $typeId): string { $parts = explode('_', $typeId); return $parts[0]; } @@ -203,9 +193,12 @@ class ConfiguredType { } $typeSettings = $this->typeManager->getConfig()->get_typeSettings(); if (!empty($typeSettings['customLabel_' . $this->id])) { - return $typeSettings['customLabel_' . $this->id]; + $this->alias = $typeSettings['customLabel_' . $this->id]; + } + else { + $this->alias = $this->getBaseType()->getAlias(); } - return $this->getBaseType()->getAlias(); + return $this->alias; } /** @@ -357,10 +350,7 @@ class ListAttribute { public function getAlias(array $predefinedDescriptions): string { if ($this->isPredefined()) { $name = strtolower(substr($this->attributeSpec, 1)); - if (isset($predefinedDescriptions[$name])) { - return $predefinedDescriptions[$name]; - } - return $name; + return $predefinedDescriptions[$name] ?? $name; } $parts = explode(':', $this->attributeSpec); return $parts[1]; @@ -372,7 +362,7 @@ class ListAttribute { * @return bool is predefined */ private function isPredefined(): bool { - return strpos($this->attributeSpec, '#') === 0; + return str_starts_with($this->attributeSpec, '#'); } } @@ -390,9 +380,9 @@ class TypeManager { /** * Constructor * - * @param \LAMConfig $config configuration (uses $_SESSION['config'] by default) + * @param LAMConfig|null $config configuration (uses $_SESSION['config'] by default) */ - public function __construct(&$config = null) { + public function __construct(LAMConfig &$config = null) { if ($config == null) { $config = &$_SESSION['config']; } @@ -413,9 +403,9 @@ class TypeManager { * Returns the configured type with the given id or null. * * @param string $typeId type id - * @return \LAM\TYPES\ConfiguredType|NULL type + * @return ConfiguredType|null type */ - public function getConfiguredType($typeId) { + public function getConfiguredType(string $typeId): ?ConfiguredType { if ($this->config == null) { return null; } @@ -429,9 +419,9 @@ class TypeManager { /** * Returns a list of configured account types. * - * @return \LAM\TYPES\ConfiguredType[] list of ConfiguredType + * @return ConfiguredType[] list of ConfiguredType */ - public function getConfiguredTypes() { + public function getConfiguredTypes(): array { $configuredTypes = []; $activeTypes = $this->config->get_ActiveTypes(); foreach ($activeTypes as $typeId) { @@ -448,9 +438,9 @@ class TypeManager { * Returns a list of configured types for this scope. * * @param string $scope scope (e.g. user) - * @return \LAM\TYPES\ConfiguredType[] list of ConfiguredType + * @return ConfiguredType[] list of ConfiguredType */ - public function getConfiguredTypesForScope($scope) { + public function getConfiguredTypesForScope(string $scope): array { $allTypes = $this->getConfiguredTypes(); $scopedTypes = []; foreach ($allTypes as $type) { @@ -465,9 +455,9 @@ class TypeManager { * Returns a list of configured types for these scopes. * * @param array $scopes scopes (e.g. user) - * @return \LAM\TYPES\ConfiguredType[] list of ConfiguredType + * @return ConfiguredType[] list of ConfiguredType */ - public function getConfiguredTypesForScopes($scopes) { + public function getConfiguredTypesForScopes(array $scopes): array { $allTypes = $this->getConfiguredTypes(); $scopedTypes = []; foreach ($allTypes as $type) { @@ -482,8 +472,9 @@ class TypeManager { * Builds a configured account type. * * @param string $typeId type id + * @return ConfiguredType|null type */ - private function buildConfiguredType($typeId) { + private function buildConfiguredType(string $typeId): ?ConfiguredType { $scope = getScopeFromTypeId($typeId); if (!class_exists($scope)) { return null; @@ -496,7 +487,7 @@ class TypeManager { * * @param string $scope account type (e.g. user) */ - public function generateNewTypeId($scope) { + public function generateNewTypeId(string $scope): string { $activeTypes = $this->config->get_ActiveTypes(); if (!in_array($scope, $activeTypes)) { return $scope; @@ -511,9 +502,9 @@ class TypeManager { /** * Returns the associated config object. * - * @return \LAMConfig config + * @return LAMConfig|null config */ - public function getConfig() { + public function getConfig(): ?LAMConfig { return $this->config; } @@ -522,7 +513,7 @@ class TypeManager { * * @return boolean configured */ - public function hasConfig() { + public function hasConfig(): bool { return !empty($this->config); } diff --git a/phpstan.neon b/phpstan.neon index c276e0bd3..970f5a3fe 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -6,6 +6,8 @@ parameters: paths: - lam/lib - lam/templates + fileExtensions: + - php excludePaths: analyseAndScan: - */3rdParty/* @@ -39,3 +41,4 @@ parameters: - '#Parameter \#1 \$input of static method LAM\\AJAX\\Ajax::managePasswordChange\(\) expects array, mixed given.#' - '#Parameter \#1 \$input of method LAM\\AJAX\\Ajax::checkPasswordStrength\(\) expects array, mixed given.#' - '#Cannot access offset non-falsy-string on array\|object.#' + - '#Unable to resolve the template type T in call to function array_values#' diff --git a/rector.php b/rector.php index 2d4d135c9..2133b7e77 100644 --- a/rector.php +++ b/rector.php @@ -3,6 +3,7 @@ use Rector\Config\RectorConfig; use Rector\Php70\Rector\StaticCall\StaticCallOnNonStaticToInstanceCallRector; use Rector\Php73\Rector\FuncCall\StringifyStrNeedlesRector; +use Rector\Php74\Rector\Property\RestoreDefaultNullToNullableTypePropertyRector; use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector; use Rector\Php81\Rector\Property\ReadOnlyPropertyRector; use Rector\Set\ValueObject\LevelSetList; @@ -26,7 +27,8 @@ ReadOnlyPropertyRector::class, ClassPropertyAssignToConstructorPromotionRector::class, StaticCallOnNonStaticToInstanceCallRector::class, - StringifyStrNeedlesRector::class + StringifyStrNeedlesRector::class, + RestoreDefaultNullToNullableTypePropertyRector::class, ]) ->withFileExtensions([ 'php',