Merge pull request #393 from LDAPAccountManager/feature/267-rector-code-quality

Feature/267 rector code quality
This commit is contained in:
gruberroland 2024-12-29 13:51:57 +01:00 committed by GitHub
commit b12077c20c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
140 changed files with 3054 additions and 3487 deletions

View file

@ -42,9 +42,9 @@ if (isset($_SESSION['conf_config'])) {
$entry206Example .= "<b>" . $type->getAlias() . ":</b><br>\n";
$descriptions = $type->getBaseType()->getListAttributeDescriptions();
$attributes = array_keys($descriptions);
for ($a = 0; $a < sizeof($attributes); $a++) {
for ($a = 0; $a < count($attributes); $a++) {
$entry206Example .= "#" . $attributes[$a] . ": " . $descriptions[$attributes[$a]];
if ($a < (sizeof($attributes) - 1)) {
if ($a < (count($attributes) - 1)) {
$entry206Example .= ", ";
}
}

View file

@ -100,8 +100,7 @@ function natCaseKeySort(array $toSort): array {
*/
function getdays() {
$days = time() / 86400;
settype($days, 'integer');
return $days;
return (int) $days;
}
/**
@ -273,22 +272,19 @@ function pwd_enable($hash) {
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 (str_starts_with($hash, "{")) {
$pos = strpos($hash, "}");
if ((substr($hash, $pos + 1, 1) == "!") || (substr($hash, $pos + 1, 1) == "*")) {
// enable hash
return substr($hash, 0, $pos + 1) . substr($hash, $pos + 2, strlen($hash));
}
else {
return $hash; // not disabled
}
elseif (str_starts_with($hash, "{")) {
$pos = strpos($hash, "}");
if ((substr($hash, $pos + 1, 1) === "!") || (substr($hash, $pos + 1, 1) === "*")) {
// enable hash
return substr($hash, 0, $pos + 1) . substr($hash, $pos + 2, strlen($hash));
}
else {
return $hash; // password is plain text
return $hash; // not disabled
}
}
else {
return $hash; // password is plain text
}
}
/**
@ -302,22 +298,19 @@ function pwd_disable($hash) {
if ((str_starts_with($hash, "!{")) || (str_starts_with($hash, "*{"))) {
return $hash;
}
// check for "!" or "*" at beginning of password hash
else {
if (str_starts_with($hash, "{")) {
$pos = strpos($hash, "}");
if ((substr($hash, $pos + 1, 1) == "!") || (substr($hash, $pos + 1, 1) == "*")) {
// hash already disabled
return $hash;
}
else {
return substr($hash, 0, $pos + 1) . "!" . substr($hash, $pos + 1, strlen($hash)); // not disabled
}
elseif (str_starts_with($hash, "{")) {
$pos = strpos($hash, "}");
if ((substr($hash, $pos + 1, 1) === "!") || (substr($hash, $pos + 1, 1) === "*")) {
// hash already disabled
return $hash;
}
else {
return $hash; // password is plain text
return substr($hash, 0, $pos + 1) . "!" . substr($hash, $pos + 1, strlen($hash)); // not disabled
}
}
else {
return $hash; // password is plain text
}
}
/**
@ -335,7 +328,7 @@ function pwd_is_lockable($password) {
if (str_starts_with($password, '{SASL}')) {
return false;
}
return ((str_starts_with($password, "{")) || (substr($password, 1, 1) == "{")) && (strpos($password, "}") > 3);
return ((str_starts_with($password, "{")) || (substr($password, 1, 1) === "{")) && (strpos($password, "}") > 3);
}
/**
@ -428,18 +421,18 @@ function checkPasswordHash($type, $hash, $password) {
return (strcmp($hash, base64_encode(hex2bin(md5($password)))) == 0);
case 'CRYPT':
$parts = explode('$', $hash);
if (sizeof($parts) === 1) {
if (count($parts) === 1) {
$salt = substr($hash, 0, 2);
$pwdHash = crypt($password, $salt);
return (strcmp($hash, $pwdHash) == 0);
}
if (sizeof($parts) === 4) {
if (count($parts) === 4) {
$version = $parts[1];
$salt = $parts[2];
$pwdHash = crypt($password, '$' . $version . '$' . $salt);
return (strcmp($hash, $pwdHash) == 0);
}
elseif (sizeof($parts) === 5) {
elseif (count($parts) === 5) {
$version = $parts[1];
$rounds = $parts[2];
$salt = $parts[3];
@ -467,16 +460,16 @@ function getNumberOfCharacterClasses($password): int {
return 0;
}
$classesCount = 0;
if (preg_match("/[a-z]/", $password)) {
if (preg_match('/[a-z]/', $password)) {
$classesCount++;
}
if (preg_match("/[A-Z]/", $password)) {
if (preg_match('/[A-Z]/', $password)) {
$classesCount++;
}
if (preg_match("/[0-9]/", $password)) {
if (preg_match('/\d/', $password)) {
$classesCount++;
}
if (preg_match("/[^a-z0-9]/i", $password)) {
if (preg_match('/[^a-z0-9]/i', $password)) {
$classesCount++;
}
return $classesCount;
@ -504,7 +497,7 @@ function search_domains($server = null, $suffix = null) {
$filter = '(objectclass=sambaDomain)';
$units = searchLDAPPaged($server, $suffix, $filter, $attr, false, 0);
// extract attributes
for ($i = 0; $i < sizeof($units); $i++) {
for ($i = 0; $i < count($units); $i++) {
$ret[$i] = new samba3domain();
$ret[$i]->dn = $units[$i]['dn'];
$ret[$i]->name = $units[$i]['sambadomainname'][0];
@ -584,55 +577,55 @@ function get_preg($argument, $regexp) {
$pregexpr = '';
switch ($regexp) {
case 'password':
$pregexpr = '/^([[:alnum:]\\^\\ \\|\\#\\*\\,\\.\\;\\:\\_\\+\\!\\%\\&\\/\\?\\{\\(\\)\\}\\[\\]\\$§°@=-])*$/u';
$pregexpr = '/^([[:alnum:]^ |#*,.;:_+!%&\/?{()}\[\]$§°@=-])*$/u';
break;
case 'groupname': // all letters, numbers, space and ._- are allowed characters
case 'username':
case 'hostname':
$pregexpr = '/^([[:alnum:]%#@\\.\\ \\_\\$-])+$/u';
$pregexpr = '/^([[:alnum:]%#@. _$-])+$/u';
break;
case 'krbUserName':
$pregexpr = '/^([[:alnum:]#@\\/\\.\\ \\_\\$-])+$/u';
$pregexpr = '/^([[:alnum:]#@\/. _$-])+$/u';
break;
case 'hostObject':
$pregexpr = '/^[!]?([[:alnum:]@\\.\\ \\_\\$\\:*-])+$/u';
$pregexpr = '/^!?([[:alnum:]@. _$:*-])+$/u';
break;
case 'usernameList': // comma separated list of user names
case 'usernameList': // comma separated list of usernames
case 'groupnameList': // comma separated list of group names
$pregexpr = '/^([[:alnum:]%#@\\.\\ \\_-])+(,([[:alnum:]%#@\\.\\ \\_-])+)*$/u';
$pregexpr = '/^([[:alnum:]%#@. _-])+(,([[:alnum:]%#@. _-])+)*$/u';
break;
case 'realname': // Allow all but \, <, >, =, $, ?
case 'cn':
$pregexpr = '/^[^\\\<>=\\$\\?]+(\\$)?$/';
$pregexpr = '/^[^\\\\<>=$?]+(\$)?$/';
break;
case "telephone": // Allow letters, numbers, space, brackets, /-+.
$pregexpr = '/^(\\+)*([0-9a-zA-Z\\.\\ \\(\\)\\/-])*$/';
$pregexpr = '/^(\+)*([0-9a-zA-Z. ()\/-])*$/';
break;
case "email":
$pregexpr = '/^([0-9a-zA-Z\'!~#+*%\\$\\/\\._-])+[@]([0-9a-zA-Z-])+([.]([0-9a-zA-Z-])+)*$/';
$pregexpr = '/^([0-9a-zA-Z\'!~#+*%$\/._-])+[@]([0-9a-zA-Z-])+([.]([0-9a-zA-Z-])+)*$/';
break;
case "emailWithName":
$pregexpr = '/^([[:alnum:] \'!~#+*%\\$\\(\\)_-])+ <([0-9a-zA-Z\'!~#+*%\\$\\/\\._-])+[@]([0-9a-zA-Z-])+([.]([0-9a-zA-Z-])+)*>$/u';
$pregexpr = '/^([[:alnum:] \'!~#+*%$()_-])+ <([0-9a-zA-Z\'!~#+*%$\/._-])+[@]([0-9a-zA-Z-])+([.]([0-9a-zA-Z-])+)*>$/u';
break;
case "mailLocalAddress":
$pregexpr = '/^([0-9a-zA-Z+\\/\\._-])*([@]([0-9a-zA-Z-])+([.]([0-9a-zA-Z-])+)*)?$/';
$pregexpr = '/^([0-9a-zA-Z+\\/._-])*([@]([0-9a-zA-Z-])+([.]([0-9a-zA-Z-])+)*)?$/';
break;
case 'kolabEmailPrefix':
$pregexpr = '/^([-])?([0-9a-zA-Z+\\/\\._-])*([@]([0-9a-zA-Z\\.-])*)?$/';
$pregexpr = '/^([-])?([0-9a-zA-Z+\\/._-])*([@]([0-9a-zA-Z.-])*)?$/';
break;
case "postalAddress": // Allow all but \, <, >, =, ?
$pregexpr = '/^[^\\\<>=\\?]*$/';
$pregexpr = '/^[^\\\<>=?]*$/';
break;
case "postalCode": // Allow all but \, <, >, =, ?
case "street":
case "title":
case "employeeType":
case "businessCategory":
$pregexpr = '/^[^\\\<>=\\$\\?]*$/';
$pregexpr = '/^[^\\\<>=$?]*$/';
break;
case "homeDirectory": // Home path, /path/......
case "filePath":
$pregexpr = '/^([\/]([[:alnum:]@\\$\\.\\ \\_-])+)+(\/)?$/u';
$pregexpr = '/^([\/]([[:alnum:]@$. _-])+)+(\/)?$/u';
break;
case "digit": // Normal number
$pregexpr = '/^[[:digit:]]*$/';
@ -644,37 +637,34 @@ function get_preg($argument, $regexp) {
$pregexpr = '/^[[:digit:]]+(\\.[[:digit:]]+)?$/';
break;
case "UNC": // UNC Path, e.g. \\server\share\folder\...
$pregexpr = '/^((([\\\][\\\])|(%))([a-zA-Z0-9@%\\.-])+)([\\\]([[:alnum:]@%\\.\\$\\ \\_-])+)+$/u';
$pregexpr = '/^((([\\\][\\\])|(%))([a-zA-Z0-9@%.-])+)([\\\]([[:alnum:]@%.$ _-])+)+$/u';
break;
case "logonscript": // path to login-script. normal unix file
$pregexpr = '/^(([\/\\\])*([[:alnum:]%\\.\\ \\$\\_-])+([\/\\\]([[:alnum:]%\\.\\ \\$\\_-])+)*((\\.bat)|(\\.cmd)|(\\.exe)|(\\.vbs)))*$/u';
$pregexpr = '/^(([\/\\\])*([[:alnum:]%. $_-])+([\/\\\]([[:alnum:]%. $_-])+)*((\\.bat)|(\\.cmd)|(\\.exe)|(\\.vbs)))*$/u';
break;
case "workstations": // comma separated list with windows-hosts
$pregexpr = '/^(([a-zA-Z0-9\\.\\_-])+(,[a-zA-Z0-9\\.\\_-])*)*$/';
$pregexpr = '/^(([a-zA-Z0-9._-])+(,[a-zA-Z0-9._-])*)*$/';
break;
case "domainname": // Windows Domainname
$pregexpr = '/^([A-Za-z0-9\\.\\_-])+$/';
$pregexpr = '/^([A-Za-z0-9._-])+$/';
break;
case "unixhost": // Unix hosts
$pregexpr = '/^([a-z0-9,\\.\\*_-])*$/';
$pregexpr = '/^([a-z0-9,.*_-])*$/';
break;
case 'digit2': // Same as digit but also -1
$pregexpr = '/^(([-][1])|([[:digit:]]*))$/';
break;
case 'gecos':
$pregexpr = '/^[[:alnum:] \\._-]+([,][[:alnum:] \\._-]+)*$/u';
$pregexpr = '/^[[:alnum:] ._-]+([,][[:alnum:] ._-]+)*$/u';
break;
case 'macAddress':
$pregexpr = '/^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$/';
break;
case 'date': // 31-12-2012
$pregexpr = '/^((0?[1-9])|([1-2][0-9])|30|31)\\-((0?[1-9])|(1[0-2]))\\-[1-3][0-9][0-9][0-9]$/';
break;
case 'date2':
$pregexpr = '/^((0[1-9])|([1-2][0-9])|30|31)\\.((0[1-9])|(1[0-2]))\\.[1-3][0-9][0-9][0-9]$/';
$pregexpr = '/^((0?[1-9])|([1-2]\d)|30|31)-((0?[1-9])|(1[0-2]))-[1-3]\d\d\d$/';
break;
case 'dateTime':
$pregexpr = '/^[1-3][0-9][0-9][0-9]\\-((0[1-9])|(1[0-2]))\\-((0[1-9])|([1-2][0-9])|30|31) ((0[0-9])|([1][0-9])|20|21|22|23):((0[0-9])|([1-5][0-9])):((0[0-9])|([1-5][0-9]))$/';
$pregexpr = '/^[1-3]\d\d\d\-((0[1-9])|(1[0-2]))-((0[1-9])|([1-2]\d)|30|31) ((0\d)|([1]\d)|20|21|22|23):((0\d)|([1-5]\d)):((0\d)|([1-5]\d))$/';
break;
case 'sambaLogonHours':
$pregexpr = '/^[0-9a-fA-F]{42}$/';
@ -683,10 +673,10 @@ function get_preg($argument, $regexp) {
$pregexpr = '/^[0-9a-zA-Z_-]+(\\.[0-9a-zA-Z_-]+)*$/';
break;
case 'nis_alias':
$pregexpr = '/^([[:alnum:]@\\.\\ \\_-])+$/u';
$pregexpr = '/^([[:alnum:]@. _-])+$/u';
break;
case 'nis_recipient':
$pregexpr = '/^([[:alnum:]+@\\.\\ \\_-])+$/u';
$pregexpr = '/^([[:alnum:]+@. _-])+$/u';
break;
case 'country': // Allow all letters and space
$pregexpr = '/^[[:alpha:]]([[:alpha:] ])+$/u';
@ -695,10 +685,10 @@ function get_preg($argument, $regexp) {
$pregexpr = '/^([^=,]+=[^=,]+)(,([^=,]+=[^=,]+))*$/';
break;
case 'domainSID': // Samba domain SID
$pregexpr = "/^S\\-[0-9]\\-[0-9]\\-[0-9]{2,2}\\-[0-9]+\\-[0-9]+\\-[0-9]+$/";
$pregexpr = "/^S-\\d-\\d-\\d{2,2}-\\d+-\\d+-\\d+\$/";
break;
case 'ip': // IP address
$pregexpr = '/^[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}$/';
$pregexpr = '/^\d{1,3}[.]\d{1,3}[.]\d{1,3}[.]\d{1,3}$/';
break;
case 'ip6': // IPv6 address (only basic check)
$pregexpr = '/^[0-9a-f:]+$/i';
@ -713,16 +703,16 @@ function get_preg($argument, $regexp) {
$pregexpr = '/^[[:digit:]]+[KMGTkmgt]?$/';
break;
case 'hostAndPort':
$pregexpr = '/^[[:alnum:]\\._-]+:[[:digit:]]+$/';
$pregexpr = '/^[[:alnum:]._-]+:[[:digit:]]+$/';
break;
case 'ldapDateAndTime':
$pregexpr = '/^[0-9]{14}Z$/';
$pregexpr = '/^\d{14}Z$/';
break;
case 'guacamoleProtocol':
$pregexpr = '/^(rdp|vnc)$/';
break;
}
if (($pregexpr != '') && preg_match($pregexpr, $argument)) {
if (($pregexpr !== '') && preg_match($pregexpr, $argument)) {
return true;
}
// Now we check "negative" cases, characters which are not allowed
@ -738,10 +728,7 @@ function get_preg($argument, $regexp) {
$pregexpr = '/[[:digit:]]/';
break;
}
if (($pregexpr != '') && !preg_match($pregexpr, $argument)) {
return true;
}
return false;
return ($pregexpr !== '') && !preg_match($pregexpr, $argument);
}
/**
@ -809,10 +796,10 @@ function searchLDAPByAttribute($name, $value, $objectClass, $attributes, $scopes
if ($objectClass != null) {
$filterParts[] = '(objectClass=' . $objectClass . ')';
}
if (sizeof($filterParts) == 1) {
if (count($filterParts) == 1) {
$filter = $filterParts[0];
}
elseif (sizeof($filterParts) > 1) {
elseif (count($filterParts) > 1) {
$filter = '(& ' . implode(' ', $filterParts) . ')';
}
$typeManager = new TypeManager();
@ -882,7 +869,7 @@ function searchLDAPByFilter($filter, $attributes, $scopes, $attrsOnly = false) {
*/
function searchLDAP($suffix, $filter, $attributes, $limit = -1) {
if ($limit === -1) {
$limit = !empty($_SESSION['config']) ? $_SESSION['config']->get_searchLimit() : 0;
$limit = empty($_SESSION['config']) ? 0 : $_SESSION['config']->get_searchLimit();
}
$return = searchLDAPPaged(getLDAPServerHandle(), $suffix, $filter, $attributes,
0, $limit);
@ -1006,7 +993,7 @@ function ldapGetDN($dn, $attributes = ['dn'], $handle = null): ?array {
*/
function ldapListDN($dn, $filter = '(objectclass=*)', $attributes = ['dn'], $handle = null, $limit = -1) {
if ($limit === -1) {
$limit = !empty($_SESSION['config']) ? $_SESSION['config']->get_searchLimit() : 0;
$limit = empty($_SESSION['config']) ? 0 : $_SESSION['config']->get_searchLimit();
}
if ($handle == null) {
$handle = $_SESSION['ldap']->server();
@ -1042,10 +1029,10 @@ function deleteDN($dn, $recursive) {
if ($sr) {
$entries = ldap_get_entries($_SESSION['ldap']->server(), $sr);
cleanLDAPResult($entries);
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
// delete recursively
$subErrors = deleteDN($entries[$i]['dn'], $recursive);
for ($e = 0; $e < sizeof($subErrors); $e++) {
for ($e = 0; $e < count($subErrors); $e++) {
$errors[] = $subErrors[$e];
}
}
@ -1155,7 +1142,7 @@ function cleanLDAPResult(&$entries) {
unset($entries['count']);
}
// iterate over all results
$count = sizeof($entries);
$count = count($entries);
for ($e = 0; $e < $count; $e++) {
// remove 'count' entries and numerical entries
for ($i = 0; $i < $entries[$e]['count']; $i++) {
@ -1165,7 +1152,7 @@ function cleanLDAPResult(&$entries) {
}
unset($entries[$e]['count']);
$attrNames = array_keys($entries[$e]);
$attrCount = sizeof($attrNames);
$attrCount = count($attrNames);
for ($i = 0; $i < $attrCount; $i++) {
if (is_array($entries[$e][$attrNames[$i]])) {
unset($entries[$e][$attrNames[$i]]['count']);
@ -1191,9 +1178,9 @@ function getAbstractDN($dn) {
$dn = str_replace($partToCut, '', $dn);
}
$parts = explode(',', $dn);
for ($i = 0; $i < sizeof($parts); $i++) {
for ($i = 0; $i < count($parts); $i++) {
$subparts = explode('=', $parts[$i]);
if (sizeof($subparts) == 2) {
if (count($subparts) == 2) {
$parts[$i] = $subparts[1];
}
}
@ -1232,8 +1219,8 @@ function compareDN($a, $b): int {
// split DNs
$array_a = explode(",", strtolower($a));
$array_b = explode(",", strtolower($b));
$len_a = sizeof($array_a);
$len_b = sizeof($array_b);
$len_a = count($array_a);
$len_b = count($array_b);
// check how many parts to compare
$len = min($len_a, $len_b);
// compare from last part on
@ -1246,7 +1233,7 @@ function compareDN($a, $b): int {
$part_b = explode('=', $part_b);
$part_b = $part_b[1] ?? $part_b[0];
// compare parts
if ($part_a == $part_b) { // part is identical
if ($part_a === $part_b) { // part is identical
if ($i == ($len - 1)) {
return $len_a <=> $len_b;
}
@ -1432,7 +1419,7 @@ function extractDNSuffix($dn) {
}
unset($parts['count']);
array_shift($parts);
for ($i = 0; $i < sizeof($parts); $i++) {
for ($i = 0; $i < count($parts); $i++) {
$parts[$i] = unescapeLdapSpecialCharacters($parts[$i]);
$parts[$i] = str_replace(',', '\\2C', $parts[$i]);
}
@ -1476,7 +1463,7 @@ function testSmtpConnection(string $server, string $user, string $password, stri
$mailer->smtpConnect();
}
catch (Exception $e) {
throw new LAMException(null, $e->getMessage());
throw new LAMException(null, $e->getMessage(), $e);
}
}
@ -1519,12 +1506,7 @@ function sendPasswordMail($pwd, $user, $recipient = null) {
$attr = str_replace('@', '', $results[0]);
$value = '';
if (isset($user[strtolower($attr)][0])) {
if (is_array($user[strtolower($attr)])) {
$value = $user[strtolower($attr)][0];
}
else {
$value = $user[strtolower($attr)];
}
$value = is_array($user[strtolower($attr)]) ? $user[strtolower($attr)][0] : $user[strtolower($attr)];
}
$body = str_replace('@@' . $attr . '@@', $value, $body);
$found = preg_match('/\@\@[^\@]+\@\@/', $body, $results);
@ -1715,7 +1697,7 @@ function getLDAPSSLCertificate($server, $port) {
return false;
}
$finalPEM = '';
for ($i = 0; $i < sizeof($context['options']['ssl']['peer_certificate_chain']); $i++) {
for ($i = 0; $i < count($context['options']['ssl']['peer_certificate_chain']); $i++) {
$cert = $context['options']['ssl']['peer_certificate_chain'][$i];
$pemData = null;
$pemResult = @openssl_x509_export($cert, $pemData);
@ -1786,7 +1768,7 @@ function getDefaultLDAPErrorString($server) {
}
$genericErrorMessage = ldap_error($server);
$message = _('LDAP error, server says:') . ' ' . $genericErrorMessage;
if (!empty($extError) && ($genericErrorMessage != $extError)) {
if (!empty($extError) && ($genericErrorMessage !== $extError)) {
$message .= ' - ' . $extError;
}
return $message;
@ -1905,7 +1887,7 @@ function formatSecondsToShortFormat($numSeconds) {
$years = '';
if ($numSeconds >= 31536000) {
$years = floor($numSeconds / 31536000);
$numSeconds = $numSeconds - ($years * 31536000);
$numSeconds -= $years * 31536000;
$years .= 'y';
}
$seconds = $numSeconds % 60;
@ -1932,7 +1914,7 @@ function unformatShortFormatToSeconds($text) {
return $text;
}
$matches = [];
if (preg_match('/^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?$/', $text, $matches)) {
if (preg_match('/^((\d+)y)?((\d+)w)?((\d+)d)?((\d+)h)?((\d+)m)?((\d+)s)?$/', $text, $matches)) {
$newValue = 0;
if (!empty($matches[2])) {
$newValue += $matches[2] * 31536000;

View file

@ -97,7 +97,7 @@ function printHeader(string $headerPrefix): void {
}
asort($toSort);
$tools = [];
foreach ($toSort as $key => $value) {
foreach (array_keys($toSort) as $key) {
$tools[] = new $key();
}
$userData = $_SESSION['ldap']->getUserName();
@ -122,7 +122,7 @@ function printHeader(string $headerPrefix): void {
$serverProfilesPersistenceManager = new ServerProfilePersistenceManager();
try {
$serverProfileNames = $serverProfilesPersistenceManager->getProfiles();
if (sizeof($serverProfileNames) < 2) {
if (count($serverProfileNames) < 2) {
$serverProfileLabel = '';
}
}
@ -166,7 +166,7 @@ function printHeader(string $headerPrefix): void {
parseHtml(null, $accountTypesGroup, [], false, null);
}
if (sizeof($tools) > 0) {
if ($tools !== []) {
$toolGroup = new htmlGroup();
$toolLink = new htmlLink(_('Tools'), "javascript:void(0);");
$toolLink->setOnClick("window.lam.topmenu.openSubmenu(event, 'lam-navigation-tools', window.lam.topmenu.subMenuCloseListenerTools);");

View file

@ -40,7 +40,7 @@ use LAM\PDF\PDFImage;
*/
/** PDF functions */
include_once('pdf.inc');
include_once(__DIR__ . '/pdf.inc');
/**
* Parent class of all account modules.
@ -145,7 +145,7 @@ abstract class baseModule {
$this->orig['objectClass'] = [];
if ($this->autoAddObjectClasses === true) {
$objectClasses = $this->getManagedObjectClasses($this->getAccountContainer()->get_type()->getId());
for ($i = 0; $i < sizeof($objectClasses); $i++) {
for ($i = 0; $i < count($objectClasses); $i++) {
if (!in_array($objectClasses[$i], $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = $objectClasses[$i];
}
@ -179,7 +179,7 @@ abstract class baseModule {
// add object classes if needed
if ($this->autoAddObjectClasses === true) {
$objectClasses = $this->getManagedObjectClasses($typeId);
for ($i = 0; $i < sizeof($objectClasses); $i++) {
for ($i = 0; $i < count($objectClasses); $i++) {
if (!in_array($objectClasses[$i], $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = $objectClasses[$i];
}
@ -189,7 +189,7 @@ abstract class baseModule {
$attributeNames = array_merge($this->getManagedAttributes($typeId), $this->getManagedHiddenAttributes($typeId));
$attributeNames = array_unique($attributeNames);
$attributeNames = array_values($attributeNames);
for ($i = 0; $i < sizeof($attributeNames); $i++) {
for ($i = 0; $i < count($attributeNames); $i++) {
if (isset($attributes[$attributeNames[$i]])) {
$this->attributes[$attributeNames[$i]] = $attributes[$attributeNames[$i]];
$this->orig[$attributeNames[$i]] = $attributes[$attributeNames[$i]];
@ -620,7 +620,7 @@ abstract class baseModule {
$val2 = $options[$check['cmp_name2']][0];
// ignore if both fields are empty
if (!(empty($val1) && empty($val2))
&& (($val1 == '') || ($val2 == '') || !(intval($val1) > intval($val2)))) {
&& (($val1 == '') || ($val2 == '') || intval($val1) <= intval($val2))) {
$errors[] = $check['error_message'];
}
break;
@ -630,7 +630,7 @@ abstract class baseModule {
$val2 = $options[$check['cmp_name2']][0];
// ignore if both fields are empty
if (!(empty($val1) && empty($val2))
&& (($val1 == '') || ($val2 == '') || !(intval($val1) >= intval($val2)))) {
&& (($val1 == '') || ($val2 == '') || intval($val1) < intval($val2))) {
$errors[] = $check['error_message'];
}
break;
@ -656,7 +656,7 @@ abstract class baseModule {
public function load_profile($profile) {
if (isset($this->meta['profile_mappings'])) {
$identifiers = array_keys($this->meta['profile_mappings']);
for ($i = 0; $i < sizeof($identifiers); $i++) {
for ($i = 0; $i < count($identifiers); $i++) {
if (isset($profile[$identifiers[$i]])) {
$this->attributes[$this->meta['profile_mappings'][$identifiers[$i]]] = $profile[$identifiers[$i]];
}
@ -681,7 +681,7 @@ abstract class baseModule {
*/
public function get_configOptions($scopes, $allScopes) {
$return = [];
for ($i = 0; $i < sizeof($scopes); $i++) {
for ($i = 0; $i < count($scopes); $i++) {
if (isset($this->meta['config_options'][$scopes[$i]])) {
if (is_array($this->meta['config_options'][$scopes[$i]])) {
$return = array_merge($return, $this->meta['config_options'][$scopes[$i]]);
@ -733,7 +733,7 @@ abstract class baseModule {
foreach ($scopes as $scope) {
if (isset($this->meta['config_checks'][$scope]) && is_array($this->meta['config_checks'][$scope])) {
$identifiers = array_keys($this->meta['config_checks'][$scope]);
for ($i = 0; $i < sizeof($identifiers); $i++) {
for ($i = 0; $i < count($identifiers); $i++) {
// check if option is required
if (isset($this->meta['config_checks'][$scope][$identifiers[$i]]['required']) && ($this->meta['config_checks'][$scope][$identifiers[$i]]['required']) && ($options[$identifiers[$i]][0] == '')) {
$messages[] = $this->meta['config_checks'][$scope][$identifiers[$i]]['required_message'];
@ -781,7 +781,7 @@ abstract class baseModule {
break;
}
// compare
if (!(intval($options[$this->meta['config_checks'][$scope][$identifiers[$i]]['cmp_name1']][0]) > intval($options[$this->meta['config_checks'][$scope][$identifiers[$i]]['cmp_name2']][0]))) {
if (intval($options[$this->meta['config_checks'][$scope][$identifiers[$i]]['cmp_name1']][0]) <= intval($options[$this->meta['config_checks'][$scope][$identifiers[$i]]['cmp_name2']][0])) {
$messages[] = $this->meta['config_checks'][$scope][$identifiers[$i]]['error_message'];
}
break;
@ -797,7 +797,7 @@ abstract class baseModule {
break;
}
// compare
if (!(intval($options[$this->meta['config_checks'][$scope][$identifiers[$i]]['cmp_name1']][0]) >= intval($options[$this->meta['config_checks'][$scope][$identifiers[$i]]['cmp_name2']][0]))) {
if (intval($options[$this->meta['config_checks'][$scope][$identifiers[$i]]['cmp_name1']][0]) < intval($options[$this->meta['config_checks'][$scope][$identifiers[$i]]['cmp_name2']][0])) {
$messages[] = $this->meta['config_checks'][$scope][$identifiers[$i]]['error_message'];
}
break;
@ -939,7 +939,7 @@ abstract class baseModule {
* @param PDFTable $table table
*/
public function addPDFImage(&$result, $attrName) {
if (isset($this->attributes[$attrName]) && (sizeof($this->attributes[$attrName]) > 0)) {
if (isset($this->attributes[$attrName]) && (count($this->attributes[$attrName]) > 0)) {
$result[static::class . '_' . $attrName][] = new PDFImage($this->attributes[$attrName][0]);
}
}
@ -1039,7 +1039,7 @@ abstract class baseModule {
$list = preg_split($regexSplit, trim($rawAccounts[$position][$ids[$colName]]));
$partialAccounts[$position][$attrName] = $list;
if (!empty($regex)) {
for ($x = 0; $x < sizeof($list); $x++) {
for ($x = 0; $x < count($list); $x++) {
if (!$this->checkUploadRegex($regexIDs, $list[$x], $message, $position, $errors)) {
break;
}
@ -1398,7 +1398,7 @@ abstract class baseModule {
$val = implode('<br>', $values);
}
$labelBox = new htmlOutputText($label);
if (!empty($this->attributes[$attrName]) && (sizeof($this->attributes[$attrName]) > 1)) {
if (!empty($this->attributes[$attrName]) && (count($this->attributes[$attrName]) > 1)) {
$labelBox->alignment = htmlElement::ALIGN_TOP;
}
$container->addLabel($labelBox);
@ -1457,7 +1457,7 @@ abstract class baseModule {
if (isset($this->attributes[$attrName][0])) {
$values = $this->attributes[$attrName];
}
if (sizeof($values) == 0) {
if (count($values) == 0) {
$values[] = '';
}
natcasesort($values);
@ -1472,7 +1472,7 @@ abstract class baseModule {
$subContainer = new htmlTable();
$subContainer->setCSSClasses(['fullwidth']);
$subContainer->alignment = htmlElement::ALIGN_TOP;
for ($i = 0; $i < sizeof($values); $i++) {
for ($i = 0; $i < count($values); $i++) {
if (!$isTextArea) {
$input = new htmlInputField($attrName . '_' . $i, $values[$i]);
$input->setAccessibilityLabel($label);
@ -1541,12 +1541,12 @@ abstract class baseModule {
$counter = 0;
while (isset($_POST[$attrName . '_' . $counter])) {
$this->attributes[$attrName][$counter] = trim($_POST[$attrName . '_' . $counter]);
if (($this->attributes[$attrName][$counter] == '') || isset($_POST['del_' . $attrName . '_' . $counter])) {
if (($this->attributes[$attrName][$counter] === '') || isset($_POST['del_' . $attrName . '_' . $counter])) {
unset($this->attributes[$attrName][$counter]);
}
elseif (($validationID != null) && ($this->attributes[$attrName][$counter] != '') && !get_preg($this->attributes[$attrName][$counter], $validationID)) {
elseif (($validationID != null) && ($this->attributes[$attrName][$counter] !== '') && !get_preg($this->attributes[$attrName][$counter], $validationID)) {
$msg = $this->messages[$attrName][0];
if (sizeof($msg) < 3) {
if (count($msg) < 3) {
$msg[] = htmlspecialchars($this->attributes[$attrName][$counter]);
}
else {
@ -1589,7 +1589,7 @@ abstract class baseModule {
if (isset($this->attributes[$attrName][0])) {
$values = $this->attributes[$attrName];
}
if (sizeof($values) == 0) {
if (count($values) == 0) {
$values[] = '';
}
natcasesort($values);
@ -1601,7 +1601,7 @@ abstract class baseModule {
}
$subContainer = new htmlTable();
$subContainer->alignment = htmlElement::ALIGN_TOP;
for ($i = 0; $i < sizeof($values); $i++) {
for ($i = 0; $i < count($values); $i++) {
$input = new htmlSelect($attrName . '_' . $i, $options, [$values[$i]], $fieldSize);
$input->setHasDescriptiveElements($hasDescriptiveOptions);
$subContainer->addElement($input);
@ -1630,7 +1630,7 @@ abstract class baseModule {
$counter = 0;
while (isset($_POST[$attrName . '_' . $counter])) {
$this->attributes[$attrName][$counter] = trim($_POST[$attrName . '_' . $counter]);
if (($this->attributes[$attrName][$counter] == '') || isset($_POST['del_' . $attrName . '_' . $counter])) {
if (($this->attributes[$attrName][$counter] === '') || isset($_POST['del_' . $attrName . '_' . $counter])) {
unset($this->attributes[$attrName][$counter]);
}
$counter++;
@ -1765,15 +1765,13 @@ abstract class baseModule {
elseif ($isTextArea && !in_array($name, $readOnlyFields)) {
$field = new htmlInputTextarea(static::class . '_' . $name, $value, null, null);
}
elseif (!$isTextArea) {
$field = new htmlOutputText($value);
}
else {
if (!$isTextArea) {
$field = new htmlOutputText($value);
}
else {
$value = htmlspecialchars($value);
$value = str_replace("\n", '<br>', $value);
$field = new htmlOutputText($value, false);
}
$value = htmlspecialchars($value);
$value = str_replace("\n", '<br>', $value);
$field = new htmlOutputText($value, false);
}
$row = new htmlResponsiveRow();
$fieldLabel = new htmlLabel(static::class . '_' . $name, $this->getSelfServiceLabel($name, $label));
@ -1805,20 +1803,13 @@ abstract class baseModule {
$ldapAttrName = $attributeName ?? $name;
if (!empty($_POST[$fieldName])) {
if (($validationID != null) && !get_preg($_POST[$fieldName], $validationID)) {
if ($validationMessage !== null) {
$container['messages'][] = $validationMessage;
}
else {
$container['messages'][] = $this->messages[$name][0];
}
$container['messages'][] = $validationMessage ?? $this->messages[$name][0];
}
else {
if (isset($attributes[$ldapAttrName]) && ($attributes[$ldapAttrName][0] != $_POST[$fieldName])) {
$container['mod'][$ldapAttrName] = [$_POST[$fieldName]];
}
elseif (!isset($attributes[$ldapAttrName])) {
$container['add'][$ldapAttrName] = [$_POST[$fieldName]];
}
elseif (isset($attributes[$ldapAttrName]) && ($attributes[$ldapAttrName][0] != $_POST[$fieldName])) {
$container['mod'][$ldapAttrName] = [$_POST[$fieldName]];
}
elseif (!isset($attributes[$ldapAttrName])) {
$container['add'][$ldapAttrName] = [$_POST[$fieldName]];
}
}
elseif (isset($attributes[$ldapAttrName])) {
@ -1863,7 +1854,7 @@ abstract class baseModule {
if (empty($values)) {
$values[] = '';
}
for ($i = 0; $i < sizeof($values); $i++) {
for ($i = 0; $i < count($values); $i++) {
$fieldRow = new htmlResponsiveRow();
$value = $values[$i];
if (!$isTextArea) {
@ -1884,7 +1875,7 @@ abstract class baseModule {
$delLink->setTitle(_('Delete'));
$linkGroup->addElement($delLink);
}
if ($i === (sizeof($values) - 1)) {
if ($i === (count($values) - 1)) {
$addLink = new htmlLink(null, '#', '../../graphics/add.svg');
$addLink->setOnClick('window.lam.selfservice.addMultiValue(\'' . $fieldNamePrefix . '\', this); return false;');
$addLink->setCSSClasses(['add-link icon', 'margin-left5']);
@ -1944,12 +1935,7 @@ abstract class baseModule {
continue;
}
if (($validationID != null) && !get_preg($postValue, $validationID)) {
if ($validationMessage !== null) {
$container['messages'][] = $validationMessage;
}
else {
$container['messages'][] = $this->messages[$name][0];
}
$container['messages'][] = $validationMessage ?? $this->messages[$name][0];
return;
}
$valuesNew[] = $postValue;
@ -1959,7 +1945,7 @@ abstract class baseModule {
}
$valuesOld = $attributes[$ldapAttrName] ?? [];
$intersect = array_intersect($valuesOld, $valuesNew);
if ((sizeof($valuesOld) != sizeof($valuesNew)) || (sizeof($intersect) != sizeof($valuesOld))) {
if ((count($valuesOld) !== count($valuesNew)) || (count($intersect) !== count($valuesOld))) {
$container['mod'][$ldapAttrName] = $valuesNew;
}
}
@ -2265,7 +2251,7 @@ abstract class baseModule {
* @see accountContainer
*/
protected function getAccountContainer(): ?accountContainer {
if (isset($this->base) && isset($_SESSION[$this->base])) {
if ($this->base !== null && isset($_SESSION[$this->base])) {
return $_SESSION[$this->base];
}
else {
@ -2350,7 +2336,7 @@ abstract class baseModule {
*/
protected function isBooleanConfigOptionSet($optionName, $default = false) {
// abort if configuration is not available
if (!isset($this->moduleSettings) || !is_array($this->moduleSettings) || !isset($this->moduleSettings[$optionName][0])) {
if ($this->moduleSettings === null || !is_array($this->moduleSettings) || !isset($this->moduleSettings[$optionName][0])) {
return $default;
}
return ($this->moduleSettings[$optionName][0] == 'true');

View file

@ -117,7 +117,7 @@ if (!extension_loaded('filter')) {
}
// check file permissions
$writableDirs = ['sess', 'tmp'];
for ($i = 0; $i < sizeof($writableDirs); $i++) {
for ($i = 0; $i < count($writableDirs); $i++) {
$path = realpath('../') . "/" . $writableDirs[$i];
if (!is_writable($path)) {
$criticalErrors[] = ["ERROR", 'The directory %s is not writable for the web server. Please change your file permissions.', '', [$path]];
@ -130,7 +130,7 @@ if (ini_get("session.auto_start") == "1") {
// check memory limit
$memLimit = ini_get('memory_limit');
if (($memLimit != '')
&& (substr(strtoupper($memLimit), strlen($memLimit) - 1) == 'M')
&& (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\".",
"Your current memory limit is $memLimit."];

View file

@ -40,15 +40,15 @@ use function LAM\TYPES\getScopeFromTypeId;
*/
/** persistence */
include_once 'persistence.inc';
include_once __DIR__ . '/persistence.inc';
/** Used to print messages. */
include_once "status.inc";
include_once __DIR__ . "/status.inc";
/** Used to get module information. */
include_once "modules.inc";
include_once __DIR__ . "/modules.inc";
/** Used to get type information. */
include_once "types.inc";
include_once __DIR__ . "/types.inc";
/** 2-factor */
include_once '2factor.inc';
include_once __DIR__ . '/2factor.inc';
/**
* Sets the environment variables for custom SSL CA certificates.
@ -140,12 +140,9 @@ function checkChmod($right, $target, $chmod) {
$write = [2, 3, 6, 7];
// What numbers allow "execute"
$execute = [1, 3, 5, 7];
if ((($right == "read") && in_array($chmod_num, $read))
return (($right == "read") && in_array($chmod_num, $read))
|| (($right == "write") && in_array($chmod_num, $write))
|| (($right == "execute") && in_array($chmod_num, $execute))) {
return true;
}
return false;
|| (($right == "execute") && in_array($chmod_num, $execute));
}
/**
@ -190,12 +187,7 @@ function extractConfigOptionsFromPOST($confTypes) {
}
// checkboxes
elseif ($type == "checkbox") {
if (isset($_POST[$element]) && ($_POST[$element] == "on")) {
$options[$element] = ['true'];
}
else {
$options[$element] = ['false'];
}
$options[$element] = isset($_POST[$element]) && ($_POST[$element] == "on") ? ['true'] : ['false'];
}
// dropdownbox
elseif ($type == "select") {
@ -267,7 +259,7 @@ function getLanguages() {
$file = fopen($languagefile, "r");
while (!feof($file)) {
$line = fgets($file, 1024);
if ($line == "" || $line == "\n" || $line[0] == "#") {
if ($line == "" || $line === "\n" || $line[0] === "#") {
continue; // ignore comment and empty lines
}
$value = explode(":", $line);
@ -373,7 +365,7 @@ class ServerProfilePersistenceManager {
$ext = substr($entry, strlen($entry) - 12, 12);
$name = substr($entry, 0, strlen($entry) - 12);
// check if extension is right, add to profile list
if ($ext == ".sample.conf") {
if ($ext === ".sample.conf") {
$ret[$pos] = $name;
$pos++;
}
@ -550,7 +542,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") && (!str_contains($name, '.sample')) && is_readable($dirName . '/' . $entry)) {
if (($ext === ".conf") && (!str_contains($name, '.sample')) && is_readable($dirName . '/' . $entry)) {
$ret[] = $name;
}
}
@ -584,7 +576,7 @@ class ServerProfilePersistenceStrategyFiles implements ServerProfilePersistenceS
while (!feof($file)) {
$line = fgets($file, 1000000);
$line = trim($line); // remove spaces at the beginning and end
if (($line == "") || ($line[0] == "#")) {
if (($line === "") || ($line[0] === "#")) {
continue; // ignore comments and empty lines
}
// search keywords
@ -592,7 +584,7 @@ class ServerProfilePersistenceStrategyFiles implements ServerProfilePersistenceS
$keyword = $parts[0];
$keyword = trim($keyword, ':');
$startIndex = strlen($keyword) + 2;
$value = (sizeof($parts) > 1) ? substr($line, $startIndex) : '';
$value = (count($parts) > 1) ? substr($line, $startIndex) : '';
if (!in_array($keyword, ['modules', 'types', 'tools', 'jobs'])) {
$data[$keyword] = $value;
}
@ -604,19 +596,19 @@ class ServerProfilePersistenceStrategyFiles implements ServerProfilePersistenceS
continue;
}
// module settings
if ($keyword == 'modules') {
if ($keyword === 'modules') {
$moduleSettings[$subKeyword] = explode(LAMConfig::LINE_SEPARATOR, $option);
}
// type settings
if ($keyword == 'types') {
if ($keyword === 'types') {
$typeSettings[$subKeyword] = $option;
}
// tool settings
if ($keyword == 'tools') {
if ($keyword === 'tools') {
$toolSettings[$subKeyword] = $option;
}
// job settings
if ($keyword == 'jobs') {
if ($keyword === 'jobs') {
$jobSettings[$subKeyword] = explode(LAMConfig::LINE_SEPARATOR, $option);
}
}
@ -645,7 +637,7 @@ class ServerProfilePersistenceStrategyFiles implements ServerProfilePersistenceS
if (is_file($confFile) && is_readable($confFile)) {
$file = @fopen($confFile, "w");
if ($file) {
fputs($file, json_encode($profile->exportData(), JSON_PRETTY_PRINT));
fwrite($file, json_encode($profile->exportData(), JSON_PRETTY_PRINT));
fclose($file);
@chmod($confFile, 0600);
}
@ -693,11 +685,11 @@ class ServerProfilePersistenceStrategyFiles implements ServerProfilePersistenceS
$dir . 'pdf/' . $name,
$dir . 'profiles/' . $name
];
for ($i = 0; $i < sizeof($subDirs); $i++) {
for ($i = 0; $i < count($subDirs); $i++) {
if (is_dir($subDirs[$i]) && is_readable($subDirs[$i])) {
$dirHandle = @opendir($subDirs[$i]);
while (false !== ($path = readdir($dirHandle))) {
if (($path != '.') && ($path != '..') && !@unlink($subDirs[$i] . '/' . $path)) {
if (($path !== '.') && ($path !== '..') && !@unlink($subDirs[$i] . '/' . $path)) {
logNewMessage(LOG_ERR, 'Unable to delete ' . $subDirs[$i] . '/' . $path);
throw new LAMException(_("Unable to delete profile!"));
}
@ -721,7 +713,7 @@ class ServerProfilePersistenceStrategyFiles implements ServerProfilePersistenceS
* @inheritDoc
*/
public function isWritable(string $name): bool {
return is_writeable($this->getPath($name));
return is_writable($this->getPath($name));
}
/**
@ -1129,7 +1121,7 @@ class LAMConfig {
public function removeInvalidTypes() {
$allTypes = LAM\TYPES\getTypes();
$activeTypes = $this->get_ActiveTypes();
for ($i = 0; $i < sizeof($activeTypes); $i++) {
for ($i = 0; $i < count($activeTypes); $i++) {
if (!in_array(getScopeFromTypeId($activeTypes[$i]), $allTypes)) {
unset($activeTypes[$i]);
}
@ -1155,7 +1147,7 @@ class LAMConfig {
$available = $availableByScope[$scope];
// only return available modules
$ret = [];
for ($i = 0; $i < sizeof($modules); $i++) {
for ($i = 0; $i < count($modules); $i++) {
if (in_array($modules[$i], $available)) {
$ret[] = $modules[$i];
}
@ -1683,7 +1675,7 @@ class LAMConfig {
}
// Explode the value to an array
$array_string = explode(";", $value);
if (count($array_string) > 0) {
if ($array_string !== []) {
// Check all IPs in the exploded Array
$valid_ips = [];
foreach ($array_string as $arr_value) {
@ -1735,7 +1727,7 @@ class LAMConfig {
* @return string rights
*/
public function get_scriptRights() {
if (!isset($this->scriptRights)) {
if ($this->scriptRights === null) {
return '755';
}
return $this->scriptRights;
@ -1846,7 +1838,7 @@ class LAMConfig {
$modulesTmp = explode(",", $this->typeSettings["modules_" . $scope]);
$modules = [];
foreach ($modulesTmp as $mod) {
if (trim($mod) != '') {
if (trim($mod) !== '') {
$modules[] = $mod;
}
}
@ -1870,7 +1862,7 @@ class LAMConfig {
}
// check module names
$available = getAvailableModules($scope);
for ($i = 0; $i < sizeof($modules); $i++) {
for ($i = 0; $i < count($modules); $i++) {
if (!in_array($modules[$i], $available)) {
return false;
}
@ -1915,7 +1907,7 @@ class LAMConfig {
* @return string[] list of types
*/
public function get_ActiveTypes() {
if (($this->activeTypes == '') || !isset($this->activeTypes)) {
if (($this->activeTypes === '') || ($this->activeTypes === null)) {
return [];
}
else {
@ -2079,10 +2071,7 @@ class LAMConfig {
*/
public function setLoginSearchDN($loginSearchDN) {
$this->loginSearchDN = $loginSearchDN;
if (($loginSearchDN == '') || get_preg($loginSearchDN, 'dn')) {
return true;
}
return false;
return ($loginSearchDN == '') || get_preg($loginSearchDN, 'dn');
}
/**
@ -2916,22 +2905,22 @@ class LAMCfgMain {
private $password;
/** Time of inactivity before session times out (minutes) */
public $sessionTimeout;
public $sessionTimeout = 30;
/** @var string hides detail messages for login errors */
public string $hideLoginErrorDetails = 'false';
/** log level */
public $logLevel;
public $logLevel = LOG_NOTICE;
/** log destination ("SYSLOG":syslog, "/...":file, "NONE":none, "REMOTE":server:port) */
public $logDestination;
public $logDestination = "SYSLOG";
/** list of hosts which may access LAM */
public $allowedHosts;
public $allowedHosts = "";
/** list of hosts which may access LAM Pro self service */
public $allowedHostsSelfService;
public $allowedHostsSelfService = '';
/** minimum length for passwords */
public $passwordMinLength = 0;
@ -3064,20 +3053,7 @@ class LAMCfgMain {
* @param string $fileName file path for config file
*/
function __construct($fileName = null) {
if ($fileName === null) {
$this->conffile = __DIR__ . "/../config/config.cfg";
}
else {
$this->conffile = $fileName;
}
// set default values
$this->sessionTimeout = 30;
$this->hideLoginErrorDetails = 'false';
$this->logLevel = LOG_NOTICE;
$this->logDestination = "SYSLOG";
$this->allowedHosts = "";
$this->allowedHostsSelfService = '';
$this->moduleSettings = '';
$this->conffile = $fileName ?? __DIR__ . "/../config/config.cfg";
try {
$this->reload();
}
@ -3172,7 +3148,7 @@ class LAMCfgMain {
$fileName = $this->getInternalSSLCaCertFileName();
$handle = @fopen($fileName, "wb");
if ($handle) {
fputs($handle, $certsContent);
fwrite($handle, $certsContent);
fclose($handle);
@chmod($fileName, 0600);
}
@ -3204,14 +3180,14 @@ class LAMCfgMain {
while (!feof($file)) {
$line = fgets($file, 1000000);
$line = trim($line); // remove spaces at the beginning and end
if (($line == "") || ($line[0] == "#")) {
if (($line === "") || ($line[0] === "#")) {
continue; // ignore comments
}
// search keywords
for ($i = 0; $i < sizeof($this->settings); $i++) {
for ($i = 0; $i < count($this->settings); $i++) {
$keyword = $this->settings[$i];
$keylen = strlen($keyword);
if (strtolower(substr($line, 0, $keylen + 2)) == strtolower($keyword . ": ")) {
if (strtolower(substr($line, 0, $keylen + 2)) === strtolower($keyword . ": ")) {
$this->$keyword = substr($line, $keylen + 2, strlen($line) - $keylen - 2);
break;
}
@ -3256,11 +3232,11 @@ class LAMCfgMain {
}
catch (PDOException $e) {
syslog(LOG_ERR, 'Unable to read main config: ' . $e->getMessage());
throw new LAMException(_('Unable to connect to configuration database.'));
throw new LAMException(_('Unable to connect to configuration database.'), null, $e);
}
catch (LAMException $e) {
syslog(LOG_ERR, 'Unable to import main config: ' . $e->getMessage());
throw new LAMException(_('Unable to connect to configuration database.'));
throw new LAMException(_('Unable to connect to configuration database.'), null, $e);
}
}
@ -3280,7 +3256,7 @@ class LAMCfgMain {
$sslPath = $this->getInternalSSLCaCertFileName();
$file = @fopen($sslPath, "w");
if ($file) {
fputs($file, $this->uploadedSSLCaCert);
fwrite($file, $this->uploadedSSLCaCert);
fclose($file);
@chmod($sslPath, 0600);
}
@ -3322,17 +3298,12 @@ class LAMCfgMain {
* @param bool $persistenceOnly store only persistence related data
*/
public function saveLocal(bool $persistenceOnly): void {
if ($persistenceOnly) {
$data = $this->exportPersistenceData();
}
else {
$data = $this->exportData();
}
$data = $persistenceOnly ? $this->exportPersistenceData() : $this->exportData();
$json = json_encode($data, JSON_PRETTY_PRINT);
$file = @fopen($this->conffile, "w");
if ($file) {
fputs($file, $json);
fwrite($file, $json);
fclose($file);
chmod($this->conffile, 0600);
}
@ -3393,7 +3364,7 @@ class LAMCfgMain {
* @return boolean writable
*/
public function isWritable(): bool {
return is_writeable($this->conffile);
return is_writable($this->conffile);
}
/**
@ -3491,7 +3462,7 @@ class LAMCfgMain {
$temporaryFilesManager = new LamTemporaryFilesManager();
$fileName = $temporaryFilesManager->registerTemporaryFile('.pem');
$handle = $temporaryFilesManager->openTemporaryFileForWrite($fileName);
fputs($handle, $content);
fwrite($handle, $content);
fclose($handle);
return $fileName;
}
@ -3516,7 +3487,7 @@ class LAMCfgMain {
$content = $this->getSSLCaCertificateContent();
$list = $this->splitSSLCaCertificateContent($content);
unset($list[$index]);
if (sizeof($list) < 1) {
if (count($list) < 1) {
$this->delSSLCaCert = true;
$this->uploadedSSLCaCert = null;
}
@ -3539,7 +3510,7 @@ class LAMCfgMain {
return [];
}
$list = $this->splitSSLCaCertificateContent($content);
for ($i = 0; $i < sizeof($list); $i++) {
for ($i = 0; $i < count($list); $i++) {
$list[$i] = @openssl_x509_parse($list[$i]);
}
return $list;

View file

@ -140,10 +140,10 @@ class CronRunner {
$pdo = $cronDatabase->getPdo();
}
catch (PDOException $e) {
throw new LAMException("Unable to connect to database. " . $e->getMessage());
throw new LAMException("Unable to connect to database. " . $e->getMessage(), null, $e);
}
catch (LAMException $e) {
throw new LAMException("Unable to connect to database. " . $e->getTitle());
throw new LAMException("Unable to connect to database. " . $e->getTitle(), null, $e);
}
// get jobs to run
if (empty($cronDatabase->getJobs())) {

View file

@ -35,7 +35,7 @@ use LamTemporaryFilesManager;
*/
/** LDAP handle */
include_once('ldap.inc');
include_once(__DIR__ . '/ldap.inc');
/**
* Creates LDAP accounts for file upload.
@ -258,7 +258,7 @@ class Exporter {
$output .= '# ' . _('Base DN') . ': ' . $this->baseDn . $lineEnding;
$output .= '# ' . _('Search scope') . ': ' . $this->searchScope . $lineEnding;
$output .= '# ' . _('Search filter') . ': ' . $this->filter . $lineEnding;
$output .= '# ' . _('Total entries') . ': ' . sizeof($entries) . $lineEnding;
$output .= '# ' . _('Total entries') . ': ' . count($entries) . $lineEnding;
$output .= '#' . $lineEnding;
$output .= '# Generated by LDAP Account Manager on ' . date('Y-m-d H:i:s') . $lineEnding;
$output .= $lineEnding;
@ -299,7 +299,7 @@ class Exporter {
}
$wrappedContent = substr($content, 0, $line_length) . $lineEnding;
$contentLeft = substr($content, $line_length);
$line_length = $line_length - 1;
$line_length -= 1;
$lines = str_split($contentLeft, $line_length);
foreach ($lines as $line) {
$wrappedContent .= ' ' . $line . $lineEnding;

View file

@ -282,7 +282,7 @@ class htmlTable extends htmlElement {
$colspan = $element->getColspanString();
$rowspan = $element->getRowspanString();
$css = '';
if (sizeof($element->getTableCellCSSClasses()) > 0) {
if (count($element->getTableCellCSSClasses()) > 0) {
$css = 'class="' . implode(' ', $element->getTableCellCSSClasses()) . '"';
}
$tagName = 'td';
@ -301,12 +301,7 @@ class htmlTable extends htmlElement {
* Adds another line to the table.
*/
public function addNewLine() {
if (!$this->rowOpen) {
$this->elements[] = "<tr>\n";
}
else {
$this->elements[] = self::NEWLINE;
}
$this->elements[] = $this->rowOpen ? self::NEWLINE : "<tr>\n";
}
/**
@ -348,22 +343,19 @@ class htmlTable extends htmlElement {
$id = ' id="' . $this->id . '"';
}
$classAttr = '';
if (sizeof($this->cssClasses) > 0) {
if (count($this->cssClasses) > 0) {
$classAttr = ' class="' . implode(' ', $this->cssClasses) . '"';
}
echo "<table" . $width . $id . $classAttr . ">\n";
// print all contained elements
for ($i = 0; $i < sizeof($this->elements); $i++) {
for ($i = 0; $i < count($this->elements); $i++) {
// print htmlElement objects
if ($this->elements[$i] instanceof htmlElement) {
$fields = $this->elements[$i]->generateHTML($module, $input, $values, $restricted, $scope);
$return = array_merge($return, $fields);
}
// print simple Strings
else {
if ($i != (sizeof($this->elements) - 1) || !($this->elements[$i] == self::NEWLINE)) {
echo $this->elements[$i];
}
elseif ($i !== count($this->elements) - 1 || ($this->elements[$i] != self::NEWLINE)) {
echo $this->elements[$i];
}
}
if ($this->rowOpen) {
@ -380,8 +372,8 @@ class htmlTable extends htmlElement {
*/
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]);
if ($table->elements[count($table->elements) - 1] == self::NEWLINE) {
unset($table->elements[count($table->elements) - 1]);
}
// close last row of other table if needed
if ($table->rowOpen) {
@ -389,8 +381,8 @@ class htmlTable extends htmlElement {
}
// close last own row if needed
if ($this->rowOpen) {
if ($this->elements[sizeof($this->elements) - 1] == self::NEWLINE) {
unset($this->elements[sizeof($this->elements) - 1]);
if ($this->elements[count($this->elements) - 1] == self::NEWLINE) {
unset($this->elements[count($this->elements) - 1]);
}
else {
$this->elements[] = "</tr>\n";
@ -1130,12 +1122,7 @@ class htmlButton extends htmlElement {
if ($this->noFormValidation) {
$noFormValidation = ' formnovalidate="formnovalidate"';
}
if ($this->type == null) {
$type = ' type="submit"';
}
else {
$type = ' type="' . $this->type . '"';
}
$type = $this->type == null ? ' type="submit"' : ' type="' . $this->type . '"';
$onClick = '';
if ($this->onClick != null) {
if ($this->type == null) {
@ -1345,7 +1332,7 @@ class htmlSelect extends htmlElement {
$onchange = ' onchange="' . $onchange . '"';
}
// hide select boxes that contain less than 2 elements
if ((sizeof($this->elements) < 2) && !$this->multiSelect && !$this->containsOptgroups && $this->transformSingleSelect) {
if ((count($this->elements) < 2) && !$this->multiSelect && !$this->containsOptgroups && $this->transformSingleSelect) {
echo '<div class="hidden">';
}
// print select box
@ -1353,7 +1340,7 @@ class htmlSelect extends htmlElement {
. $name . $size . $multi . $disabled . $onchange . ">\n";
if ($this->containsOptgroups) {
foreach ($this->elements as $label => $elements) {
if (sizeof($elements) > 0) {
if (count($elements) > 0) {
echo '<optgroup label="' . $label . '">';
$this->printOptionsHTML($elements);
echo '</optgroup>';
@ -1365,9 +1352,9 @@ class htmlSelect extends htmlElement {
}
echo "</select>\n";
// if select box has only one element then show it as text
if ((sizeof($this->elements) < 2) && !$this->multiSelect && !$this->containsOptgroups && $this->transformSingleSelect) {
if ((count($this->elements) < 2) && !$this->multiSelect && !$this->containsOptgroups && $this->transformSingleSelect) {
echo '</div>';
if (sizeof($this->elements) == 1) {
if (count($this->elements) == 1) {
echo '&nbsp;';
if ($this->hasDescriptiveElements) {
$keys = array_keys($this->elements);
@ -1565,7 +1552,7 @@ class htmlSelect extends htmlElement {
* @param String $onChange onChange code
*/
private function printCodeForShowHideTableRows(&$onChange) {
if ((sizeof($this->tableRowsToHide) == 0) && (sizeof($this->tableRowsToShow) == 0)) {
if ((count($this->tableRowsToHide) == 0) && (count($this->tableRowsToShow) == 0)) {
return;
}
$values = [];
@ -1581,12 +1568,12 @@ class htmlSelect extends htmlElement {
// build onChange listener
$onChange .= 'if (document.getElementById(\'' . $this->name . '\').value == \'' . $val . '\') {';
if (isset($this->tableRowsToShow[$val])) {
for ($i = 0; $i < sizeof($this->tableRowsToShow[$val]); $i++) {
for ($i = 0; $i < count($this->tableRowsToShow[$val]); $i++) {
$onChange .= 'document.getElementById(\'' . $this->tableRowsToShow[$val][$i] . '\')?.closest(\'' . $selector . '\').classList.remove(\'hidden\');';
}
}
if (isset($this->tableRowsToHide[$val])) {
for ($i = 0; $i < sizeof($this->tableRowsToHide[$val]); $i++) {
for ($i = 0; $i < count($this->tableRowsToHide[$val]); $i++) {
$onChange .= 'document.getElementById(\'' . $this->tableRowsToHide[$val][$i] . '\')?.closest(\'' . $selector . '\').classList.add(\'hidden\');';
}
}
@ -1595,13 +1582,13 @@ class htmlSelect extends htmlElement {
// build script to set initial state
$script = '<script type="text/javascript">window.lam.utility.documentReady(function() {' . "\n";
if (isset($this->tableRowsToShow[$this->selectedElements[0]])) {
for ($i = 0; $i < sizeof($this->tableRowsToShow[$this->selectedElements[0]]); $i++) {
for ($i = 0; $i < count($this->tableRowsToShow[$this->selectedElements[0]]); $i++) {
$classType = 'remove';
$script .= 'document.getElementById(\'' . $this->tableRowsToShow[$this->selectedElements[0]][$i] . '\')?.closest(\'' . $selector . '\').classList.' . $classType . '(\'hidden\');' . "\n";
}
}
if (isset($this->tableRowsToHide[$this->selectedElements[0]])) {
for ($i = 0; $i < sizeof($this->tableRowsToHide[$this->selectedElements[0]]); $i++) {
for ($i = 0; $i < count($this->tableRowsToHide[$this->selectedElements[0]]); $i++) {
$classType = 'add';
$script .= 'document.getElementById(\'' . $this->tableRowsToHide[$this->selectedElements[0]][$i] . '\')?.closest(\'' . $selector . '\').classList.' . $classType . '(\'hidden\');' . "\n";
}
@ -1625,7 +1612,7 @@ class htmlSelect extends htmlElement {
*/
public function enableDynamicScrolling() {
// not possible for optgroups and smaller option lists
if ((sizeof($this->elements) < 10000) || $this->containsOptgroups) {
if ((count($this->elements) < 10000) || $this->containsOptgroups) {
return;
}
$this->dynamicScrolling = true;
@ -1780,7 +1767,7 @@ class htmlRadio extends htmlElement {
*/
private function getOnchangeCodeForShowHideTableRows($counter): string {
$onChange = '';
if ((sizeof($this->tableRowsToHide) == 0) && (sizeof($this->tableRowsToShow) == 0)) {
if ((count($this->tableRowsToHide) == 0) && (count($this->tableRowsToShow) == 0)) {
return $onChange;
}
$values = [];
@ -1797,12 +1784,12 @@ class htmlRadio extends htmlElement {
// build onChange listener
$onChange .= 'if (document.getElementById(\'' . $this->name . $counter . '\').value == \'' . $val . '\') {';
if (isset($this->tableRowsToShow[$val])) {
for ($i = 0; $i < sizeof($this->tableRowsToShow[$val]); $i++) {
for ($i = 0; $i < count($this->tableRowsToShow[$val]); $i++) {
$onChange .= 'document.getElementById(\'' . $this->tableRowsToShow[$val][$i] . '\')?.closest(\'' . $selector . '\').classList.remove(\'hidden\');';
}
}
if (isset($this->tableRowsToHide[$val])) {
for ($i = 0; $i < sizeof($this->tableRowsToHide[$val]); $i++) {
for ($i = 0; $i < count($this->tableRowsToHide[$val]); $i++) {
$onChange .= 'document.getElementById(\'' . $this->tableRowsToHide[$val][$i] . '\')?.closest(\'' . $selector . '\').classList.add(\'hidden\');';
}
}
@ -1816,12 +1803,12 @@ class htmlRadio extends htmlElement {
// build script to set initial state
$script = '<script type="text/javascript">window.lam.utility.documentReady(function() {' . "\n";
if (isset($this->tableRowsToShow[$this->selectedElement])) {
for ($i = 0; $i < sizeof($this->tableRowsToShow[$this->selectedElement]); $i++) {
for ($i = 0; $i < count($this->tableRowsToShow[$this->selectedElement]); $i++) {
$script .= 'document.getElementById(\'' . $this->tableRowsToShow[$this->selectedElement][$i] . '\')?.closest(\'' . $selector . '\').classList.remove(\'hidden\');' . "\n";
}
}
if (isset($this->tableRowsToHide[$this->selectedElement])) {
for ($i = 0; $i < sizeof($this->tableRowsToHide[$this->selectedElement]); $i++) {
for ($i = 0; $i < count($this->tableRowsToHide[$this->selectedElement]); $i++) {
$script .= 'document.getElementById(\'' . $this->tableRowsToHide[$this->selectedElement][$i] . '\')?.closest(\'' . $selector . '\').classList.add(\'hidden\');' . "\n";
}
}
@ -2049,12 +2036,7 @@ class htmlInputCheckbox extends htmlElement {
*/
function generateHTML($module, $input, $values, $restricted, $scope) {
if (isset($values[$this->name])) {
if ($values[$this->name][0] == 'true') {
$this->checked = true;
}
else {
$this->checked = false;
}
$this->checked = ($values[$this->name][0] == 'true');
}
$checked = '';
if ($this->checked) {
@ -2076,34 +2058,34 @@ class htmlInputCheckbox extends htmlElement {
$onChange = '';
$script = '';
$selector = $this->getShowHideSelector();
if ((sizeof($this->tableRowsToShow) > 0) || (sizeof($this->tableRowsToHide) > 0)) {
if ((count($this->tableRowsToShow) > 0) || (count($this->tableRowsToHide) > 0)) {
// build onChange listener
$onChange .= 'if (document.querySelector(\'#' . $this->name . ':checked\') !== null) {';
for ($i = 0; $i < sizeof($this->tableRowsToShow); $i++) {
for ($i = 0; $i < count($this->tableRowsToShow); $i++) {
$onChange .= 'document.getElementById(\'' . $this->tableRowsToShow[$i] . '\')?.closest(\'' . $selector . '\').classList.remove(\'hidden\');';
}
for ($i = 0; $i < sizeof($this->tableRowsToHide); $i++) {
for ($i = 0; $i < count($this->tableRowsToHide); $i++) {
$onChange .= 'document.getElementById(\'' . $this->tableRowsToHide[$i] . '\')?.closest(\'' . $selector . '\').classList.add(\'hidden\');';
}
$onChange .= '}';
$onChange .= 'else {';
for ($i = 0; $i < sizeof($this->tableRowsToShow); $i++) {
for ($i = 0; $i < count($this->tableRowsToShow); $i++) {
$onChange .= 'document.getElementById(\'' . $this->tableRowsToShow[$i] . '\')?.closest(\'' . $selector . '\').classList.add(\'hidden\');';
}
for ($i = 0; $i < sizeof($this->tableRowsToHide); $i++) {
for ($i = 0; $i < count($this->tableRowsToHide); $i++) {
$onChange .= 'document.getElementById(\'' . $this->tableRowsToHide[$i] . '\')?.closest(\'' . $selector . '\').classList.remove(\'hidden\');';
}
$onChange .= '};';
// build script to set initial state
$script .= '<script type="text/javascript">window.lam.utility.documentReady(function() {';
for ($i = 0; $i < sizeof($this->tableRowsToShow); $i++) {
for ($i = 0; $i < count($this->tableRowsToShow); $i++) {
$classType = 'add';
if ($this->checked) {
$classType = 'remove';
}
$script .= 'document.getElementById(\'' . $this->tableRowsToShow[$i] . '\')?.closest(\'' . $selector . '\').classList.' . $classType . '(\'hidden\');';
}
for ($i = 0; $i < sizeof($this->tableRowsToHide); $i++) {
for ($i = 0; $i < count($this->tableRowsToHide); $i++) {
$classType = 'remove';
if ($this->checked) {
$classType = 'add';
@ -2113,34 +2095,34 @@ class htmlInputCheckbox extends htmlElement {
$script .= '});</script>';
}
// build Java script to enable/disable elements
if ((sizeof($this->elementsToEnable) > 0) || (sizeof($this->elementsToDisable) > 0)) {
if ((count($this->elementsToEnable) > 0) || (count($this->elementsToDisable) > 0)) {
// build onChange listener
$onChange .= 'if (document.querySelector(\'#' . $this->name . ':checked\') !== null) {';
for ($i = 0; $i < sizeof($this->elementsToEnable); $i++) {
for ($i = 0; $i < count($this->elementsToEnable); $i++) {
$onChange .= 'document.getElementById(\'' . $this->elementsToEnable[$i] . '\').disabled = false;';
}
for ($i = 0; $i < sizeof($this->elementsToDisable); $i++) {
for ($i = 0; $i < count($this->elementsToDisable); $i++) {
$onChange .= 'document.getElementById(\'' . $this->elementsToDisable[$i] . '\').disabled = true;';
}
$onChange .= '}';
$onChange .= 'else {';
for ($i = 0; $i < sizeof($this->elementsToEnable); $i++) {
for ($i = 0; $i < count($this->elementsToEnable); $i++) {
$onChange .= 'document.getElementById(\'' . $this->elementsToEnable[$i] . '\').disabled = true;';
}
for ($i = 0; $i < sizeof($this->elementsToDisable); $i++) {
for ($i = 0; $i < count($this->elementsToDisable); $i++) {
$onChange .= 'document.getElementById(\'' . $this->elementsToDisable[$i] . '\').disabled = false;';
}
$onChange .= '};';
// build script to set initial state
$script .= '<script type="text/javascript">window.lam.utility.documentReady(function() {';
for ($i = 0; $i < sizeof($this->elementsToEnable); $i++) {
for ($i = 0; $i < count($this->elementsToEnable); $i++) {
$classType = 'true';
if ($this->checked) {
$classType = 'false';
}
$script .= 'document.getElementById(\'' . $this->elementsToEnable[$i] . '\').disabled = ' . $classType . ';';
}
for ($i = 0; $i < sizeof($this->elementsToDisable); $i++) {
for ($i = 0; $i < count($this->elementsToDisable); $i++) {
$classType = 'false';
if ($this->checked) {
$classType = 'true';
@ -2825,7 +2807,7 @@ class htmlStatusMessage extends htmlElement {
* @return htmlStatusMessage
*/
public static function fromParamArray($params) {
if (sizeof($params) < 2) {
if (count($params) < 2) {
throw new BadMethodCallException("Invalid parameter count");
}
@ -3121,7 +3103,7 @@ class htmlLink extends htmlElement {
$idAttr = ' id="' . $this->id . '"';
}
$classAttr = '';
if (sizeof($this->cssClasses) > 0) {
if (count($this->cssClasses) > 0) {
$classAttr = ' class="' . implode(' ', $this->cssClasses) . '"';
}
echo '<a href="' . $this->target . '"' . $idAttr . $classAttr . $title . $targetWindow . $onClick . $onMouseOver . $this->getDataAttributesAsString() . '>' . $image . $text . '</a>';
@ -3280,7 +3262,7 @@ class htmlGroup extends htmlElement {
*/
function generateHTML($module, $input, $values, $restricted, $scope) {
$return = [];
for ($i = 0; $i < sizeof($this->subelements); $i++) {
for ($i = 0; $i < count($this->subelements); $i++) {
$return = array_merge($return, $this->subelements[$i]->generateHTML($module, $input, $values, $restricted, $scope));
}
return $return;
@ -3367,7 +3349,7 @@ class htmlDiv extends htmlElement {
$idValue = ' id="' . $this->id . '"';
}
$classesValue = '';
if (($this->cssClasses != null) && (sizeof($this->cssClasses) > 0)) {
if (($this->cssClasses != null) && (count($this->cssClasses) > 0)) {
$classesValue = ' class="' . implode(' ', $this->cssClasses) . '"';
}
echo '<div' . $idValue . $classesValue . $this->getDataAttributesAsString() . '>';
@ -3418,7 +3400,7 @@ class htmlSpan extends htmlElement {
function generateHTML($module, $input, $values, $restricted, $scope) {
$return = [];
$classesValue = '';
if (($this->cssClasses != null) && (sizeof($this->cssClasses) > 0)) {
if (($this->cssClasses != null) && (count($this->cssClasses) > 0)) {
$classesValue = ' class="' . implode(' ', $this->cssClasses) . '"';
}
$onclickHandler = '';
@ -3653,7 +3635,7 @@ class htmlSortableList extends htmlElement {
* @return array List of input field names and their type (name => type)
*/
function generateHTML($module, $input, $values, $restricted, $scope) {
if (sizeof($this->elements) == 0) {
if (count($this->elements) == 0) {
return [];
}
$return = [];
@ -3662,7 +3644,7 @@ class htmlSortableList extends htmlElement {
$classesValue = ' class="' . implode(' ', $this->cssClasses) . '"';
}
echo '<ul' . $classesValue . ' id="' . $this->id . '">';
for ($i = 0; $i < sizeof($this->elements); $i++) {
for ($i = 0; $i < count($this->elements); $i++) {
$element = $this->elements[$i];
echo '<li data-position-orig="' . $i . '">';
echo '<span class="lam-sortable-list-icon"></span>';
@ -3818,7 +3800,6 @@ class htmlResponsiveRow extends htmlElement {
* @param htmlElement $field field element if this is a simple label+field row
*/
public function __construct($label = null, $field = null) {
$this->cells = [];
if ($label != null) {
$this->addLabel($label);
}
@ -3944,7 +3925,7 @@ class htmlResponsiveRow extends htmlElement {
* @return int cell count
*/
public function getCellCount(): int {
return sizeof($this->cells);
return count($this->cells);
}
}
@ -4604,7 +4585,7 @@ class htmlResponsiveTable extends htmlElement {
echo '</tr>';
echo '</thead>';
echo '<tbody>';
$titleCount = sizeof($this->titles);
$titleCount = count($this->titles);
$counter = 0;
foreach ($this->data as $row) {
$cssClass = '';

View file

@ -288,13 +288,13 @@ class ImageManipulatorGd implements ImageManipulator {
$thumbHeight = $this->getHeight();
if ($thumbWidth > $width) {
$factor = $width / $thumbWidth;
$thumbWidth = $thumbWidth * $factor;
$thumbHeight = $thumbHeight * $factor;
$thumbWidth *= $factor;
$thumbHeight *= $factor;
}
if ($thumbHeight > $height) {
$factor = $height / $thumbHeight;
$thumbWidth = $thumbWidth * $factor;
$thumbHeight = $thumbHeight * $factor;
$thumbWidth *= $factor;
$thumbHeight *= $factor;
}
$thumbnail = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled(
@ -318,7 +318,7 @@ class ImageManipulatorGd implements ImageManipulator {
if ($this->type == IMAGETYPE_JPEG) {
imagejpeg($this->image);
}
else if ($this->type == IMAGETYPE_PNG) {
elseif ($this->type == IMAGETYPE_PNG) {
imagepng($this->image);
}
$output = ob_get_contents();

View file

@ -34,7 +34,7 @@ use LAMException;
*/
/** LDAP handle */
include_once('ldap.inc');
include_once(__DIR__ . '/ldap.inc');
/**
* Imports LDIF files.
@ -84,7 +84,7 @@ class Importer {
throw new LAMException(_('Invalid data'), htmlspecialchars($line));
}
else {
$currentEntry[sizeof($currentEntry) - 1] .= substr($line, 1);
$currentEntry[count($currentEntry) - 1] .= substr($line, 1);
}
}
elseif ($line === '-') {
@ -92,7 +92,7 @@ class Importer {
}
else {
$parts = explode(':', $line, 2);
if (sizeof($parts) < 2) {
if (count($parts) < 2) {
throw new LAMException(_('Invalid data'), htmlspecialchars($line));
}
$currentEntry[] = $line;
@ -181,7 +181,7 @@ class Importer {
];
return json_encode($status);
}
$progress = (sizeof($_SESSION[Importer::SESSION_KEY_TASKS]) / $_SESSION[Importer::SESSION_KEY_COUNT]) * 100.0;
$progress = (count($_SESSION[Importer::SESSION_KEY_TASKS]) / $_SESSION[Importer::SESSION_KEY_COUNT]) * 100.0;
$progress = floor(100 - $progress);
$status = [
Importer::STATUS => 'inProgress',
@ -216,18 +216,18 @@ class Importer {
*/
private function convertToTasks($entries) {
$tasks = [];
$count = sizeof($entries);
$count = count($entries);
for ($i = 0; $i < $count; $i++) {
$entry = $entries[$i];
$firstParts = explode(':', $entry[0], 2);
if ($firstParts[Importer::KEY] == 'version') {
if ($firstParts[Importer::KEY] === 'version') {
if ($i > 0) {
// allow version only as first chunk
throw new LAMException(_('Invalid data'), _('Duplicate version entry found.'));
}
$this->processVersion($entry);
}
elseif ($firstParts[Importer::KEY] == 'dn') {
elseif ($firstParts[Importer::KEY] === 'dn') {
$tasks[] = $this->processDnEntry($entry);
}
else {
@ -245,7 +245,7 @@ class Importer {
*/
private function processVersion($entry) {
$keyValue = $this->getLineKeyValue($entry[0]);
if (($keyValue[Importer::VALUE] != '1') || (sizeof($entry) > 1)) {
if (($keyValue[Importer::VALUE] != '1') || (count($entry) > 1)) {
$escapedLines = array_map(htmlspecialchars(...), $entry);
throw new LAMException(_('LDIF import only supports version 1'), implode('<br>', $escapedLines));
}
@ -302,7 +302,7 @@ class Importer {
}
$subtasks = [];
$currentLines = [];
$linesCount = sizeof($entry);
$linesCount = count($entry);
for ($i = 0; $i < $linesCount; $i++) {
$line = $entry[$i];
if ($line === '-') {
@ -327,7 +327,7 @@ class Importer {
* @throws LAMException syntax error
*/
private function createModRdnTask($dn, $entry) {
if (sizeof($entry) !== 2) {
if (count($entry) !== 2) {
throw new LAMException(_('Invalid data'), htmlspecialchars($dn));
}
$newRdnData = $this->getLineKeyValue($entry[0]);
@ -400,7 +400,7 @@ class Importer {
*/
private function getLineKeyValue($line) {
$parts = explode(':', $line, 2);
if (sizeof($parts) !== 2) {
if (count($parts) !== 2) {
throw new LAMException(_('Invalid data'), htmlspecialchars($line));
}
if (str_starts_with($parts[Importer::VALUE], ':')) {

View file

@ -255,7 +255,8 @@ class Ldap {
}
$rootDse = ldapGetDN('', ['*']);
logNewMessage(LOG_DEBUG, 'Root DSE: ' . print_r($rootDse, true));
return isset($rootDse['domaincontrollerfunctionality']) || isset($rootDse['forestfunctionality']);
$this->isActiveDirectory = isset($rootDse['domaincontrollerfunctionality']) || isset($rootDse['forestfunctionality']);
return $this->isActiveDirectory;
}
}

View file

@ -165,18 +165,18 @@ class lamList {
* Reads the list options from the cookie value.
*/
private function listReadOptionsFromCookie() {
if ((sizeof($this->configOptions) > 0)
if ((count($this->configOptions) > 0)
&& isset($_COOKIE["ListOptions_" . $this->type->getId()])) {
$cookieValue = $_COOKIE["ListOptions_" . $this->type->getId()];
$valueParts = explode(";", $cookieValue);
$values = [];
for ($i = 0; $i < sizeof($valueParts); $i++) {
for ($i = 0; $i < count($valueParts); $i++) {
$key_value = explode('=', $valueParts[$i]);
if (sizeof($key_value) == 2) {
if (count($key_value) == 2) {
$values[$key_value[0]] = $key_value[1];
}
}
for ($i = 0; $i < sizeof($this->configOptions); $i++) {
for ($i = 0; $i < count($this->configOptions); $i++) {
if (isset($values[$this->configOptions[$i]->getID()])) {
$this->configOptions[$i]->setValue($values[$this->configOptions[$i]->getID()]);
}
@ -207,7 +207,7 @@ class lamList {
// local filtering
$this->applyLocalFilters();
// sort rows by sort column
if (isset($this->entries)) {
if ($this->entries !== null) {
$this->listCreateSortMapping($this->entries);
}
// insert HTML fragment from listDoPost
@ -219,18 +219,18 @@ class lamList {
// show form
echo "<form action=\"list.php?type=" . $this->type->getId() . "&amp;norefresh=true\" method=\"post\">\n";
// draw account list if accounts were found
if (sizeof($this->entries) > 0) {
if (count($this->entries) > 0) {
// buttons
$this->listPrintButtons(false);
// navigation bar
$this->listDrawNavigationBar(sizeof($this->entries));
$this->listDrawNavigationBar(count($this->entries));
$this->printAccountTable($this->entries);
}
else {
// buttons
$this->listPrintButtons(true);
// navigation bar
$this->listDrawNavigationBar(sizeof($this->entries));
$this->listDrawNavigationBar(count($this->entries));
$accounts = [];
$this->printAccountTable($accounts);
echo "</table><br>\n";
@ -250,7 +250,7 @@ class lamList {
$this->filters = [];
if (!isset($_POST['clear_filter'])) {
// build filter array
for ($i = 0; $i < sizeof($this->attrArray); $i++) {
for ($i = 0; $i < count($this->attrArray); $i++) {
$foundFilter = null;
if (isset($_GET["filter" . strtolower($this->attrArray[$i])])) {
$foundFilter = $_GET["filter" . strtolower($this->attrArray[$i])];
@ -293,8 +293,8 @@ class lamList {
}
$toSort = [];
$col = $this->sortColumn;
$size = sizeof($info);
if ($this->sortColumn != 'dn') {
$size = count($info);
if ($this->sortColumn !== 'dn') {
for ($i = 0; $i < $size; $i++) {
// sort by first attribute with name $sort
$toSort[] = &$info[$i][$col][0];
@ -308,13 +308,13 @@ class lamList {
natcasesort($toSort);
$sortResult = [];
if ($this->sortDirection == 1) {
foreach ($toSort as $orig => $val) {
foreach (array_keys($toSort) as $orig) {
$sortResult[] = $orig;
}
}
else {
$counter = sizeof($toSort);
foreach ($toSort as $orig => $val) {
$counter = count($toSort);
foreach (array_keys($toSort) as $orig) {
$counter--;
$sortResult[$counter] = $orig;
}
@ -500,7 +500,7 @@ class lamList {
$filterButton = new htmlButton('apply_filter', 'filter.svg', true);
$filterButton->setTitle(_("Here you can input simple filter expressions (e.g. 'value' or 'v*'). The filter is case-insensitive."));
$actionElement->addElement($filterButton);
if (sizeof($this->filters) > 0) {
if (count($this->filters) > 0) {
$clearFilterButton = new htmlButton('clear_filter', 'del.svg', true);
$clearFilterButton->setTitle(_('Clear filter'));
$actionElement->addElement($clearFilterButton);
@ -578,16 +578,11 @@ class lamList {
private function addDataElements(&$data, &$info, &$onClickEvents, &$onDoubleClickEvents) {
// calculate which rows to show
$table_begin = ($this->page - 1) * $this->maxPageEntries;
if (($this->page * $this->maxPageEntries) > sizeof($info)) {
$table_end = sizeof($info);
}
else {
$table_end = ($this->page * $this->maxPageEntries);
}
$table_end = ($this->page * $this->maxPageEntries) > count($info) ? count($info) : $this->page * $this->maxPageEntries;
// get sort mapping
if (empty($this->sortMapping)) {
$this->sortMapping = [];
$infoSize = sizeof($info);
$infoSize = count($info);
for ($i = 0; $i < $infoSize; $i++) {
$this->sortMapping[$i] = $i;
}
@ -680,7 +675,7 @@ class lamList {
}
// additional tools
$tools = $this->getAdditionalTools();
for ($i = 0; $i < sizeof($tools); $i++) {
for ($i = 0; $i < count($tools); $i++) {
$toolLink = new htmlLink('', $tools[$i]->getLinkTarget() . "?type=" . $this->type->getId() . "&DN='" . rawurlencode($account['dn']) . "'", '../../graphics/' . $tools[$i]->getImage());
$toolLink->setTitle($tools[$i]->getName());
$toolLink->setCSSClasses(['lam-margin-smaller', 'icon']);
@ -751,7 +746,7 @@ class lamList {
return new htmlOutputText(getAbstractDN($entry[$attribute]));
}
// print all attribute entries separated by "; "
if (isset($entry[$attribute]) && sizeof($entry[$attribute]) > 0) {
if (isset($entry[$attribute]) && count($entry[$attribute]) > 0) {
if (is_array($entry[$attribute])) {
// sort array
sort($entry[$attribute]);
@ -761,6 +756,7 @@ class lamList {
return new htmlOutputText($entry[$attribute]);
}
}
return null;
}
/**
@ -788,13 +784,13 @@ class lamList {
$accounts = array_keys($_POST, "on");
// build DN list
$_SESSION['delete_dn'] = [];
for ($i = 0; $i < sizeof($accounts); $i++) {
for ($i = 0; $i < count($accounts); $i++) {
if ($accounts[$i] == 'tableSelectAll') {
continue;
}
$_SESSION['delete_dn'][] = base64_decode($accounts[$i]);
}
if (sizeof($accounts) > 0) {
if ($accounts !== []) {
metaRefresh("../delete.php?type=" . $this->type->getId());
exit;
}
@ -806,10 +802,10 @@ class lamList {
}
}
// PDF button
foreach ($_POST as $key => $value) {
foreach (array_keys($_POST) as $key) {
if (strpos($key, 'createPDF_') > -1) {
$parts = explode("_", $key);
if (sizeof($parts) == 2) {
if (count($parts) == 2) {
$this->showPDFPage($parts[1]);
exit;
}
@ -834,27 +830,27 @@ class lamList {
$accounts = array_keys($_POST, "on");
$list = [];
// load accounts from LDAP
for ($i = 0; $i < sizeof($accounts); $i++) {
for ($i = 0; $i < count($accounts); $i++) {
$_SESSION["accountPDF-$i"] = new accountContainer($this->type, "accountPDF-$i");
$_SESSION["accountPDF-$i"]->load_account(base64_decode($accounts[$i]));
$list[$i] = $_SESSION["accountPDF-$i"];
}
if (sizeof($list) > 0) {
if ($list !== []) {
$fileName = createModulePDF($list, $pdfStruct, $pdfFont);
for ($i = 0; $i < sizeof($accounts); $i++) {
for ($i = 0; $i < count($accounts); $i++) {
unset($_SESSION["accountPDF-$i"]);
}
}
} // create for all accounts
elseif ($option == 'ALL') {
$list = [];
$entriesCount = sizeof($this->entries);
$entriesCount = count($this->entries);
for ($i = 0; $i < $entriesCount; $i++) {
$_SESSION["accountPDF-$i"] = new accountContainer($this->type, "accountPDF-$i");
$_SESSION["accountPDF-$i"]->load_account($this->entries[$i]['dn']);
$list[$i] = $_SESSION["accountPDF-$i"];
}
if (sizeof($list) > 0) {
if ($list !== []) {
$fileName = createModulePDF($list, $pdfStruct, $pdfFont);
for ($i = 0; $i < $entriesCount; $i++) {
// clean session
@ -876,9 +872,9 @@ class lamList {
}
}
// check if back from configuration page
if ((sizeof($this->configOptions) > 0) && isset($_POST['saveConfigOptions'])) {
if ((count($this->configOptions) > 0) && isset($_POST['saveConfigOptions'])) {
$cookieValue = '';
for ($i = 0; $i < sizeof($this->configOptions); $i++) {
for ($i = 0; $i < count($this->configOptions); $i++) {
$this->configOptions[$i]->fillFromPostData();
$cookieValue .= $this->configOptions[$i]->getID() . "=" . $this->configOptions[$i]->getValue() . ';';
}
@ -944,8 +940,8 @@ class lamList {
else {
$radioOptions = [
getAbstractDN(base64_decode($id)) => 'DN',
sprintf(_('All selected accounts (%s)'), sizeof($selAccounts)) => 'SELECTED',
sprintf(_('All accounts (%s)'), sizeof($this->entries)) => 'ALL'
sprintf(_('All selected accounts (%s)'), count($selAccounts)) => 'SELECTED',
sprintf(_('All accounts (%s)'), count($this->entries)) => 'ALL'
];
$container->addField(new htmlRadio('createFor', $radioOptions, 'DN'));
}
@ -958,7 +954,7 @@ class lamList {
$buttonContainer->addElement(new htmlButton('createPDFCancel', _('Cancel')));
$container->addField($buttonContainer);
// hidden inputs for selected accounts
for ($i = 0; $i < sizeof($selAccounts); $i++) {
for ($i = 0; $i < count($selAccounts); $i++) {
$container->add(new htmlHiddenInput($selAccounts[$i], 'on'), 0);
}
$container->add(new htmlHiddenInput('clickedAccount', $id), 0);
@ -976,9 +972,9 @@ class lamList {
*/
protected function listShowOUSelection() {
$group = new htmlGroup();
if (sizeof($this->possibleSuffixes) > 1) {
if (count($this->possibleSuffixes) > 1) {
$suffixList = [];
for ($i = 0; $i < sizeof($this->possibleSuffixes); $i++) {
for ($i = 0; $i < count($this->possibleSuffixes); $i++) {
$suffixList[getAbstractDN($this->possibleSuffixes[$i])] = $this->possibleSuffixes[$i];
}
$suffixSelect = new htmlSelect('suffix', $suffixList, [$this->suffix]);
@ -1057,7 +1053,7 @@ class lamList {
* Prints the header part of the page.
*/
private function printHeader() {
include 'adminHeader.inc';
include __DIR__ . '/adminHeader.inc';
$row = new htmlResponsiveRow();
$row->setCSSClasses(['maxrow']);
$row->add(new htmlTitle($this->type->getAlias()));
@ -1077,7 +1073,7 @@ class lamList {
*/
private function printFooter() {
$this->printFooterContent();
include 'adminFooter.inc';
include __DIR__ . '/adminFooter.inc';
}
/**
@ -1125,12 +1121,7 @@ class lamList {
exit();
}
// get current page
if (!empty($_GET["page"])) {
$this->page = $_GET["page"];
}
else {
$this->page = 1;
}
$this->page = empty($_GET["page"]) ? 1 : $_GET["page"];
// generate attribute-description table
$temp_array = $this->listGetAttributeDescriptionList();
$this->attrArray = array_keys($temp_array); // list of LDAP attributes to show
@ -1200,7 +1191,7 @@ class lamList {
$filter = "(&" . $module_filter . $this->buildLDAPAttributeFilter() . ")";
$attrs = $this->attrArray;
// remove virtual attributes from list
for ($i = 0; $i < sizeof($attrs); $i++) {
for ($i = 0; $i < count($attrs); $i++) {
if (str_starts_with($attrs[$i], self::VIRTUAL_ATTRIBUTE_PREFIX)) {
unset($attrs[$i]);
}
@ -1208,7 +1199,7 @@ class lamList {
$attrs = array_values($attrs);
// include additional attributes
$additionalAttrs = $this->getAdditionalLDAPAttributesToRead();
for ($i = 0; $i < sizeof($additionalAttrs); $i++) {
for ($i = 0; $i < count($additionalAttrs); $i++) {
if (!in_array_ignore_case($additionalAttrs[$i], $attrs)) {
$attrs[] = $additionalAttrs[$i];
}
@ -1255,7 +1246,7 @@ class lamList {
$filterExpression = substr($filterExpression, 0, -1);
}
elseif (strrpos($filter, '*') !== (strlen($filter) - 1)) {
$filterExpression = $filterExpression . '*';
$filterExpression .= '*';
}
$text .= '(' . $attr . '=' . $filterExpression . ')';
}
@ -1314,10 +1305,8 @@ class lamList {
$toFilter[] = $index;
}
}
else {
if (!$this->isFilterMatching($data, $filterAttribute, $regex)) {
$toFilter[] = $index;
}
elseif (!$this->isFilterMatching($data, $filterAttribute, $regex)) {
$toFilter[] = $index;
}
}
}
@ -1416,7 +1405,7 @@ class lamList {
echo "<form id=\"settingsDialogForm\" action=\"list.php?type=" . $this->type->getId() . "&amp;norefresh=true\" method=\"post\">\n";
$configContainer = new htmlResponsiveRow();
for ($i = 0; $i < sizeof($this->configOptions); $i++) {
for ($i = 0; $i < count($this->configOptions); $i++) {
$configContainer->add($this->configOptions[$i]->getMetaHTML(), 12);
}
$configContainer->add(new htmlHiddenInput('saveConfigOptions', 'ok'), 12);
@ -1434,7 +1423,7 @@ class lamList {
* @param String $ID ID
*/
protected function listGetConfigOptionByID($ID) {
for ($i = 0; $i < sizeof($this->configOptions); $i++) {
for ($i = 0; $i < count($this->configOptions); $i++) {
if ($this->configOptions[$i]->getID() === $ID) {
return $this->configOptions[$i];
}
@ -1485,7 +1474,7 @@ class lamList {
StatusMessage('WARN', _('Please do not edit multiple accounts in parallel in multiple browser tabs.'));
}
if (isset($_SESSION['listRedirectMessages'])) {
for ($i = 0; $i < sizeof($_SESSION['listRedirectMessages']); $i++) {
for ($i = 0; $i < count($_SESSION['listRedirectMessages']); $i++) {
call_user_func_array(StatusMessage(...), $_SESSION['listRedirectMessages'][$i]);
}
unset($_SESSION['listRedirectMessages']);
@ -1496,7 +1485,7 @@ class lamList {
* Injects values for the virtual account status attribute to make it sortable.
*/
private function injectAccountStatusAttribute() {
$entryCount = sizeof($this->ldapEntries);
$entryCount = count($this->ldapEntries);
for ($i = 0; $i < $entryCount; $i++) {
$accountStatus = AccountStatus::fromAttributes($this->type, $this->ldapEntries[$i]);
$status = self::FILTER_UNLOCKED;

View file

@ -63,7 +63,7 @@ $modulesINC_dirname = substr(__FILE__, 0, strlen(__FILE__) - 12) . "/modules";
$modulesINC_dir = dir($modulesINC_dirname);
// get module names.
while ($entry = $modulesINC_dir->read()) {
if ((substr($entry, strlen($entry) - 4, 4) == '.inc') && is_file($modulesINC_dirname . '/' . $entry)) {
if ((substr($entry, strlen($entry) - 4, 4) === '.inc') && is_file($modulesINC_dirname . '/' . $entry)) {
include_once($modulesINC_dirname . '/' . $entry);
}
}
@ -107,7 +107,7 @@ function get_ldap_filter($typeId) {
$mods = $_SESSION['config']->get_AccountModules($typeId);
$filters = ['or' => [], 'and' => []];
$orFilter = '';
for ($i = 0; $i < sizeof($mods); $i++) {
for ($i = 0; $i < count($mods); $i++) {
$module = moduleCache::getModule($mods[$i], $type->getScope());
$modinfo = $module->get_ldap_filter($typeId);
if (isset($modinfo['or'])) {
@ -118,10 +118,10 @@ function get_ldap_filter($typeId) {
}
}
// build OR filter
if (sizeof($filters['or']) == 1) {
if (count($filters['or']) == 1) {
$orFilter = $filters['or'][0];
}
elseif (sizeof($filters['or']) > 1) {
elseif (count($filters['or']) > 1) {
$orFilter = "(|" . implode("", $filters['or']) . ")";
}
// add built OR filter to AND filters
@ -138,14 +138,7 @@ function get_ldap_filter($typeId) {
$filters['and'][] = '(' . $typeSettings['filter_' . $typeId] . ')';
}
}
// collapse AND filters
$finalFilter = '';
if (sizeof($filters['and']) < 2) {
$finalFilter = $filters['and'][0];
}
else {
$finalFilter = "(&" . implode("", $filters['and']) . ")";
}
$finalFilter = (count($filters['and']) < 2) ? $filters['and'][0] : "(&" . implode("", $filters['and']) . ")";
$loginData = $_SESSION['ldap']->getUserName();
return str_replace('@@LOGIN_DN@@', $loginData, $finalFilter);
}
@ -167,13 +160,13 @@ function getRDNAttributes($typeId, $selectedModules = null) {
$attrs_low = [];
$attrs_normal = [];
$attrs_high = [];
for ($i = 0; $i < sizeof($mods); $i++) {
for ($i = 0; $i < count($mods); $i++) {
// get list of attributes
$module = moduleCache::getModule($mods[$i], \LAM\TYPES\getScopeFromTypeId($typeId));
$attrs = $module->get_RDNAttributes($typeId);
$keys = array_keys($attrs);
// sort attributes
for ($k = 0; $k < sizeof($keys); $k++) {
for ($k = 0; $k < count($keys); $k++) {
switch ($attrs[$keys[$k]]) {
case "normal":
$attrs_normal[] = $keys[$k];
@ -190,12 +183,12 @@ function getRDNAttributes($typeId, $selectedModules = null) {
}
// merge arrays
$return = array_values(array_unique($attrs_high));
for ($i = 0; $i < sizeof($attrs_normal); $i++) {
for ($i = 0; $i < count($attrs_normal); $i++) {
if (!in_array($attrs_normal[$i], $return)) {
$return[] = $attrs_normal[$i];
}
}
for ($i = 0; $i < sizeof($attrs_low); $i++) {
for ($i = 0; $i < count($attrs_low); $i++) {
if (!in_array($attrs_low[$i], $return)) {
$return[] = $attrs_low[$i];
}
@ -215,7 +208,7 @@ function getRDNAttributes($typeId, $selectedModules = null) {
*/
function getModulesDependencies($scope) {
$mods = getAvailableModules($scope);
for ($i = 0; $i < sizeof($mods); $i++) {
for ($i = 0; $i < count($mods); $i++) {
$module = moduleCache::getModule($mods[$i], $scope);
$return[$mods[$i]] = $module->get_dependencies();
}
@ -233,14 +226,14 @@ function getModulesDependencies($scope) {
*/
function check_module_depends($selected, $deps) {
$ret = [];
for ($m = 0; $m < sizeof($selected); $m++) { // check selected modules
for ($i = 0; $i < sizeof($deps[$selected[$m]]['depends']); $i++) { // check dependencies of module
for ($m = 0; $m < count($selected); $m++) { // check selected modules
for ($i = 0; $i < count($deps[$selected[$m]]['depends']); $i++) { // check dependencies of module
// check if we have OR-combined modules
if (is_array($deps[$selected[$m]]['depends'][$i])) {
// one of the elements is needed
$found = false;
$depends = $deps[$selected[$m]]['depends'][$i];
for ($d = 0; $d < sizeof($depends); $d++) {
for ($d = 0; $d < count($depends); $d++) {
if (in_array($depends[$d], $selected)) {
$found = true;
break;
@ -251,16 +244,14 @@ function check_module_depends($selected, $deps) {
$ret[] = [$selected[$m], implode(" || ", $depends)];
}
}
else {
elseif (!in_array($deps[$selected[$m]]['depends'][$i], $selected)) {
// single dependency
if (!in_array($deps[$selected[$m]]['depends'][$i], $selected)) {
// missing dependency, add to return value
$ret[] = [$selected[$m], $deps[$selected[$m]]['depends'][$i]];
}
// missing dependency, add to return value
$ret[] = [$selected[$m], $deps[$selected[$m]]['depends'][$i]];
}
}
}
if (sizeof($ret) > 0) {
if ($ret !== []) {
return $ret;
}
return false;
@ -276,14 +267,14 @@ function check_module_depends($selected, $deps) {
*/
function check_module_conflicts($selected, $deps) {
$ret = [];
for ($m = 0; $m < sizeof($selected); $m++) {
for ($i = 0; $i < sizeof($deps[$selected[$m]]['conflicts']); $i++) {
for ($m = 0; $m < count($selected); $m++) {
for ($i = 0; $i < count($deps[$selected[$m]]['conflicts']); $i++) {
if (in_array($deps[$selected[$m]]['conflicts'][$i], $selected)) {
$ret[] = [$selected[$m], $deps[$selected[$m]]['conflicts'][$i]];
}
}
}
if (sizeof($ret) > 0) {
if ($ret !== []) {
return $ret;
}
return false;
@ -302,7 +293,7 @@ function getAvailableModules($scope, $mustSupportAdminInterface = false) {
$return = [];
// get module names.
while ($entry = $dir->read()) {
if ((substr($entry, strlen($entry) - 4, 4) == '.inc') && is_file($dirname . '/' . $entry)) {
if ((substr($entry, strlen($entry) - 4, 4) === '.inc') && is_file($dirname . '/' . $entry)) {
$entry = substr($entry, 0, strpos($entry, '.'));
$temp = moduleCache::getModule($entry, $scope);
if ($temp === null) {
@ -330,7 +321,7 @@ function getAllModules(): array {
$return = [];
// get module names.
while ($entry = $dir->read()) {
if ((substr($entry, strlen($entry) - 4, 4) == '.inc') && is_file($dirname . '/' . $entry)) {
if ((substr($entry, strlen($entry) - 4, 4) === '.inc') && is_file($dirname . '/' . $entry)) {
$entry = substr($entry, 0, strpos($entry, '.'));
$return[] = new $entry(null);
}
@ -349,7 +340,7 @@ function getProfileOptions($typeId) {
$type = $typeManager->getConfiguredType($typeId);
$mods = $type->getModules();
$return = [];
for ($i = 0; $i < sizeof($mods); $i++) {
for ($i = 0; $i < count($mods); $i++) {
$module = moduleCache::getModule($mods[$i], $type->getScope());
$moduleOptions = $module->get_profileOptions($typeId);
if ($moduleOptions !== null) {
@ -371,7 +362,7 @@ function checkProfileOptions($typeId, $options) {
$type = $typeManager->getConfiguredType($typeId);
$mods = $type->getModules();
$return = [];
for ($i = 0; $i < sizeof($mods); $i++) {
for ($i = 0; $i < count($mods); $i++) {
$module = moduleCache::getModule($mods[$i], $type->getScope());
$temp = $module->check_profileOptions($options, $type->getId());
$return = array_merge($return, $temp);
@ -455,7 +446,7 @@ function getAvailablePDFFields($typeId) {
$return[$moduleName] = [];
if (is_array($fields)) {
foreach ($fields as $fieldID => $fieldLabel) {
if (is_integer($fieldID)) {
if (is_int($fieldID)) {
// support old PDF field list which did not contain a label
$return[$moduleName][$fieldLabel] = $fieldLabel;
}
@ -488,7 +479,7 @@ function getAvailablePDFFields($typeId) {
*/
function getUploadColumns(&$type, $selectedModules) {
$return = [];
for ($i = 0; $i < sizeof($selectedModules); $i++) {
for ($i = 0; $i < count($selectedModules); $i++) {
$module = moduleCache::getModule($selectedModules[$i], $type->getScope());
$return[$selectedModules[$i]] = $module->get_uploadColumns($selectedModules, $type);
}
@ -513,14 +504,14 @@ function buildUploadAccounts($type, $data, $ids, $selectedModules, htmlResponsiv
$ordered = [];
$predepends = [];
// get dependencies
for ($i = 0; $i < sizeof($unOrdered); $i++) {
for ($i = 0; $i < count($unOrdered); $i++) {
$mod = moduleCache::getModule($unOrdered[$i], $type->getScope());
logNewMessage(LOG_DEBUG, 'Checking dependencies for ' . $unOrdered[$i]);
$predepends[$unOrdered[$i]] = $mod->get_uploadPreDepends();
}
// first all modules without predepends can be ordered
for ($i = 0; $i < sizeof($unOrdered); $i++) {
if (sizeof($predepends[$unOrdered[$i]]) == 0) {
for ($i = 0; $i < count($unOrdered); $i++) {
if (count($predepends[$unOrdered[$i]]) == 0) {
$ordered[] = $unOrdered[$i];
unset($unOrdered[$i]);
$unOrdered = array_values($unOrdered);
@ -529,12 +520,12 @@ function buildUploadAccounts($type, $data, $ids, $selectedModules, htmlResponsiv
}
$unOrdered = array_values($unOrdered); // fix indexes
// now add all modules with fulfilled dependencies until all are in order
while (sizeof($unOrdered) > 0) {
while ($unOrdered !== []) {
$newRound = false;
for ($i = 0; $i < sizeof($unOrdered); $i++) {
for ($i = 0; $i < count($unOrdered); $i++) {
$deps = $predepends[$unOrdered[$i]];
$depends = false;
for ($d = 0; $d < sizeof($deps); $d++) {
for ($d = 0; $d < count($deps); $d++) {
if (in_array($deps[$d], $unOrdered)) {
$depends = true;
break;
@ -562,11 +553,11 @@ function buildUploadAccounts($type, $data, $ids, $selectedModules, htmlResponsiv
$partialAccounts[$i]['objectClass'] = [];
}
$stopUpload = false;
for ($i = 0; $i < sizeof($ordered); $i++) {
for ($i = 0; $i < count($ordered); $i++) {
$module = new $ordered[$i]($type->getScope());
logNewMessage(LOG_DEBUG, 'Building data for ' . $ordered[$i]);
$moduleErrors = $module->build_uploadAccounts($data, $ids, $partialAccounts, $selectedModules, $type);
if (sizeof($moduleErrors) > 0) {
if (count($moduleErrors) > 0) {
$errors = array_merge($errors, $moduleErrors);
foreach ($moduleErrors as $error) {
if ($error[0] == 'ERROR') {
@ -582,8 +573,8 @@ function buildUploadAccounts($type, $data, $ids, $selectedModules, htmlResponsiv
break;
}
}
if (sizeof($errors) > 0) {
for ($i = 0; (($i < sizeof($errors)) && ($i < 50)); $i++) {
if ($errors !== []) {
for ($i = 0; (($i < count($errors)) && ($i < 50)); $i++) {
$text = empty($errors[$i][2]) ? null : $errors[$i][2];
$values = empty($errors[$i][3]) ? null : $errors[$i][3];
$container->add(new htmlStatusMessage($errors[$i][0], $errors[$i][1], $text, $values), 12);
@ -606,7 +597,7 @@ function buildUploadAccounts($type, $data, $ids, $selectedModules, htmlResponsiv
*/
function doUploadPreActions($type, $selectedModules, $attributes) {
$messages = [];
for ($i = 0; $i < sizeof($selectedModules); $i++) {
for ($i = 0; $i < count($selectedModules); $i++) {
$activeModule = $selectedModules[$i];
$module = moduleCache::getModule($activeModule, $type->getScope());
$messages = array_merge($messages, $module->doUploadPreActions($attributes, $type));
@ -653,12 +644,7 @@ function doUploadPostActions($type, &$data, $ids, $failed, $selectedModules, &$a
}
// update status and return back to upload page
$return['module'] = $activeModule;
if (sizeof($_SESSION['mass_postActions']['remainingModules']) > 0) {
$return['status'] = 'inProgress';
}
else {
$return['status'] = 'finished';
}
$return['status'] = (count($_SESSION['mass_postActions']['remainingModules']) > 0) ? 'inProgress' : 'finished';
return $return;
}
@ -673,10 +659,10 @@ function getRequiredExtensions() {
$types = $typeManager->getConfiguredTypes();
foreach ($types as $type) {
$mods = $_SESSION['config']->get_AccountModules($type->getId());
for ($m = 0; $m < sizeof($mods); $m++) {
for ($m = 0; $m < count($mods); $m++) {
$module = moduleCache::getModule($mods[$m], $type->getScope());
$ext = $module->getRequiredExtensions();
for ($e = 0; $e < sizeof($ext); $e++) {
for ($e = 0; $e < count($ext); $e++) {
if (!in_array($ext[$e], $extList)) {
$extList[] = $ext[$e];
}
@ -703,9 +689,9 @@ function parseHtml($module, $input, $values, $restricted, $scope) {
if ($input instanceof htmlElement) {
return $input->generateHTML($module, $input, $values, $restricted, $scope);
}
if (is_array($input) && (sizeof($input) > 0)) {
if (is_array($input) && ($input !== [])) {
$return = [];
for ($i = 0; $i < sizeof($input); $i++) {
for ($i = 0; $i < count($input); $i++) {
$return = array_merge($return, $input[$i]->generateHTML($module, $input, $values, $restricted, $scope));
}
return $return;
@ -968,10 +954,10 @@ class accountContainer {
exit;
}
// module actions
if ((sizeof($_POST) > 0) && checkIfWriteAccessIsAllowed($this->type->getId())) {
if (($_POST !== []) && checkIfWriteAccessIsAllowed($this->type->getId())) {
$result = call_user_func([&$this->module[$this->order[$this->current_page]], 'process_' . $this->subpage]);
if (is_array($result)) { // messages were returned, check for errors
for ($i = 0; $i < sizeof($result); $i++) {
for ($i = 0; $i < count($result); $i++) {
if ($result[$i][0] == 'ERROR') {
$errorsOccurred = true;
break;
@ -992,7 +978,7 @@ class accountContainer {
$incompleteModules[] = $this->module[$module]->get_alias();
}
}
if (sizeof($incompleteModules) > 0) {
if ($incompleteModules !== []) {
$result[] = ['INFO', _('Some required information is missing'),
sprintf(_('Please set up all required attributes on page: %s'), implode(", ", $incompleteModules))];
}
@ -1000,7 +986,7 @@ class accountContainer {
// save account
$saveMessages = $this->save_account();
$saveOk = true;
for ($i = 0; $i < sizeof($saveMessages); $i++) {
for ($i = 0; $i < count($saveMessages); $i++) {
if ($saveMessages[$i][0] == 'ERROR') {
$saveOk = false;
}
@ -1017,7 +1003,7 @@ class accountContainer {
}
// change to next page
if (is_array($result)) { // messages were returned, check for errors
for ($i = 0; $i < sizeof($result); $i++) {
for ($i = 0; $i < count($result); $i++) {
if ($result[$i][0] == 'ERROR') {
$errorsOccurred = true;
break;
@ -1027,11 +1013,11 @@ class accountContainer {
if (!$errorsOccurred) {
// go to subpage of current module
$postKeys = array_keys($_POST);
for ($p = 0; $p < sizeof($postKeys); $p++) {
for ($p = 0; $p < count($postKeys); $p++) {
if (is_string($postKeys[$p]) && (str_starts_with($postKeys[$p], 'form_subpage_' . $this->order[$this->current_page]))) {
$temp = substr($postKeys[$p], strlen($this->order[$this->current_page]) + 14);
$temp = explode('_', $temp);
if (sizeof($temp) == 2) {
if (count($temp) == 2) {
$this->subpage = $temp[0];
}
}
@ -1080,7 +1066,7 @@ class accountContainer {
$this->printPasswordPromt();
// display error messages
if (is_array($result)) {
for ($i = 0; $i < sizeof($result); $i++) {
for ($i = 0; $i < count($result); $i++) {
call_user_func_array(StatusMessage(...), $result[$i]);
}
}
@ -1110,7 +1096,7 @@ class accountContainer {
foreach ($this->getOUs() as $suffix) {
$suffixList[getAbstractDN($suffix)] = $suffix;
}
if (!($this->dnSuffix == '') && !in_array_ignore_case($this->dnSuffix, $this->getOUs())) {
if (($this->dnSuffix != '') && !in_array_ignore_case($this->dnSuffix, $this->getOUs())) {
$suffixList[getAbstractDN($this->dnSuffix)] = $this->dnSuffix;
}
$selectedSuffix = [$this->dnSuffix];
@ -1307,22 +1293,22 @@ class accountContainer {
$forcePasswordChange = true;
}
$return['forcePasswordChange'] = $forcePasswordChange;
if ($return['errorsOccurred'] == 'false') {
if ($return['errorsOccurred'] === 'false') {
// set new password
foreach ($this->module as $module) {
if ($module instanceof passwordService) {
$messages = $module->passwordChangeRequested($password1, $modules, $forcePasswordChange);
for ($m = 0; $m < sizeof($messages); $m++) {
for ($m = 0; $m < count($messages); $m++) {
if ($messages[$m][0] == 'ERROR') {
$return['errorsOccurred'] = 'true';
}
if (sizeof($messages[$m]) == 2) {
if (count($messages[$m]) == 2) {
$return['messages'] .= StatusMessage($messages[$m][0], $messages[$m][1], '', [], true);
}
elseif (sizeof($messages[$m]) == 3) {
elseif (count($messages[$m]) == 3) {
$return['messages'] .= StatusMessage($messages[$m][0], $messages[$m][1], $messages[$m][2], [], true);
}
elseif (sizeof($messages[$m]) == 4) {
elseif (count($messages[$m]) == 4) {
$return['messages'] .= StatusMessage($messages[$m][0], $messages[$m][1], $messages[$m][2], $messages[$m][3], true);
}
}
@ -1339,7 +1325,7 @@ class accountContainer {
$this->sendPasswordViaMailAlternateAddress = $input['sendMailAlternateAddress'];
}
}
if ($return['errorsOccurred'] == 'false') {
if ($return['errorsOccurred'] === 'false') {
$return['messages'] .= StatusMessage('INFO', _('The new password will be stored in the directory after you save this account.'), '', [], true);
$this->extraInfoAttributes['INFO.passwordUpdated'] = 'yes';
$this->extraInfoAttributes['INFO.forcePasswordChange'] = $forcePasswordChange ? 'yes' : 'no';
@ -1414,10 +1400,10 @@ class accountContainer {
// profile selection
$accountProfilePersistenceManager = new AccountProfilePersistenceManager();
$profilelist = $accountProfilePersistenceManager->getAccountProfileNames($this->type->getId(), $_SESSION['config']->getName());
if (sizeof($profilelist) > 0) {
if (count($profilelist) > 0) {
$profileButton = new htmlButton('accountContainerLoadProfileButton', _('Load profile'));
$profileButton->setOnClick('confirmLoadProfile(\'' . _('Load profile') . '\', \'' . _('This may overwrite existing values with profile data. Continue?') . '\','
. ' \'' . _('Ok') . '\', \'' . _('Cancel') . '\', event); return false;');
. ' \'' . _('Ok') . '\', \'' . _('Cancel') . '\', event); return false;');
$profileButton->addDataAttribute('lastprofile', $this->lastLoadedProfile);
$profileListOptions = [];
foreach ($profilelist as $profileName) {
@ -1455,7 +1441,7 @@ class accountContainer {
if (!empty($_POST)) {
validateSecurityToken();
}
include '../../lib/adminHeader.inc';
include __DIR__ . '/adminHeader.inc';
echo "<form id=\"inputForm\" enctype=\"multipart/form-data\" action=\"edit.php?editKey=" . htmlspecialchars($this->base) . "\" method=\"post\" onSubmit=\"window.lam.utility.saveScrollPosition('inputForm')\" autocomplete=\"off\" novalidate=\"novalidate\">\n";
echo '<input type="hidden" name="' . getSecurityTokenName() . '" value="' . getSecurityTokenValue() . '">';
}
@ -1465,7 +1451,7 @@ class accountContainer {
*/
private function printPageFooter() {
echo "</form>\n";
include '../../lib/adminFooter.inc';
include __DIR__ . '/adminFooter.inc';
}
/**
@ -1476,19 +1462,14 @@ class accountContainer {
private function printSuccessPage($messages) {
$this->printPageHeader();
// Show success message
if ($this->dn_orig == '') {
$text = _("Account was created successfully.");
}
else {
$text = _("Account was modified successfully.");
}
$text = ($this->dn_orig == '') ? _("Account was created successfully.") : _("Account was modified successfully.");
echo "<div smallPaddingContent\">";
$container = new htmlResponsiveRow();
$container->addVerticalSpacer('2rem');
// show messages
for ($i = 0; $i < sizeof($messages); $i++) {
if (sizeof($messages[$i]) == 2) {
for ($i = 0; $i < count($messages); $i++) {
if (count($messages[$i]) == 2) {
$message = new htmlStatusMessage($messages[$i][0], $messages[$i][1]);
$container->add($message);
}
@ -1665,7 +1646,7 @@ class accountContainer {
// create modify with add and remove
$attributes2 = array_keys($toadd);
for ($i = 0; $i < count($attributes2); $i++) {
if (isset($torem[$attributes2[$i]]) && (count($toadd[$attributes2[$i]]) > 0) && (count($torem[$attributes2[$i]]) > 0)) {
if (isset($torem[$attributes2[$i]]) && ($toadd[$attributes2[$i]] !== []) && (count($torem[$attributes2[$i]]) > 0)) {
// found attribute which should be modified
$tomodify[$attributes2[$i]] = $toadd[$attributes2[$i]];
// merge unchanged values
@ -1678,16 +1659,16 @@ class accountContainer {
unset($torem[$attributes2[$i]]);
}
}
if (count($toadd) > 0) {
if ($toadd !== []) {
$return[$this->dn_orig]['add'] = $toadd;
}
if (count($torem) > 0) {
if ($torem !== []) {
$return[$this->dn_orig]['remove'] = $torem;
}
if (count($tomodify) > 0) {
if ($tomodify !== []) {
$return[$this->dn_orig]['modify'] = $tomodify;
}
if (count($notchanged) > 0) {
if ($notchanged !== []) {
$return[$this->dn_orig]['notchanged'] = $notchanged;
}
return $return;
@ -1734,7 +1715,7 @@ class accountContainer {
$attr = $this->fixLDAPAttributes($attr, $modules);
// get binary attributes
$binaryAttr = ['jpegPhoto'];
for ($i = 0; $i < sizeof($binaryAttr); $i++) {
for ($i = 0; $i < count($binaryAttr); $i++) {
if (isset($attr[$binaryAttr[$i]][0])) {
$binData = ldap_get_values_len($_SESSION['ldap']->server(), $entry, $binaryAttr[$i]);
unset($binData['count']);
@ -1790,14 +1771,14 @@ class accountContainer {
}
// build lower case attribute names
$ldapAttributes = [];
for ($i = 0; $i < sizeof($ldapAttributesTemp); $i++) {
for ($i = 0; $i < count($ldapAttributesTemp); $i++) {
$ldapAttributes[strtolower($ldapAttributesTemp[$i])] = $ldapAttributesTemp[$i];
unset($ldapAttributes[$i]);
}
$ldapAttributesKeys = array_keys($ldapAttributes);
// convert alias names to lower case (for easier comparison)
$aliasKeys = array_keys($aliases);
for ($i = 0; $i < sizeof($aliasKeys); $i++) {
for ($i = 0; $i < count($aliasKeys); $i++) {
if ($aliasKeys[$i] != strtolower($aliasKeys[$i])) {
$aliases[strtolower($aliasKeys[$i])] = $aliases[$aliasKeys[$i]];
unset($aliases[$aliasKeys[$i]]);
@ -1805,9 +1786,9 @@ class accountContainer {
}
}
// fix object classes and attributes
for ($i = 0; $i < sizeof($keys); $i++) {
for ($i = 0; $i < count($keys); $i++) {
// check object classes
if (strtolower($keys[$i]) == 'objectclass') {
if (strtolower($keys[$i]) === 'objectclass') {
// fix object class attribute
if ($keys[$i] != 'objectClass') {
$temp = $attributes[$keys[$i]];
@ -1815,9 +1796,9 @@ class accountContainer {
$attributes['objectClass'] = $temp;
}
// fix object classes
for ($attrClass = 0; $attrClass < sizeof($attributes['objectClass']); $attrClass++) {
for ($modClass = 0; $modClass < sizeof($objectClasses); $modClass++) {
if (strtolower($attributes['objectClass'][$attrClass]) == strtolower($objectClasses[$modClass])) {
for ($attrClass = 0; $attrClass < count($attributes['objectClass']); $attrClass++) {
for ($modClass = 0; $modClass < count($objectClasses); $modClass++) {
if (strtolower($attributes['objectClass'][$attrClass]) === strtolower($objectClasses[$modClass])) {
if ($attributes['objectClass'][$attrClass] != $objectClasses[$modClass]) {
unset($attributes['objectClass'][$attrClass]);
$attributes['objectClass'][] = $objectClasses[$modClass];
@ -1827,19 +1808,16 @@ class accountContainer {
}
}
}
else {
elseif (in_array(strtolower($keys[$i]), $aliasKeys)) {
// fix aliases
if (in_array(strtolower($keys[$i]), $aliasKeys)) {
$attributes[$aliases[strtolower($keys[$i])]] = $attributes[$keys[$i]];
$attributes[$aliases[strtolower($keys[$i])]] = $attributes[$keys[$i]];
unset($attributes[$keys[$i]]);
}
elseif (in_array(strtolower($keys[$i]), $ldapAttributesKeys)) {
if ($keys[$i] != $ldapAttributes[strtolower($keys[$i])]) {
$attributes[$ldapAttributes[strtolower($keys[$i])]] = $attributes[$keys[$i]];
unset($attributes[$keys[$i]]);
}
// fix attribute names
elseif (in_array(strtolower($keys[$i]), $ldapAttributesKeys)) {
if ($keys[$i] != $ldapAttributes[strtolower($keys[$i])]) {
$attributes[$ldapAttributes[strtolower($keys[$i])]] = $attributes[$keys[$i]];
unset($attributes[$keys[$i]]);
}
}
}
}
return $attributes;
@ -2035,7 +2013,7 @@ class accountContainer {
foreach ($module as $singlemodule) {
$preModifyMessages = $this->module[$singlemodule]->preModifyActions($this->isNewAccount, $prePostModifyAttributes);
$errors = array_merge($errors, $preModifyMessages);
for ($i = 0; $i < sizeof($preModifyMessages); $i++) {
for ($i = 0; $i < count($preModifyMessages); $i++) {
if ($preModifyMessages[$i][0] == 'ERROR') {
$preModifyOk = false;
break;
@ -2059,7 +2037,7 @@ class accountContainer {
}
$rdnAttr = strtolower(extractRDNAttribute($this->finalDN));
if (isset($attributes[$this->finalDN]['modify'][$rdnAttr])
&& (sizeof($attributes[$this->finalDN]['modify'][$rdnAttr]) == 1)
&& (count($attributes[$this->finalDN]['modify'][$rdnAttr]) == 1)
&& (($attributes[$this->finalDN]['modify'][$rdnAttr][0] == extractRDNValue($this->finalDN))
|| (unescapeLdapSpecialCharacters($attributes[$this->finalDN]['modify'][$rdnAttr][0]) == unescapeLdapSpecialCharacters(extractRDNValue($this->finalDN))))) {
// remove old RDN if attribute is single valued
@ -2128,7 +2106,7 @@ class accountContainer {
logNewMessage(LOG_NOTICE, 'Modified DN: ' . $DNs[$i]);
// check if the password of the currently logged in user was changed
$lamAdmin = $_SESSION['ldap']->getUserName();
if ((strtolower($DNs[$i]) == strtolower($lamAdmin)) && isset($attributes[$DNs[$i]]['info']['userPasswordClearText'][0])) {
if ((strtolower($DNs[$i]) === strtolower($lamAdmin)) && isset($attributes[$DNs[$i]]['info']['userPasswordClearText'][0])) {
$_SESSION['ldap']->tryAndApplyNewPassword($attributes[$DNs[$i]]['info']['userPasswordClearText'][0]);
}
}
@ -2164,7 +2142,7 @@ class accountContainer {
// send password mail
if (!$stopprocessing && isLAMProVersion() && ($this->sendPasswordViaMail != null)) {
$mailMessages = sendPasswordMail($this->sendPasswordViaMail, $prePostModifyAttributes, $this->sendPasswordViaMailAlternateAddress);
if (sizeof($mailMessages) > 0) {
if (count($mailMessages) > 0) {
$errors = array_merge($errors, $mailMessages);
}
$this->sendPasswordViaMail = null;
@ -2213,7 +2191,7 @@ class accountContainer {
next($this->module);
}
$dn = $this->dn_orig;
if (isset($this->finalDN)) {
if ($this->finalDN !== null) {
$dn = $this->finalDN;
}
return array_merge($return, ['main_dn' => [new \LAM\PDF\PDFLabelValue(_('DN'), $dn)]]);
@ -2226,16 +2204,16 @@ class accountContainer {
$order = [];
$modules = array_keys($this->module);
$depModules = [];
if (isset($this->order)) {
if ($this->order !== null) {
$currentPage = $this->order[$this->current_page];
}
for ($i = 0; $i < sizeof($modules); $i++) {
for ($i = 0; $i < count($modules); $i++) {
// insert waiting modules
for ($w = 0; $w < sizeof($depModules); $w++) {
for ($w = 0; $w < count($depModules); $w++) {
$dependencies = $this->module[$depModules[$w]]->get_dependencies();
$dependencies = $dependencies['depends'];
$everything_found = true;
for ($d = 0; $d < sizeof($dependencies); $d++) {
for ($d = 0; $d < count($dependencies); $d++) {
if (!in_array($dependencies[$d], $order)) {
$everything_found = false;
break;
@ -2254,7 +2232,7 @@ class accountContainer {
if (is_array($dependencies['depends'])) {
$everything_found = true;
$dependencies = $dependencies['depends'];
for ($d = 0; $d < sizeof($dependencies); $d++) {
for ($d = 0; $d < count($dependencies); $d++) {
if (is_array($dependencies[$d])) { // or-combined dependencies
$noneFound = true;
foreach ($dependencies[$d] as $or) {
@ -2289,15 +2267,15 @@ class accountContainer {
}
}
// add modules which could not be sorted (e.g. because of cyclic dependencies)
if (sizeof($depModules) > 0) {
for ($i = 0; $i < sizeof($depModules); $i++) {
if ($depModules !== []) {
for ($i = 0; $i < count($depModules); $i++) {
$order[] = $depModules[$i];
}
}
// move disabled modules to end
$activeModules = [];
$passiveModules = [];
for ($i = 0; $i < sizeof($order); $i++) {
for ($i = 0; $i < count($order); $i++) {
if ($this->module[$order[$i]]->getButtonStatus() == 'enabled') {
$activeModules[] = $order[$i];
}
@ -2410,7 +2388,7 @@ class accountContainer {
$found = $this->doReplace($replacements, $data[$key]) || $found;
}
else {
foreach ($value as $valueIndex => $valueEntry) {
foreach (array_keys($value) as $valueIndex) {
$found = $this->doReplace($replacements, $data[$key][$valueIndex]) || $found;
}
}

View file

@ -140,10 +140,7 @@ class account extends baseModule {
* @return boolean true if LDAP operation can be done
*/
function module_complete() {
if (!$this->isUnixActive() && empty($this->attributes['uid'][0])) {
return false;
}
return true;
return $this->isUnixActive() || !empty($this->attributes['uid'][0]);
}
/**
@ -263,7 +260,7 @@ class account extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("account", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "account";

View file

@ -65,7 +65,7 @@ class asteriskAccount extends baseModule implements passwordService {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['user']);
return $this->get_scope() === 'user';
}
/**
@ -799,14 +799,16 @@ class asteriskAccount extends baseModule implements passwordService {
// check if caller ID is empty
if ($this->attributes['AstAccountCallerID'][0] == '') {
$errors[] = $this->messages['AstAccountCallerID'][0];
} // check format
else if (!get_preg($this->attributes['AstAccountCallerID'][0], 'username')) {
}
// check format
elseif (!get_preg($this->attributes['AstAccountCallerID'][0], 'username')) {
$errors[] = $this->messages['AstAccountCallerID'][1];
} // check for duplicate caller ID
else if (!isset($this->orig['AstAccountCallerID'][0])
}
// check for duplicate caller ID
elseif (!isset($this->orig['AstAccountCallerID'][0])
|| ($this->orig['AstAccountCallerID'][0] != $this->attributes['AstAccountCallerID'][0])) {
$entries = searchLDAPByAttribute('AstAccountCallerID', $this->attributes['AstAccountCallerID'][0], 'AsteriskSIPUser', ['dn'], ['user']);
if (sizeof($entries) > 0) {
if (count($entries) > 0) {
$errors[] = $this->messages['AstAccountCallerID'][2];
}
}
@ -1035,7 +1037,7 @@ class asteriskAccount extends baseModule implements passwordService {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("AsteriskSIPUser", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "AsteriskSIPUser";
@ -1119,10 +1121,7 @@ class asteriskAccount extends baseModule implements passwordService {
*
*/
public function managesPasswordAttributes() {
if (!in_array('AsteriskSIPUser', $this->attributes['objectClass'])) {
return false;
}
return true;
return in_array('AsteriskSIPUser', $this->attributes['objectClass']);
}
/**
@ -1205,16 +1204,12 @@ class asteriskAccount extends baseModule implements passwordService {
if ($_POST['posixAccount_password'] != $_POST['posixAccount_password2']) {
return $return;
}
else {
if (!get_preg($_POST['posixAccount_password'], 'password')) {
return $return;
}
else {
// sync password
if (in_array('syncAsteriskPassword', $fields)) {
$return['mod']['AstAccountRealmedPassword'][0] = asteriskAccount::buildPasswordString($attributes, $this->selfServiceSettings->moduleSettings, $_POST['posixAccount_password']);
}
}
elseif (!get_preg($_POST['posixAccount_password'], 'password')) {
return $return;
}
elseif (in_array('syncAsteriskPassword', $fields)) {
// sync password
$return['mod']['AstAccountRealmedPassword'][0] = asteriskAccount::buildPasswordString($attributes, $this->selfServiceSettings->moduleSettings, $_POST['posixAccount_password']);
}
}
return $return;

View file

@ -67,7 +67,7 @@ class asteriskExtension extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['asteriskExt']);
return $this->get_scope() === 'asteriskExt';
}
/**
@ -249,11 +249,11 @@ class asteriskExtension extends baseModule {
$title->setHelpId('member');
$renderContainer->add($title, 12);
$ownerList = new htmlTable();
if ((!isset($this->extensionOwners) || sizeof($this->extensionOwners) == 0) && isset($this->extensionRows[0]['member'])) {
if (($this->extensionOwners === null || count($this->extensionOwners) == 0) && isset($this->extensionRows[0]['member'])) {
$this->extensionOwners = $this->extensionRows[0]['member'];
}
if (isset($this->extensionOwners)) {
for ($i = 0; $i < sizeof($this->extensionOwners); $i++) {
if ($this->extensionOwners !== null) {
for ($i = 0; $i < count($this->extensionOwners); $i++) {
$ownerList->addElement(new htmlOutputText(getAbstractDN($this->extensionOwners[$i])), true);
}
}
@ -327,7 +327,7 @@ class asteriskExtension extends baseModule {
$renderContainer->add(new htmlSubTitle(_('Rules')), 12);
$renderContainer->addVerticalSpacer('1rem');
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$this->render_extension($entries[$i], $i, $renderContainer);
$renderContainer->addLabel(new htmlButton("delete_rule_" . $i, _('Delete rule')), false);
@ -335,8 +335,8 @@ class asteriskExtension extends baseModule {
if ($i > 0) {
$upDownButtons->addElement(new htmlButton('rule_up_button_' . $i, 'up.svg', true), false);
}
if (($i < sizeof($entries) - 1) &&
((sizeof($entries) > 1) || ($this->addRuleFlag))) {
if (($i < count($entries) - 1) &&
((count($entries) > 1) || ($this->addRuleFlag))) {
$upDownButtons->addElement(new htmlButton('rule_down_button_' . $i, 'down.svg', true));
}
$renderContainer->addField($upDownButtons, true);
@ -344,11 +344,11 @@ class asteriskExtension extends baseModule {
$renderContainer->addVerticalSpacer('2rem');
}
$displayEntrNum = sizeof($entries);
$displayEntrNum = count($entries);
if ($this->addRuleFlag || sizeof($entries) == 0) {
if ($this->addRuleFlag || count($entries) == 0) {
$this->render_extension(null, sizeof($entries), $renderContainer);
$this->render_extension(null, count($entries), $renderContainer);
if ($this->addRuleFlag) {
$upDownButtons = new htmlTable();
@ -423,7 +423,7 @@ class asteriskExtension extends baseModule {
else {
arsort($sortable_array);
}
foreach ($sortable_array as $k => $v) {
foreach (array_keys($sortable_array) as $k) {
$new_array[] = $array[$k];
}
}
@ -445,22 +445,17 @@ class asteriskExtension extends baseModule {
}
$entries = searchLDAPByAttribute(null, null, $searchClass, ['dn'], [$searchScope]);
$users_dn = [];
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$dn = $entries[$i]['dn'];
if (isset($dn) && (!isset($this->extensionOwners) || !in_array($dn, $this->extensionOwners))) {
if (isset($dn) && ($this->extensionOwners === null || !in_array($dn, $this->extensionOwners))) {
$users_dn[getAbstractDN($dn)] = $dn;
}
}
uasort($users_dn, compareDN(...));
if (isset($this->extensionOwners)) {
$memberList = $this->extensionOwners;
}
else {
$memberList = [];
}
$memberList = $this->extensionOwners ?? [];
usort($memberList, compareDN(...));
$members = [];
for ($i = 0; $i < sizeof($memberList); $i++) {
for ($i = 0; $i < count($memberList); $i++) {
$members[getAbstractDN($memberList[$i])] = $memberList[$i];
}
// options
@ -495,7 +490,7 @@ class asteriskExtension extends baseModule {
$this->filterOwnerForAsteriskAccounts = false;
}
}
if (!isset($this->extensionOwners)) {
if ($this->extensionOwners === null) {
$this->extensionOwners = [];
}
if (isset($_POST['owners_2']) && isset($_POST['owners_left'])) {
@ -517,10 +512,8 @@ class asteriskExtension extends baseModule {
*/
function isMoveToNewSuffix() {
$orig_suffix = extractDNSuffix($this->getAccountContainer()->dn_orig);
if (strcmp($orig_suffix, $this->getAccountContainer()->dnSuffix) != 0 && !$this->getAccountContainer()->isNewAccount) {
return true;
}
return false;
return strcmp($orig_suffix, $this->getAccountContainer()->dnSuffix) != 0
&& !$this->getAccountContainer()->isNewAccount;
}
@ -530,10 +523,7 @@ class asteriskExtension extends baseModule {
* @return boolean true if one or more owners
*/
function isExtensionOwnerSet() {
if (sizeof($this->extensionOwners) > 0) {
return true;
}
return false;
return (count($this->extensionOwners) > 0);
}
/**
@ -606,7 +596,7 @@ class asteriskExtension extends baseModule {
$extRow = [];
if (!isset($_POST['delete_rule_' . $entryCounter])) {
$singleExtAddErrors = $this->processSingleExtension($extRow, $extensionName, $extensionContext, $entryCounter, $extensionPriorityCntr);
$errors = $errors + $singleExtAddErrors;
$errors += $singleExtAddErrors;
if ((isset($extRow['astapplication'][0]) && $extRow['astapplication'][0] != "") ||
(isset($extRow['astapplicationdata'][0]) && $extRow['astapplicationdata'][0] != "")
@ -702,13 +692,12 @@ class asteriskExtension extends baseModule {
* Reorders the rules if the user clicked on a move button.
*/
function processPriorityChange() {
for ($entryCounter = 0; $entryCounter < sizeof($this->extensionRows); $entryCounter++) {
for ($entryCounter = 0; $entryCounter < count($this->extensionRows); $entryCounter++) {
if (isset($_POST["rule_up_button_" . $entryCounter])) {
$this->extensionRows[$entryCounter]['astpriority'][0]--;
$this->extensionRows[$entryCounter - 1]['astpriority'][0]++;
}
else if (isset($_POST["rule_down_button_" . $entryCounter])) {
elseif (isset($_POST["rule_down_button_" . $entryCounter])) {
$this->extensionRows[$entryCounter]['astpriority'][0]++;
$this->extensionRows[$entryCounter + 1]['astpriority'][0]--;
}
@ -730,7 +719,7 @@ class asteriskExtension extends baseModule {
$entries = searchLDAPByAttribute("AstExtension", $extension, $searchClass, ['dn'], [$searchScope]);
$exists = false;
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$dn = extractDNSuffix($entries[$i]['dn']);
if ($dn == $this->getAccountContainer()->dnSuffix) {
$exists = true;
@ -757,8 +746,8 @@ class asteriskExtension extends baseModule {
$entries = searchLDAPByAttribute(null, null, $searchClass, ['astextension'], [$searchScope]);
$entries = $this->array_sort($entries, 'astextension');
if (isset($entries[sizeof($entries) - 1]['astextension'][0])) {
$greater_ext_name = $entries[sizeof($entries) - 1]['astextension'][0];
if (isset($entries[count($entries) - 1]['astextension'][0])) {
$greater_ext_name = $entries[count($entries) - 1]['astextension'][0];
}
else {
$greater_ext_name = 0;
@ -806,7 +795,7 @@ class asteriskExtension extends baseModule {
$pdfRow->cells[] = new PDFTableCell(_('Application data'), '30%', null, true);
$pdfRow->cells[] = new PDFTableCell(_('Priority'), '20%', null, true);
$pdfTable->rows[] = $pdfRow;
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$appdata = ' ';
if (isset($entries[$i]['astapplicationdata'][0])) {
$appdata = $entries[$i]['astapplicationdata'][0];
@ -830,7 +819,7 @@ class asteriskExtension extends baseModule {
$messages = [];
//hash to store extension_name => priority. For new extension priority will be 1
$extensionNamePriorityMap = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("AsteriskExtension", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "AsteriskExtension";

View file

@ -63,7 +63,7 @@ class asteriskVoicemail extends baseModule implements passwordService {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['user']);
return $this->get_scope() === 'user';
}
/**
@ -297,7 +297,7 @@ class asteriskVoicemail extends baseModule implements passwordService {
elseif (isset($_POST['remVoicemailObjectClass'])) {
$this->attributes['objectClass'] = array_delete(['AsteriskVoiceMail'], $this->attributes['objectClass']);
$attrKeys = array_keys($this->attributes);
for ($k = 0; $k < sizeof($attrKeys); $k++) {
for ($k = 0; $k < count($attrKeys); $k++) {
if (strpos($attrKeys[$k], 'AstVoicemail') > -1) {
unset($this->attributes[$attrKeys[$k]]);
}
@ -334,13 +334,13 @@ class asteriskVoicemail extends baseModule implements passwordService {
$errors[] = $this->messages['AstVoicemailMailbox'][0];
}
// check format
else if (!get_preg($this->attributes['AstVoicemailMailbox'][0], 'username')) {
elseif (!get_preg($this->attributes['AstVoicemailMailbox'][0], 'username')) {
$errors[] = $this->messages['AstVoicemailMailbox'][1];
}
// check for duplicate Voicemail ID
else if (!isset($this->orig['AstVoicemailMailbox'][0]) || ($this->orig['AstVoicemailMailbox'][0] != $this->attributes['AstVoicemailMailbox'][0])) {
elseif (!isset($this->orig['AstVoicemailMailbox'][0]) || ($this->orig['AstVoicemailMailbox'][0] != $this->attributes['AstVoicemailMailbox'][0])) {
$entries = searchLDAPByAttribute('AstVoicemailMailbox', $this->attributes['AstVoicemailMailbox'][0], 'AstVoicemailMailbox', ['dn'], ['user']);
if (sizeof($entries) > 0) {
if (count($entries) > 0) {
$errors[] = $this->messages['AstVoicemailMailbox'][2];
}
}
@ -397,7 +397,7 @@ class asteriskVoicemail extends baseModule implements passwordService {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("AsteriskVoiceMail", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "AsteriskVoiceMail";
@ -441,10 +441,8 @@ class asteriskVoicemail extends baseModule implements passwordService {
* @return boolean true if LDAP operation can be done
*/
function module_complete() {
if (in_array('AsteriskVoiceMail', $this->attributes['objectClass']) && empty($this->attributes['AstVoicemailPassword'][0])) {
return false;
}
return true;
return (!in_array('AsteriskVoiceMail', $this->attributes['objectClass'])
|| !empty($this->attributes['AstVoicemailPassword'][0]));
}
/**
@ -474,10 +472,7 @@ class asteriskVoicemail extends baseModule implements passwordService {
*
*/
public function managesPasswordAttributes() {
if (!in_array('AsteriskVoiceMail', $this->attributes['objectClass'])) {
return false;
}
return true;
return in_array('AsteriskVoiceMail', $this->attributes['objectClass']);
}
/**
@ -534,16 +529,12 @@ class asteriskVoicemail extends baseModule implements passwordService {
if ($_POST['posixAccount_password'] != $_POST['posixAccount_password2']) {
return $return;
}
else {
if (!get_preg($_POST['posixAccount_password'], 'password')) {
return $return;
}
else {
// sync password
if (in_array('syncAsteriskVoicemailPassword', $fields)) {
$return['mod']['AstVoicemailPassword'][0] = $_POST['posixAccount_password'];
}
}
elseif (!get_preg($_POST['posixAccount_password'], 'password')) {
return $return;
}
elseif (in_array('syncAsteriskVoicemailPassword', $fields)) {
// sync password
$return['mod']['AstVoicemailPassword'][0] = $_POST['posixAccount_password'];
}
}
return $return;

View file

@ -57,7 +57,7 @@ class authorizedServiceObject extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['user']);
return $this->get_scope() === 'user';
}
/**
@ -206,7 +206,7 @@ class authorizedServiceObject extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("authorizedServiceObject", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "authorizedServiceObject";
@ -246,7 +246,7 @@ class authorizedServiceObject extends baseModule {
// add ASs
if (isset ($profile['authorizedServiceObject_services'][0]) && ($profile['authorizedServiceObject_services'][0] != "")) {
$services = explode(',', $profile['authorizedServiceObject_services'][0]);
for ($m = 0; $m < sizeof($services); $m++) {
for ($m = 0; $m < count($services); $m++) {
if (get_preg($services[$m], 'ascii')) {
$this->attributes['authorizedservice'][] = trim($services[$m]);
}

View file

@ -508,7 +508,7 @@ class courierMailAccount extends baseModule {
*/
public function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("courierMailAccount", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "courierMailAccount";

View file

@ -44,7 +44,7 @@ class courierMailAlias extends baseModule {
* {@inheritdoc}
*/
public function can_manage() {
return in_array($this->get_scope(), ['mailAlias']);
return $this->get_scope() === 'mailAlias';
}
/**
@ -151,9 +151,9 @@ class courierMailAlias extends baseModule {
$this->addSimpleInputTextField($return, 'mail', _('Email address'), true);
$this->addMultiValueInputTextField($return, 'maildrop', _('Recipient address'), true);
$return->addVerticalSpacer('0.5rem');
$selectedSource = (!empty($this->attributes['mailsource'][0])) ? $this->attributes['mailsource'][0] : "-";
$selectedSource = (empty($this->attributes['mailsource'][0])) ? "-" : $this->attributes['mailsource'][0];
$return->add(new htmlResponsiveSelect('mailsource', ['-', 'esmtp', 'local'], [$selectedSource], _('Mail source'), 'mailsource'), 12);
$description = (!empty($this->attributes['description'][0])) ? $this->attributes['description'][0] : '';
$description = (empty($this->attributes['description'][0])) ? '' : $this->attributes['description'][0];
$boxInput = new htmlResponsiveInputField(_('Description'), 'description', $description, 'description');
$boxInput->setFieldMaxLength(100);
$return->add($boxInput, 12);
@ -202,7 +202,7 @@ class courierMailAlias extends baseModule {
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
$possibleSources = ['esmtp', 'local'];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
if (!in_array("courierMailAlias", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "courierMailAlias";
}
@ -215,7 +215,7 @@ class courierMailAlias extends baseModule {
}
else {
$error = $this->messages['mailsource'][0];
array_push($error, [$i]);
$error[] = [$i];
$messages[] = $error;
}
}
@ -243,7 +243,7 @@ class courierMailAlias extends baseModule {
return function(array $entry, string $attribute): ?htmlElement {
$group = new htmlGroup();
if (isset($entry[$attribute][0]) && ($entry[$attribute][0] != '')) {
for ($i = 0; $i < sizeof($entry[$attribute]); $i++) {
for ($i = 0; $i < count($entry[$attribute]); $i++) {
if ($i > 0) {
$group->addElement(new htmlOutputText(", "));
}

View file

@ -177,7 +177,7 @@ class ddns extends baseModule {
}
$zones = $this->getZoneNames();
if (sizeof($zones) < 2) {
if (count($zones) < 2) {
return false;
}
}
@ -300,7 +300,7 @@ class ddns extends baseModule {
$errors[] = $this->messages['ip'][0];
}
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (str_starts_with($this->attributes['dhcpStatements'][$i], 'zone ')) {
unset($this->attributes['dhcpStatements'][$i]);
$this->attributes['dhcpStatements'] = array_values($this->attributes['dhcpStatements']);
@ -317,10 +317,8 @@ class ddns extends baseModule {
$this->attributes['dhcpStatements'][] = "zone {$zone}. { key DHCP_UPDATER; }";
}
}
else {
if (!empty($ip)) {
$errors[] = $this->messages['zone'][0];
}
elseif (!empty($ip)) {
$errors[] = $this->messages['zone'][0];
}
// Zone reverse inserted?
@ -332,10 +330,8 @@ class ddns extends baseModule {
$this->attributes['dhcpStatements'][] = "zone {$zone_reverse}. { key DHCP_UPDATER; }";
}
}
else {
if (!empty($ip)) {
$errors[] = $this->messages['zone_reverse'][0];
}
elseif (!empty($ip)) {
$errors[] = $this->messages['zone_reverse'][0];
}
return $errors;
}
@ -352,7 +348,7 @@ class ddns extends baseModule {
// check if DHCP main settings and valid DHCP entry
if ($this->isRootNode()) {
if (!in_array_ignore_case('dhcpService', $this->attributes['objectClass']) && !in_array_ignore_case('dhcpServer', $this->attributes['objectClass'])) {
$return->addElement(new htmlStatusMessage('ERROR', _('Please set your LDAP suffix to an LDAP entry with object class "dhcpService" or "dhcpServer".')));
$return->add(new htmlStatusMessage('ERROR', _('Please set your LDAP suffix to an LDAP entry with object class "dhcpService" or "dhcpServer".')));
return $return;
}
// DHCP main settings
@ -362,32 +358,30 @@ class ddns extends baseModule {
$keyInput = new htmlResponsiveInputField(_('Path to key for DNS updates'), 'key_path', $this->getUpdateKey(), 'keypath');
$return->add($keyInput);
}
else {
elseif (!$this->check_if_ddns_is_enable()) {
// Account edit
if (!$this->check_if_ddns_is_enable()) {
$return->add(new htmlOutputText(_("DDNS is not activated. You can activate it in the DHCP settings (DDNS).")));
}
else {
// DNS server
$serverInput = new htmlResponsiveInputField(_('IP address of the DNS server'), 'ip', $this->getDNSServer(), 'dns');
$return->add($serverInput);
$return->add(new htmlOutputText(_("DDNS is not activated. You can activate it in the DHCP settings (DDNS).")));
}
else {
// DNS server
$serverInput = new htmlResponsiveInputField(_('IP address of the DNS server'), 'ip', $this->getDNSServer(), 'dns');
$return->add($serverInput);
$zones = $this->getZoneNames();
$zone = '';
$revzone = '';
if (isset($zones[0])) {
$zone = $zones[0];
}
if (isset($zones[1])) {
$revzone = $zones[1];
}
// zone name
$zoneInput = new htmlResponsiveInputField(_('Zone name'), 'zone', $zone, 'zone');
$return->add($zoneInput);
// reverse zone name
$revZoneInput = new htmlResponsiveInputField(_('Reverse zone name'), 'zone_reverse', $revzone, 'zone_reverse');
$return->add($revZoneInput);
$zones = $this->getZoneNames();
$zone = '';
$revzone = '';
if (isset($zones[0])) {
$zone = $zones[0];
}
if (isset($zones[1])) {
$revzone = $zones[1];
}
// zone name
$zoneInput = new htmlResponsiveInputField(_('Zone name'), 'zone', $zone, 'zone');
$return->add($zoneInput);
// reverse zone name
$revZoneInput = new htmlResponsiveInputField(_('Reverse zone name'), 'zone_reverse', $revzone, 'zone_reverse');
$return->add($revZoneInput);
}
return $return;
@ -424,7 +418,7 @@ class ddns extends baseModule {
*/
private function getDNSServer() {
if (isset($this->attributes['dhcpStatements'][0])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (str_starts_with($this->attributes['dhcpStatements'][$i], 'zone ')) {
if (!str_contains($this->attributes['dhcpStatements'][$i], ' primary ')) {
continue;
@ -449,7 +443,7 @@ class ddns extends baseModule {
$zone = '';
$revZone = '';
if (is_array($this->attributes['dhcpStatements'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (str_starts_with($this->attributes['dhcpStatements'][$i], 'zone ')) {
$parts = explode(" ", substr($this->attributes['dhcpStatements'][$i], 5));
$value = substr(array_shift($parts), 0, -1);
@ -475,7 +469,7 @@ class ddns extends baseModule {
private function isDynDNSActivated() {
$return = false;
if (is_array($this->attributes['dhcpStatements'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if ($this->attributes['dhcpStatements'][$i] == 'ddns-update-style interim') {
$return = true;
break;
@ -492,19 +486,14 @@ class ddns extends baseModule {
*/
private function setDynDNSActivated($activated) {
if (is_array($this->attributes['dhcpStatements'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (str_starts_with($this->attributes['dhcpStatements'][$i], 'ddns-update-style ')) {
unset($this->attributes['dhcpStatements'][$i]);
$this->attributes['dhcpStatements'] = array_values($this->attributes['dhcpStatements']);
}
}
}
if ($activated) {
$this->attributes['dhcpStatements'][] = 'ddns-update-style interim';
}
else {
$this->attributes['dhcpStatements'][] = 'ddns-update-style none';
}
$this->attributes['dhcpStatements'][] = $activated ? 'ddns-update-style interim' : 'ddns-update-style none';
}
/**
@ -515,7 +504,7 @@ class ddns extends baseModule {
private function addFixIPs() {
$return = false;
if (is_array($this->attributes['dhcpStatements'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if ($this->attributes['dhcpStatements'][$i] == 'update-static-leases true') {
$return = true;
break;
@ -532,7 +521,7 @@ class ddns extends baseModule {
*/
private function setFixIPs($add) {
if (is_array($this->attributes['dhcpStatements'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (str_starts_with($this->attributes['dhcpStatements'][$i], 'update-static-leases ')) {
unset($this->attributes['dhcpStatements'][$i]);
$this->attributes['dhcpStatements'] = array_values($this->attributes['dhcpStatements']);
@ -552,7 +541,7 @@ class ddns extends baseModule {
private function isIgnoreClientUpdates() {
$return = false;
if (is_array($this->attributes['dhcpStatements'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (preg_replace('/[ ]+/', ' ', $this->attributes['dhcpStatements'][$i]) == 'ignore client-updates') {
$return = true;
break;
@ -569,7 +558,7 @@ class ddns extends baseModule {
*/
private function setIgnoreClientUpdates($ignore) {
if (is_array($this->attributes['dhcpStatements'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (preg_replace('/[ ]+/', ' ', $this->attributes['dhcpStatements'][$i]) == 'ignore client-updates') {
if ($ignore) {
return; // option already set, no change
@ -592,7 +581,7 @@ class ddns extends baseModule {
private function getUpdateKey() {
$return = null;
if (is_array($this->attributes['dhcpStatements'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (str_starts_with($this->attributes['dhcpStatements'][$i], 'include ')) {
$return = substr($this->attributes['dhcpStatements'][$i], 9, strlen($this->attributes['dhcpStatements'][$i]) - 10);
break;
@ -611,7 +600,7 @@ class ddns extends baseModule {
if (!is_array($this->attributes['dhcpStatements'])) {
$this->attributes['dhcpStatements'] = [];
}
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (str_starts_with($this->attributes['dhcpStatements'][$i], 'include ')) {
unset($this->attributes['dhcpStatements'][$i]);
$this->attributes['dhcpStatements'] = array_values($this->attributes['dhcpStatements']);
@ -645,7 +634,7 @@ class ddns extends baseModule {
if (!$this->check_if_ddns_is_enable()) {
return $messages;
}
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// principal name
if (!check_ip($rawAccounts[$i][$ids['ddns_DNSserver']])) {
$error = $this->messages['ip'][1];

View file

@ -440,7 +440,7 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
$errors[] = $this->messages['cn'][0];
}
// Check, if cn is not already use:
elseif ((sizeof(searchLDAPByAttribute('cn', $_POST['cn'], 'dhcpOptions', ['cn'], ['dhcp'])) > 0) && $this->orig['cn']['0'] != $_POST['cn']) {
elseif ((count(searchLDAPByAttribute('cn', $_POST['cn'], 'dhcpOptions', ['cn'], ['dhcp'])) > 0) && $this->orig['cn']['0'] != $_POST['cn']) {
$errors[] = $this->messages['cn'][1];
}
elseif (!check_ip($_POST['cn'], true)) {
@ -532,7 +532,7 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
}
$netbiosServers = explode(', ', $_POST['netbios']);
$netbiosServersOk = true;
for ($i = 0; $i < sizeof($netbiosServers); $i++) {
for ($i = 0; $i < count($netbiosServers); $i++) {
if (!check_ip($netbiosServers[$i]) && !get_preg($netbiosServers[$i], 'DNSname')) {
$netbiosServersOk = false;
break;
@ -587,7 +587,7 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
// check if bit order is 11...00...
$parts = explode('.', $mask);
$bits = '';
for ($i = 0; $i < sizeof($parts); $i++) {
for ($i = 0; $i < count($parts); $i++) {
$bits .= decbin($parts[$i]);
}
return preg_match('/^1*0*$/', $bits);
@ -787,9 +787,9 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
public function getDHCPOption($name) {
$return = null;
if (is_array($this->attributes['dhcpOption'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpOption']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpOption']); $i++) {
$val = $this->attributes['dhcpOption'][$i];
if (substr($val, 0, strlen($name) + 1) == ($name . ' ')) {
if (substr($val, 0, strlen($name) + 1) === $name . ' ') {
$return = substr($val, strlen($name) + 1);
$return = str_replace('"', '', $return);
break;
@ -809,8 +809,8 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
if (empty($this->attributes['dhcpOption'])) {
$this->attributes['dhcpOption'] = [];
}
for ($i = 0; $i < sizeof($this->attributes['dhcpOption']); $i++) {
if (substr($this->attributes['dhcpOption'][$i], 0, strlen($name) + 1) == ($name . ' ')) {
for ($i = 0; $i < count($this->attributes['dhcpOption']); $i++) {
if (substr($this->attributes['dhcpOption'][$i], 0, strlen($name) + 1) === $name . ' ') {
unset($this->attributes['dhcpOption'][$i]);
$this->attributes['dhcpOption'] = array_values($this->attributes['dhcpOption']);
}
@ -828,8 +828,8 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
private function getDefaultLeaseTime() {
$return = null;
if (!empty($this->attributes['dhcpStatements'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
if (substr($this->attributes['dhcpStatements'][$i], 0, 19) == (self::DEFAULT_LEASE_TIME . ' ')) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (substr($this->attributes['dhcpStatements'][$i], 0, 19) === self::DEFAULT_LEASE_TIME . ' ') {
$return = substr($this->attributes['dhcpStatements'][$i], 19);
break;
}
@ -847,8 +847,8 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
if (empty($this->attributes['dhcpStatements'])) {
$this->attributes['dhcpStatements'] = [];
}
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
if (substr($this->attributes['dhcpStatements'][$i], 0, 19) == (self::DEFAULT_LEASE_TIME . ' ')) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (substr($this->attributes['dhcpStatements'][$i], 0, 19) === self::DEFAULT_LEASE_TIME . ' ') {
unset($this->attributes['dhcpStatements'][$i]);
$this->attributes['dhcpStatements'] = array_values($this->attributes['dhcpStatements']);
}
@ -866,7 +866,7 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
private function getUnknownClients() {
$return = null;
if (!empty($this->attributes['dhcpStatements'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
$val = $this->attributes['dhcpStatements'][$i];
if (strpos($val, self::UNKNOWN_CLIENTS) === (strlen($val) - strlen(self::UNKNOWN_CLIENTS))) {
$return = substr($val, 0, (strlen($val) - strlen(self::UNKNOWN_CLIENTS) - 1));
@ -886,7 +886,7 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
if (!isset($this->attributes['dhcpStatements'])) {
$this->attributes['dhcpStatements'] = [];
}
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
$val = $this->attributes['dhcpStatements'][$i];
if (strpos($val, self::UNKNOWN_CLIENTS) === (strlen($val) - strlen(self::UNKNOWN_CLIENTS))) {
unset($this->attributes['dhcpStatements'][$i]);
@ -906,8 +906,8 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
private function getMaxLeaseTime() {
$return = null;
if (!empty($this->attributes['dhcpStatements'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
if (substr($this->attributes['dhcpStatements'][$i], 0, 15) == (self::MAX_LEASE_TIME . ' ')) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (substr($this->attributes['dhcpStatements'][$i], 0, 15) === self::MAX_LEASE_TIME . ' ') {
$return = substr($this->attributes['dhcpStatements'][$i], 15);
break;
}
@ -925,8 +925,8 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
if (!is_array($this->attributes['dhcpStatements'])) {
$this->attributes['dhcpStatements'] = [];
}
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
if (substr($this->attributes['dhcpStatements'][$i], 0, 15) == (self::MAX_LEASE_TIME . ' ')) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if (substr($this->attributes['dhcpStatements'][$i], 0, 15) === self::MAX_LEASE_TIME . ' ') {
unset($this->attributes['dhcpStatements'][$i]);
$this->attributes['dhcpStatements'] = array_values($this->attributes['dhcpStatements']);
}
@ -943,7 +943,7 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
*/
private function isAuthoritative(): bool {
if (!empty($this->attributes['dhcpStatements'])) {
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if ($this->attributes['dhcpStatements'][$i] === self::AUTHORITATIVE) {
return true;
}
@ -961,7 +961,7 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
if (!is_array($this->attributes['dhcpStatements'])) {
$this->attributes['dhcpStatements'] = [];
}
for ($i = 0; $i < sizeof($this->attributes['dhcpStatements']); $i++) {
for ($i = 0; $i < count($this->attributes['dhcpStatements']); $i++) {
if ($this->attributes['dhcpStatements'][$i] === self::AUTHORITATIVE) {
unset($this->attributes['dhcpStatements'][$i]);
$this->attributes['dhcpStatements'] = array_values($this->attributes['dhcpStatements']);
@ -1071,7 +1071,7 @@ By default, the nodes are configured as H-Nodes which fits for small networks. I
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("dhcpOptions", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "dhcpOptions";

View file

@ -60,7 +60,7 @@ class eduPerson extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['user']);
return $this->get_scope() === 'user';
}
/**
@ -158,7 +158,7 @@ class eduPerson extends baseModule {
]];
// profile options
$profileContainer = new htmlResponsiveRow();
$profileContainer->add(new htmlResponsiveInputCheckbox('eduPerson_addExt', false, _('Automatically add this extension'), 'autoAdd'), 12);
$profileContainer->add(new htmlResponsiveInputCheckbox('eduPerson_addExt', false, _('Automatically add this extension'), 'autoAdd'));
$return['profile_options'] = $profileContainer;
// upload fields
$return['upload_columns'] = [
@ -273,10 +273,7 @@ class eduPerson extends baseModule {
* @return boolean true, if all is ok
*/
function module_complete() {
if (($this->getAccountContainer()->rdn == 'eduPersonPrincipalName') && !isset($this->attributes['eduPersonPrincipalName'][0])) {
return false;
}
return true;
return ($this->getAccountContainer()->rdn !== 'eduPersonPrincipalName') || isset($this->attributes['eduPersonPrincipalName'][0]);
}
/**
@ -294,14 +291,14 @@ class eduPerson extends baseModule {
if (isset($this->attributes['eduPersonPrimaryAffiliation'][0])) {
$primaryAffiliation = [$this->attributes['eduPersonPrimaryAffiliation'][0]];
}
$return->add(new htmlResponsiveSelect('primaryAffiliation', $this->affiliationTypes, $primaryAffiliation, _('Primary affiliation'), 'primaryAffiliation'), 12);
$return->add(new htmlResponsiveSelect('primaryAffiliation', $this->affiliationTypes, $primaryAffiliation, _('Primary affiliation'), 'primaryAffiliation'));
// scoped affiliations
$scopedAffiliationLabel = new htmlOutputText(_('Scoped affiliations'));
$scopedAffiliationLabel->alignment = htmlElement::ALIGN_TOP;
$return->addLabel($scopedAffiliationLabel);
$scopedAffiliations = new htmlTable();
if (isset($this->attributes['eduPersonScopedAffiliation'][0])) {
for ($i = 0; $i < sizeof($this->attributes['eduPersonScopedAffiliation']); $i++) {
for ($i = 0; $i < count($this->attributes['eduPersonScopedAffiliation']); $i++) {
$parts = explode('@', $this->attributes['eduPersonScopedAffiliation'][$i]);
$scopedAffiliationPrefix = [$parts[0]];
$scopedAffiliation = substr($this->attributes['eduPersonScopedAffiliation'][$i], strlen($parts[0]) + 1);
@ -310,7 +307,7 @@ class eduPerson extends baseModule {
$scopedAffiliationContainer->addElement(new htmlOutputText('@'));
$scopedAffiliationContainer->addElement(new htmlInputField('scopedAffiliation' . $i, $scopedAffiliation));
$scopedAffiliationContainer->addElement(new htmlButton('deleduPersonScopedAffiliation' . $i, 'del.svg', true));
if ($i == (sizeof($this->attributes['eduPersonScopedAffiliation']) - 1)) {
if ($i === count($this->attributes['eduPersonScopedAffiliation']) - 1) {
$scopedAffiliationContainer->addElement(new htmlButton('addeduPersonScopedAffiliation', 'add.svg', true));
}
$scopedAffiliations->addElement($scopedAffiliationContainer, true);
@ -321,14 +318,14 @@ class eduPerson extends baseModule {
$scopedAffiliationContainer->addElement(new htmlOutputText('-'));
$scopedAffiliationContainer->addElement(new htmlSpacer('10px', null));
$scopedAffiliationContainer->addElement(new htmlButton('addeduPersonScopedAffiliation', 'add.svg', true));
$scopedAffiliationContainer->addElement(new htmlHelpLink('scopedAffiliation'), true);
$scopedAffiliationContainer->addElement(new htmlHelpLink('scopedAffiliation'));
$scopedAffiliations->addElement($scopedAffiliationContainer);
}
$return->addField($scopedAffiliations);
// affiliations
$affiliations = new htmlTable();
if (isset($this->attributes['eduPersonAffiliation'][0])) {
for ($i = 0; $i < sizeof($this->attributes['eduPersonAffiliation']); $i++) {
for ($i = 0; $i < count($this->attributes['eduPersonAffiliation']); $i++) {
$affiliations->addElement(new htmlSelect('affiliation' . $i, $this->affiliationTypes, [$this->attributes['eduPersonAffiliation'][$i]]));
$affiliationButton = new htmlButton('delAffiliation' . $i, 'del.svg', true);
$affiliations->addElement($affiliationButton);
@ -368,7 +365,7 @@ class eduPerson extends baseModule {
$return->add($remButton, 12, 12, 12, 'text-center');
}
else {
$return->add(new htmlButton('addObjectClass', _('Add EDU person extension')), 12);
$return->add(new htmlButton('addObjectClass', _('Add EDU person extension')));
}
return $return;
}
@ -386,7 +383,7 @@ class eduPerson extends baseModule {
}
elseif (isset($_POST['remObjectClass'])) {
$this->attributes['objectClass'] = array_delete(['eduPerson'], $this->attributes['objectClass']);
for ($i = 0; $i < sizeof($this->meta['attributes']); $i++) {
for ($i = 0; $i < count($this->meta['attributes']); $i++) {
if (isset($this->attributes[$this->meta['attributes'][$i]])) {
unset($this->attributes[$this->meta['attributes'][$i]]);
}
@ -474,7 +471,7 @@ class eduPerson extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("eduPerson", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "eduPerson";
@ -483,7 +480,7 @@ class eduPerson extends baseModule {
if ($rawAccounts[$i][$ids['eduPerson_principalName']] != "") {
if (!preg_match('/^[0-9a-z_\\.@-]+$/i', $rawAccounts[$i][$ids['eduPerson_principalName']])) {
$error = $this->messages['eduPersonPrincipalName'][1];
array_push($error, $i);
$error[] = $i;
$messages[] = $error;
}
else {
@ -494,7 +491,7 @@ class eduPerson extends baseModule {
if ($rawAccounts[$i][$ids['eduPerson_primaryAffiliation']] != "") {
if (!in_array($rawAccounts[$i][$ids['eduPerson_primaryAffiliation']], $this->affiliationTypes)) {
$error = $this->messages['primaryAffiliation'][0];
array_push($error, $i);
$error[] = $i;
$messages[] = $error;
}
else {
@ -504,11 +501,11 @@ class eduPerson extends baseModule {
// scoped affiliations
if ($rawAccounts[$i][$ids['eduPerson_scopedAffiliation']] != "") {
$parts = explode(', ', $rawAccounts[$i][$ids['eduPerson_scopedAffiliation']]);
for ($a = 0; $a < sizeof($parts); $a++) {
for ($a = 0; $a < count($parts); $a++) {
$subparts = explode('@', $parts[$a]);
if (!in_array($subparts[0], $this->affiliationTypes)) {
$error = $this->messages['scopedAffiliation'][0];
array_push($error, $i);
$error[] = $i;
$messages[] = $error;
}
else {
@ -520,11 +517,11 @@ class eduPerson extends baseModule {
if ($rawAccounts[$i][$ids['eduPerson_affiliation']] != "") {
$parts = explode(', ', $rawAccounts[$i][$ids['eduPerson_affiliation']]);
$valid = true;
for ($a = 0; $a < sizeof($parts); $a++) {
for ($a = 0; $a < count($parts); $a++) {
if (!in_array($parts[$a], $this->affiliationTypes)) {
$valid = false;
$error = $this->messages['affiliation'][0];
array_push($error, $i);
$error[] = $i;
$messages[] = $error;
break;
}

View file

@ -204,13 +204,13 @@ class fixed_ip extends baseModule {
// Only run it, when ranges already exists:
if (is_array($this->fixed_ip)) {
$ex_subnet = explode(".", $this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0]);
foreach ($this->fixed_ip as $id => $arr) {
if (!empty($this->fixed_ip[$id]['ip']) && !range::check_subnet_range($this->fixed_ip[$id]['ip'],
foreach ($this->fixed_ip as $id => $value) {
if (!empty($value['ip']) && !range::check_subnet_range($value['ip'],
$this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0],
$this->getAccountContainer()->getAccountModule('dhcp_settings')->getDHCPOption('subnet-mask'))) {
// Range anpassen:
$ex = explode(".", $this->fixed_ip[$id]['ip']);
$tmp = $this->fixed_ip[$id]['ip'];
$ex = explode(".", $value['ip']);
$tmp = $value['ip'];
$this->fixed_ip[$id]['ip'] = $ex_subnet['0'] . "." . $ex_subnet['1'] . "." . $ex_subnet['2'] . "." . $ex['3'];
if ($tmp != $this->fixed_ip[$id]['ip']) {
$ip_edit = true;
@ -230,7 +230,7 @@ class fixed_ip extends baseModule {
if (!$this->isRootNode()) {
$searchAttributes = ['cn', 'dhcphwaddress', 'dhcpstatements', 'dhcpcomments'];
$entries = searchLDAP($this->getAccountContainer()->dn_orig, '(objectClass=dhcpHost)', $searchAttributes);
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$dhcphwaddress = explode(" ", $entries[$i]['dhcphwaddress'][0]);
$dhcphwaddress = array_pop($dhcphwaddress);
$dhcpstatements = [];
@ -273,7 +273,7 @@ class fixed_ip extends baseModule {
}
natcasesort($order);
$newVal = [];
foreach ($order as $index => $sortval) {
foreach (array_keys($order) as $index) {
$newVal[] = $this->fixed_ip[$index];
}
$this->fixed_ip = $newVal;
@ -410,7 +410,7 @@ class fixed_ip extends baseModule {
$this->initCache();
// auto-completion for host names
$autoNames = [];
if (!empty($this->hostCache) && (sizeof($this->hostCache) < 200)) {
if (!empty($this->hostCache) && (count($this->hostCache) < 200)) {
foreach ($this->hostCache as $attrs) {
if (!empty($attrs['cn'][0])) {
$autoNames[] = $attrs['cn'][0];
@ -429,21 +429,21 @@ class fixed_ip extends baseModule {
}
$pcs = [];
$messages = [];
foreach ($this->fixed_ip as $id => $arr) {
foreach ($this->fixed_ip as $id => $value) {
// pc name
$existsInDifferentDn = false;
if (!empty($_POST['pc_' . $id])) {
$existsInDifferentDn = $this->hostNameExists($_POST['pc_' . $id]);
}
if ($this->processed) {
if (strlen($this->fixed_ip[$id]['cn']) > 20) {
$messages[] = new htmlStatusMessage('ERROR', _("The PC name may not be longer than 20 characters."), htmlspecialchars($this->fixed_ip[$id]['cn']));
if (strlen($value['cn']) > 20) {
$messages[] = new htmlStatusMessage('ERROR', _("The PC name may not be longer than 20 characters."), htmlspecialchars($value['cn']));
}
elseif (strlen($this->fixed_ip[$id]['cn']) < 2) {
$messages[] = new htmlStatusMessage('ERROR', _("The PC name needs to be at least 2 characters long."), htmlspecialchars($this->fixed_ip[$id]['cn']));
elseif (strlen($value['cn']) < 2) {
$messages[] = new htmlStatusMessage('ERROR', _("The PC name needs to be at least 2 characters long."), htmlspecialchars($value['cn']));
}
elseif (in_array($this->fixed_ip[$id]['cn'], $pcs)) {
$messages[] = new htmlStatusMessage('ERROR', _("This PC name already exists."), htmlspecialchars($this->fixed_ip[$id]['cn']));
elseif (in_array($value['cn'], $pcs)) {
$messages[] = new htmlStatusMessage('ERROR', _("This PC name already exists."), htmlspecialchars($value['cn']));
}
elseif (isset($_POST['pc_' . $id]) && !preg_match("/^[A-Za-z0-9\\._-]*$/", $_POST['pc_' . $id])) {
$messages[] = new htmlStatusMessage('ERROR', _("The PC name may only contain A-Z, a-z and 0-9."), htmlspecialchars($_POST['pc_' . $id]));
@ -452,42 +452,42 @@ class fixed_ip extends baseModule {
$messages[] = new htmlStatusMessage('ERROR', sprintf(_('This PC name already exists in %s. Use e.g. %s.'), $existsInDifferentDn[0], $existsInDifferentDn[1]));
}
}
$pcs[] = $this->fixed_ip[$id]['cn'];
$pcs[] = $value['cn'];
// MAC address
if ($this->processed && $this->check_mac($this->fixed_ip[$id]['mac'])) {
$messages[] = new htmlStatusMessage('ERROR', _("Invalid MAC address."), htmlspecialchars($this->fixed_ip[$id]['mac']));
if ($this->processed && $this->check_mac($value['mac'])) {
$messages[] = new htmlStatusMessage('ERROR', _("Invalid MAC address."), htmlspecialchars($value['mac']));
}
// description
if ($this->processed && !get_preg($this->fixed_ip[$id]['description'], 'ascii')) {
$messages[] = new htmlStatusMessage('ERROR', _("Invalid description."), htmlspecialchars($this->fixed_ip[$id]['description']));
if ($this->processed && !get_preg($value['description'], 'ascii')) {
$messages[] = new htmlStatusMessage('ERROR', _("Invalid description."), htmlspecialchars($value['description']));
}
// fixed ip
if ($this->processed && !empty($this->fixed_ip[$id]['ip'])) {
if (!check_ip($this->fixed_ip[$id]['ip'])) {
$messages[] = new htmlStatusMessage('ERROR', _("The IP address is invalid."), htmlspecialchars($this->fixed_ip[$id]['ip']));
if ($this->processed && !empty($value['ip'])) {
if (!check_ip($value['ip'])) {
$messages[] = new htmlStatusMessage('ERROR', _("The IP address is invalid."), htmlspecialchars($value['ip']));
}
elseif (!range::check_subnet_range($this->fixed_ip[$id]['ip'],
elseif (!range::check_subnet_range($value['ip'],
$this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0],
$this->getAccountContainer()->getAccountModule('dhcp_settings')->getDHCPOption('subnet-mask'))) {
$messages[] = new htmlStatusMessage('ERROR', _("The IP address does not match the subnet."), htmlspecialchars($this->fixed_ip[$id]['ip']));
$messages[] = new htmlStatusMessage('ERROR', _("The IP address does not match the subnet."), htmlspecialchars($value['ip']));
}
elseif (!$this->isNotOverlappedIp($this->fixed_ip[$id]['ip'])) {
$messages[] = new htmlStatusMessage('ERROR', _("The IP address is already in use."), htmlspecialchars($this->fixed_ip[$id]['ip']));
elseif (!$this->isNotOverlappedIp($value['ip'])) {
$messages[] = new htmlStatusMessage('ERROR', _("The IP address is already in use."), htmlspecialchars($value['ip']));
}
}
$entry = [];
$entry[] = new htmlInputField('ip_' . $id, $this->fixed_ip[$id]['ip']);
$pcInput = new htmlInputField('pc_' . $id, $this->fixed_ip[$id]['cn']);
$entry[] = new htmlInputField('ip_' . $id, $value['ip']);
$pcInput = new htmlInputField('pc_' . $id, $value['cn']);
if (!empty($autoNames)) {
$pcInput->enableAutocompletion($autoNames);
}
$entry[] = $pcInput;
$entry[] = new htmlInputField('mac_' . $id, $this->fixed_ip[$id]['mac']);
$entry[] = new htmlInputField('description_' . $id, $this->fixed_ip[$id]['description']);
$entry[] = new htmlInputCheckbox('active_' . $id, $this->fixed_ip[$id]['active']);
$entry[] = new htmlInputField('mac_' . $id, $value['mac']);
$entry[] = new htmlInputField('description_' . $id, $value['description']);
$entry[] = new htmlInputCheckbox('active_' . $id, $value['active']);
$entry[] = new htmlButton('drop_ip_' . $id, 'del.svg', true);
$data[] = $entry;
}
@ -552,7 +552,7 @@ class fixed_ip extends baseModule {
$matches = [];
$number = 0;
$namePrefix = $name;
if (preg_match('/(.*[^0-9])([0-9]+)/', $name, $matches)) {
if (preg_match('/(.*[^0-9])(\d+)/', $name, $matches)) {
$namePrefix = $matches[1];
$number = $matches[2];
}
@ -753,7 +753,7 @@ class fixed_ip extends baseModule {
*/
function get_pdfEntries($pdfKeys, $typeId) {
$return = [];
if (is_array($this->fixed_ip) && (sizeof($this->fixed_ip) > 0)) {
if (is_array($this->fixed_ip) && ($this->fixed_ip !== [])) {
$pdfTable = new PDFTable();
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell(_('PC name'), '20%', null, true);
@ -762,7 +762,7 @@ class fixed_ip extends baseModule {
$pdfRow->cells[] = new PDFTableCell(_('Active'), '10%', null, true);
$pdfRow->cells[] = new PDFTableCell(_('Description'), '30%', null, true);
$pdfTable->rows[] = $pdfRow;
for ($i = 0; $i < sizeof($this->fixed_ip); $i++) {
for ($i = 0; $i < count($this->fixed_ip); $i++) {
$name = $this->fixed_ip[$i]['cn'];
$mac = $this->fixed_ip[$i]['mac'];
$ip = $this->fixed_ip[$i]['ip'];
@ -792,7 +792,7 @@ class fixed_ip extends baseModule {
public static function extractIP($dhcpStatements) {
$return = null;
if (is_array($dhcpStatements)) {
for ($i = 0; $i < sizeof($dhcpStatements); $i++) {
for ($i = 0; $i < count($dhcpStatements); $i++) {
if (str_starts_with($dhcpStatements[$i], 'fixed-address ')) {
$return = substr($dhcpStatements[$i], strlen('fixed-address') + 1);
break;
@ -809,7 +809,7 @@ class fixed_ip extends baseModule {
* @param String $ip new IP
*/
private function setIP(&$dhcpStatements, $ip) {
for ($i = 0; $i < sizeof($dhcpStatements); $i++) {
for ($i = 0; $i < count($dhcpStatements); $i++) {
if (str_starts_with($dhcpStatements[$i], 'fixed-address ')) {
unset($dhcpStatements[$i]);
$dhcpStatements = array_values($dhcpStatements);
@ -827,10 +827,10 @@ class fixed_ip extends baseModule {
*/
public static function isActive($dhcpStatements) {
if (is_array($dhcpStatements)) {
for ($i = 0; $i < sizeof($dhcpStatements); $i++) {
for ($i = 0; $i < count($dhcpStatements); $i++) {
if (strpos($dhcpStatements[$i], ' booting') === (strlen($dhcpStatements[$i]) - strlen(' booting'))) {
$val = substr($dhcpStatements[$i], 0, (strlen($dhcpStatements[$i]) - strlen(' booting')));
if ($val == 'deny') {
if ($val === 'deny') {
return false;
}
break;
@ -847,18 +847,13 @@ class fixed_ip extends baseModule {
* @param boolean $active is active
*/
private function setActive(&$dhcpStatements, $active) {
for ($i = 0; $i < sizeof($dhcpStatements); $i++) {
for ($i = 0; $i < count($dhcpStatements); $i++) {
if (str_contains($dhcpStatements[$i], ' booting')) {
unset($dhcpStatements[$i]);
$dhcpStatements = array_values($dhcpStatements);
}
}
if ($active) {
$dhcpStatements[] = 'allow booting';
}
else {
$dhcpStatements[] = 'deny booting';
}
$dhcpStatements[] = $active ? 'allow booting' : 'deny booting';
}
/**
@ -920,10 +915,10 @@ class fixed_ip extends baseModule {
return function(array $entry, string $attribute): ?htmlElement {
// find all fixed addresses:
$entries = searchLDAP($entry['dn'], 'objectClass=dhcpHost', ['dhcpstatements', 'dhcphwaddress', 'cn']);
if (sizeof($entries) > 0) {
if (count($entries) > 0) {
// sort by IP
$order = [];
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$order[$i] = '';
if (!empty($entries[$i]['dhcpstatements'])) {
$order[$i] = fixed_ip::extractIP($entries[$i]['dhcpstatements']);
@ -931,7 +926,7 @@ class fixed_ip extends baseModule {
}
$group = new htmlGroup();
natcasesort($order);
for ($i = 0; $i < sizeof($order); $i++) {
for ($i = 0; $i < count($order); $i++) {
$dhcpstatements = [];
if (isset($entries[$i]['dhcpstatements'][0])) {
$dhcpstatements = $entries[$i]['dhcpstatements'];
@ -959,7 +954,7 @@ class fixed_ip extends baseModule {
$name->setCSSClasses($cssClasses);
$group->addElement($name);
$group->addElement(new htmlOutputText('<br>', false));
if ($i < (sizeof($order) - 1)) {
if ($i < (count($order) - 1)) {
$group->addElement(new htmlOutputText('<br>', false));
}
}

View file

@ -188,7 +188,7 @@ class freeRadius extends baseModule {
$return['profile_mappings']['freeRadius_radiusProfileDn'] = 'radiusProfileDn';
}
$profileContainer = new htmlResponsiveRow();
for ($i = 0; $i < sizeof($profileElements); $i++) {
for ($i = 0; $i < count($profileElements); $i++) {
$profileContainer->add($profileElements[$i]);
}
$return['profile_options'] = $profileContainer;
@ -449,7 +449,7 @@ class freeRadius extends baseModule {
}
elseif (isset($_POST['remObjectClass'])) {
$this->attributes['objectClass'] = array_delete(['radiusprofile'], $this->attributes['objectClass']);
for ($i = 0; $i < sizeof($this->meta['attributes']); $i++) {
for ($i = 0; $i < count($this->meta['attributes']); $i++) {
if (isset($this->attributes[$this->meta['attributes'][$i]])) {
unset($this->attributes[$this->meta['attributes'][$i]]);
}
@ -557,7 +557,7 @@ class freeRadius extends baseModule {
// find button name
$buttonName = '';
$postKeys = array_keys($_POST);
for ($i = 0; $i < sizeof($postKeys); $i++) {
for ($i = 0; $i < count($postKeys); $i++) {
if (str_contains($postKeys[$i], 'form_subpage_freeRadius_attributes_')) {
$buttonName = $postKeys[$i];
}
@ -570,7 +570,7 @@ class freeRadius extends baseModule {
if (str_contains($buttonName, 'radiusExpiration')) {
$attr = 'radiusExpiration';
}
if ($attr == '') {
if ($attr === '') {
return [];
}
// determine action
@ -613,7 +613,7 @@ class freeRadius extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$errors = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("radiusprofile", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "radiusprofile";
@ -697,7 +697,7 @@ class freeRadius extends baseModule {
&& isset($options['freeRadius_radiusGroupName'][0])
&& ($options['freeRadius_radiusGroupName'][0] != '')) {
$list = preg_split('/;[ ]*/', $options['freeRadius_radiusGroupName'][0]);
for ($i = 0; $i < sizeof($list); $i++) {
for ($i = 0; $i < count($list); $i++) {
if (!get_preg($list[$i], 'groupname')) {
$messages[] = $this->messages['radiusGroupName'][0];
break;
@ -716,10 +716,10 @@ class freeRadius extends baseModule {
// profile mappings in meta data
parent::load_profile($profile);
// add extension
if (isset($profile['freeRadius_addExt'][0]) && ($profile['freeRadius_addExt'][0] === "true")) {
if (!in_array('radiusprofile', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'radiusprofile';
}
if (isset($profile['freeRadius_addExt'][0])
&& ($profile['freeRadius_addExt'][0] === "true")
&& !in_array('radiusprofile', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'radiusprofile';
}
// group names
if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusGroupName')

View file

@ -190,7 +190,7 @@ class hostObject extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("hostObject", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "hostObject";
@ -220,14 +220,13 @@ class hostObject extends baseModule {
// profile mappings in meta data
parent::load_profile($profile);
// add extension
if (isset($profile['hostObject_addExt'][0]) && ($profile['hostObject_addExt'][0] == "true")) {
if (!in_array('hostObject', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'hostObject';
}
if (isset($profile['hostObject_addExt'][0])
&& ($profile['hostObject_addExt'][0] == "true")
&& !in_array('hostObject', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'hostObject';
}
$hostList = preg_split('/,[ ]*/', $profile['hostObject_host'][0]);
$this->attributes['host'] = $hostList;
}
/**

View file

@ -46,7 +46,7 @@ class ieee802device extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['host']);
return $this->get_scope() === 'host';
}
/**
@ -152,7 +152,7 @@ class ieee802device extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("ieee802Device", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "ieee802Device";

View file

@ -189,7 +189,7 @@ class imapAccess extends baseModule {
$attrs = array_merge($attrs, $this->getAccountContainer()->getAccountModule('posixAccount')->getAttributes());
}
}
$this->email = !empty($attrs['mail'][0]) ? $attrs['mail'][0] : '';
$this->email = empty($attrs['mail'][0]) ? '' : $attrs['mail'][0];
$this->user = '';
// extract user name from email address
if (empty($this->moduleSettings['ImapAccess_UserNameAttribute'][0]) || $this->moduleSettings['ImapAccess_UserNameAttribute'][0] == 'mail') {
@ -204,7 +204,7 @@ class imapAccess extends baseModule {
}
// extract user name from Unix user name (might be in inetOrgPerson/windowUser or posixAccount module)
else {
$this->user = !empty($attrs['uid'][0]) ? $attrs['uid'][0] : '';
$this->user = empty($attrs['uid'][0]) ? '' : $attrs['uid'][0];
}
if (empty($this->email)) {
@ -463,31 +463,29 @@ class imapAccess extends baseModule {
if ($this->isWrongDomain($email_domain)) {
$errors[] = $this->messages['managemailbox'][4];
}
elseif ($quota == '') {
try {
$this->runSetQuotaCommand($client, $root, '-1');
}
catch (Exception $e) {
$message = $this->messages['managemailbox'][7];
$message[] = $e->getMessage();
$errors[] = $message;
}
}
elseif (get_preg($quota, 'digit')) {
logNewMessage(LOG_DEBUG, 'Setting quota ' . $quota . ' for ' . $root);
try {
$this->runSetQuotaCommand($client, $root, $quota);
}
catch (Exception $e) {
$message = $this->messages['managemailbox'][7];
$message[] = $e->getMessage();
$errors[] = $message;
}
}
else {
if ($quota == '') {
try {
$this->runSetQuotaCommand($client, $root, '-1');
}
catch (Exception $e) {
$message = $this->messages['managemailbox'][7];
$message[] = $e->getMessage();
$errors[] = $message;
}
}
elseif (get_preg($quota, 'digit')) {
logNewMessage(LOG_DEBUG, 'Setting quota ' . $quota . ' for ' . $root);
try {
$this->runSetQuotaCommand($client, $root, $quota);
}
catch (Exception $e) {
$message = $this->messages['managemailbox'][7];
$message[] = $e->getMessage();
$errors[] = $message;
}
}
else {
$errors[] = $this->messages['managemailbox'][8];
}
$errors[] = $this->messages['managemailbox'][8];
}
return $errors;
}
@ -683,12 +681,7 @@ class imapAccess extends baseModule {
}
else {
$serverName = $this->moduleSettings['ImapAccess_ImapServerAddress'][0];
if ($encryptionType === "TLS") {
$port = 143;
}
else {
$port = 993;
}
$port = ($encryptionType === "TLS") ? 143 : 993;
}
$validateCertificate = !isset($this->moduleSettings['ImapAccess_ImapValidateServerCert'][0]) || ($this->moduleSettings['ImapAccess_ImapValidateServerCert'][0] !== 'novalidate-cert');
try {
@ -814,7 +807,7 @@ class imapAccess extends baseModule {
if (!isset($ids['imapAccess_createMailbox'])) {
return $errors;
}
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
if (isset($rawAccounts[$i][$ids['imapAccess_createMailbox']])
&& !in_array($rawAccounts[$i][$ids['imapAccess_createMailbox']], ['true', 'false'])) {
$errMsg = $this->messages['createMailbox'][0];
@ -884,7 +877,7 @@ class imapAccess extends baseModule {
];
}
// add mailbox
elseif ($temp['counter'] < sizeof($temp['users'])) {
elseif ($temp['counter'] < count($temp['users'])) {
$errors = [];
$data = $temp['users'][$temp['counter']];
$uid = $data['uid'];
@ -915,7 +908,7 @@ class imapAccess extends baseModule {
$temp['counter']++;
return [
'status' => 'inProgress',
'progress' => ($temp['counter'] * 100) / sizeof($temp['users']),
'progress' => ($temp['counter'] * 100) / count($temp['users']),
'errors' => $errors
];
}
@ -938,7 +931,7 @@ class imapAccess extends baseModule {
*/
private function isMailboxExisting($client, string $path): bool {
$list = $client->getConnection()->folders($path);
return ($list !== null) && is_array($list->data()) && (sizeof($list->data()) >= 1);
return ($list !== null) && is_array($list->data()) && (count($list->data()) >= 1);
}
/**

View file

@ -179,10 +179,10 @@ class inetLocalMailRecipient extends baseModule {
// profile mappings in meta data
parent::load_profile($profile);
// add extension
if (isset($profile['inetLocalMailRecipient_addExt'][0]) && ($profile['inetLocalMailRecipient_addExt'][0] == "true")) {
if (!in_array('inetLocalMailRecipient', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'inetLocalMailRecipient';
}
if (isset($profile['inetLocalMailRecipient_addExt'][0])
&& ($profile['inetLocalMailRecipient_addExt'][0] == "true")
&& !in_array('inetLocalMailRecipient', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'inetLocalMailRecipient';
}
}
@ -233,7 +233,7 @@ class inetLocalMailRecipient extends baseModule {
}
elseif (isset($_POST['remObjectClass'])) {
$this->attributes['objectClass'] = array_delete(['inetLocalMailRecipient'], $this->attributes['objectClass']);
for ($i = 0; $i < sizeof($this->meta['attributes']); $i++) {
for ($i = 0; $i < count($this->meta['attributes']); $i++) {
if (isset($this->attributes[$this->meta['attributes'][$i]])) {
unset($this->attributes[$this->meta['attributes'][$i]]);
}
@ -302,7 +302,7 @@ class inetLocalMailRecipient extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("inetLocalMailRecipient", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "inetLocalMailRecipient";

View file

@ -851,12 +851,9 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
if (!isset($this->attributes['sn'][0]) || ($this->attributes['sn'][0] == '')) {
return false;
}
if (!$this->isUnixActive()) {
if (($this->getAccountContainer()->rdn == 'uid') && !isset($this->attributes['uid'][0])) {
return false;
}
}
return true;
return $this->isUnixActive()
|| ($this->getAccountContainer()->rdn !== 'uid')
|| isset($this->attributes['uid'][0]);
}
/**
@ -907,7 +904,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
unset($return[$this->getAccountContainer()->dn_orig]['remove']['facsimileTelephoneNumber']);
}
if (isset($return[$this->getAccountContainer()->dn_orig]['add']['facsimileTelephoneNumber'])
&& isset($this->orig['facsimileTelephoneNumber']) && (sizeof($this->orig['facsimileTelephoneNumber']) > 0)) {
&& isset($this->orig['facsimileTelephoneNumber']) && (count($this->orig['facsimileTelephoneNumber']) > 0)) {
$return[$this->getAccountContainer()->dn_orig]['modify']['facsimileTelephoneNumber'] = $this->attributes['facsimileTelephoneNumber'];
unset($return[$this->getAccountContainer()->dn_orig]['add']['facsimileTelephoneNumber']);
}
@ -1024,7 +1021,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
// first name
if (!$this->isAdminReadOnly('givenName')) {
$this->attributes['givenName'][0] = trim($_POST['givenName']);
if (($this->attributes['givenName'][0] != '') && !get_preg($this->attributes['givenName'][0], 'realname')) {
if (($this->attributes['givenName'][0] !== '') && !get_preg($this->attributes['givenName'][0], 'realname')) {
$errors[] = $this->messages['givenName'][0];
}
}
@ -1035,12 +1032,10 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$this->processMultiValueInputTextField('mail', $errors, 'email');
if (!empty($this->attributes['mail'])) {
foreach ($this->attributes['mail'] as &$mail) {
if (empty($this->orig['mail']) || !in_array($mail, $this->orig['mail'])) {
if ($this->emailExists($mail)) {
$msg = $this->messages['mail'][1];
$msg[] = [htmlspecialchars($mail)];
$errors[] = $msg;
}
if ((empty($this->orig['mail']) || !in_array($mail, $this->orig['mail'])) && $this->emailExists($mail)) {
$msg = $this->messages['mail'][1];
$msg[] = [htmlspecialchars($mail)];
$errors[] = $msg;
}
}
}
@ -1079,7 +1074,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
if (!get_preg($this->attributes['postalAddress'][$addressCounter], 'postalAddress')) {
$errors[] = $this->messages['postalAddress'][0];
}
if ($this->attributes['postalAddress'][$addressCounter] == '') {
if ($this->attributes['postalAddress'][$addressCounter] === '') {
unset($this->attributes['postalAddress'][$addressCounter]);
}
$addressCounter++;
@ -1099,7 +1094,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
if (!get_preg($this->attributes['registeredAddress'][$addressCounter], 'postalAddress')) {
$errors[] = $this->messages['registeredAddress'][0];
}
if ($this->attributes['registeredAddress'][$addressCounter] == '') {
if ($this->attributes['registeredAddress'][$addressCounter] === '') {
unset($this->attributes['registeredAddress'][$addressCounter]);
}
$addressCounter++;
@ -1168,12 +1163,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
if (!$this->isAdminReadOnly('cn')) {
$this->processMultiValueInputTextField('cn', $errors, 'cn');
if (empty($this->attributes['cn'][0])) {
if ($_POST['givenName'] != '') {
$this->attributes['cn'][0] = $_POST['givenName'] . " " . $_POST['sn'];
}
else {
$this->attributes['cn'][0] = $_POST['sn'];
}
$this->attributes['cn'][0] = ($_POST['givenName'] != '') ? $_POST['givenName'] . " " . $_POST['sn'] : $_POST['sn'];
}
}
if (!$this->isAdminReadOnly('userPassword')) {
@ -1330,22 +1320,22 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
if (!$this->isBooleanConfigOptionSet('inetOrgPerson_hidePostalAddress')) {
$postalAddresses = [];
if (isset($this->attributes['postalAddress'][0])) {
for ($i = 0; $i < sizeof($this->attributes['postalAddress']); $i++) {
for ($i = 0; $i < count($this->attributes['postalAddress']); $i++) {
$postalAddresses[] = implode("\r\n", explode('$', $this->attributes['postalAddress'][$i]));
}
}
if (sizeof($postalAddresses) == 0) {
if (count($postalAddresses) == 0) {
$postalAddresses[] = '';
}
$addressLabel = new htmlOutputText(_('Postal address'));
$addressLabel->alignment = htmlElement::ALIGN_TOP;
$fieldContainer->addLabel($addressLabel);
$addressContainer = new htmlGroup();
for ($i = 0; $i < sizeof($postalAddresses); $i++) {
for ($i = 0; $i < count($postalAddresses); $i++) {
if ($this->isAdminReadOnly('postalAddress')) {
$val = str_replace("\r\n", '<br>', htmlspecialchars($postalAddresses[$i]));
$addressContainer->addElement(new htmlOutputText($val, false));
if ($i < (sizeof($postalAddresses) - 1)) {
if ($i < (count($postalAddresses) - 1)) {
$addressContainer->addElement(new htmlOutputText('<br>', false));
}
}
@ -1353,7 +1343,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$postalAddressTextarea = new htmlInputTextarea('postalAddress' . $i, $postalAddresses[$i], 30, 3);
$postalAddressTextarea->setAccessibilityLabel(_('Postal address'));
$addressContainer->addElement($postalAddressTextarea);
if ($i < (sizeof($postalAddresses) - 1)) {
if ($i < (count($postalAddresses) - 1)) {
$addressContainer->addElement(new htmlOutputText('<br>', false));
}
else {
@ -1371,22 +1361,22 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
if (!$this->isBooleanConfigOptionSet('inetOrgPerson_hideRegisteredAddress')) {
$registeredAddresses = [];
if (isset($this->attributes['registeredAddress'][0])) {
for ($i = 0; $i < sizeof($this->attributes['registeredAddress']); $i++) {
for ($i = 0; $i < count($this->attributes['registeredAddress']); $i++) {
$registeredAddresses[] = implode("\r\n", explode('$', $this->attributes['registeredAddress'][$i]));
}
}
if (sizeof($registeredAddresses) == 0) {
if (count($registeredAddresses) == 0) {
$registeredAddresses[] = '';
}
$registeredAddressLabel = new htmlOutputText(_('Registered address'));
$registeredAddressLabel->alignment = htmlElement::ALIGN_TOP;
$fieldContainer->addLabel($registeredAddressLabel);
$registeredAddressContainer = new htmlGroup();
for ($i = 0; $i < sizeof($registeredAddresses); $i++) {
for ($i = 0; $i < count($registeredAddresses); $i++) {
if ($this->isAdminReadOnly('registeredAddress')) {
$val = str_replace("\r\n", '<br>', htmlspecialchars($registeredAddresses[$i]));
$registeredAddressContainer->addElement(new htmlOutputText($val, false));
if ($i < (sizeof($registeredAddresses) - 1)) {
if ($i < (count($registeredAddresses) - 1)) {
$registeredAddressContainer->addElement(new htmlOutputText('<br>', false));
}
}
@ -1394,7 +1384,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$registeredAddressTextarea = new htmlInputTextarea('registeredAddress' . $i, $registeredAddresses[$i], 30, 3);
$registeredAddressTextarea->setAccessibilityLabel(_('Registered address'));
$registeredAddressContainer->addElement($registeredAddressTextarea);
if ($i < (sizeof($registeredAddresses) - 1)) {
if ($i < (count($registeredAddresses) - 1)) {
$registeredAddressContainer->addElement(new htmlOutputText('<br>', false));
}
else {
@ -1569,7 +1559,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$userCertificateGroup = new htmlGroup();
$userCertificateCount = 0;
if (isset($this->attributes['userCertificate;binary'])) {
$userCertificateCount = sizeof($this->attributes['userCertificate;binary']);
$userCertificateCount = count($this->attributes['userCertificate;binary']);
}
$userCertificateGroup->addElement(new htmlOutputText($userCertificateCount));
$userCertificateGroup->addElement(new htmlSpacer('10px', null));
@ -1591,14 +1581,14 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
}
if (isset($this->attributes['manager'][0])) {
$managerList = [];
for ($i = 0; $i < sizeof($this->attributes['manager']); $i++) {
for ($i = 0; $i < count($this->attributes['manager']); $i++) {
$managerList[] = $this->attributes['manager'][$i];
}
usort($managerList, 'compareDN');
$managers = new htmlTable();
$managers->alignment = htmlElement::ALIGN_RIGHT;
$managers->colspan = 3;
for ($i = 0; $i < sizeof($managerList); $i++) {
for ($i = 0; $i < count($managerList); $i++) {
$manager = new htmlOutputText(getAbstractDN($managerList[$i]));
$manager->alignment = htmlElement::ALIGN_RIGHT;
$managers->addElement($manager, true);
@ -1821,19 +1811,19 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$options = [];
$filter = get_ldap_filter('user');
$entries = searchLDAPByFilter('(|' . $filter . '(objectclass=organizationalRole))', ['dn'], ['user']);
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$entries[$i] = $entries[$i]['dn'];
}
// sort by DN
usort($entries, 'compareDN');
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
if (!isset($this->attributes['manager']) || !in_array($entries[$i], $this->attributes['manager'])) {
$options[getAbstractDN($entries[$i])] = $entries[$i];
}
}
$size = 20;
if (sizeof($options) < 20) {
$size = sizeof($options);
if (count($options) < 20) {
$size = count($options);
}
$managerSelect = new htmlSelect('manager', $options, [], $size);
$managerSelect->setHasDescriptiveElements(true);
@ -1864,14 +1854,14 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
// sort by DN
usort($managerTemp, 'compareDN');
$managers = [];
for ($i = 0; $i < sizeof($managerTemp); $i++) {
for ($i = 0; $i < count($managerTemp); $i++) {
$managers[getAbstractDN($managerTemp[$i])] = $managerTemp[$i];
}
$size = 20;
if (sizeof($this->attributes['manager']) < 20) {
$size = sizeof($this->attributes['manager']);
if (count($this->attributes['manager']) < 20) {
$size = count($this->attributes['manager']);
}
if (sizeof($managers) > 0) {
if ($managers !== []) {
$managerSelect = new htmlSelect('manager', $managers, [], $size);
$managerSelect->setHasDescriptiveElements(true);
$managerSelect->setMultiSelect(true);
@ -1904,7 +1894,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
}
if (isset($_POST['form_subpage_' . static::class . '_manager_remove']) && isset($_POST['manager'])) {
$managers = array_flip($this->attributes['manager']);
for ($i = 0; $i < sizeof($_POST['manager']); $i++) {
for ($i = 0; $i < count($_POST['manager']); $i++) {
if (isset($managers[$_POST['manager'][$i]])) {
unset($managers[$_POST['manager'][$i]]);
}
@ -1912,7 +1902,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$this->attributes['manager'] = array_values(array_flip($managers));
}
elseif (isset($_POST['form_subpage_' . static::class . '_manager_addManagers']) && isset($_POST['manager'])) {
for ($i = 0; $i < sizeof($_POST['manager']); $i++) {
for ($i = 0; $i < count($_POST['manager']); $i++) {
$this->attributes['manager'][] = $_POST['manager'][$i];
$this->attributes['manager'] = array_unique($this->attributes['manager']);
}
@ -1931,7 +1921,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$table = new htmlTable();
$table->colspan = 10;
$temFilesManager = new LamTemporaryFilesManager();
for ($i = 0; $i < sizeof($this->attributes['userCertificate;binary']); $i++) {
for ($i = 0; $i < count($this->attributes['userCertificate;binary']); $i++) {
$filename = $temFilesManager->registerTemporaryFile('.der');
$out = $temFilesManager->openTemporaryFileForWrite($filename);
fwrite($out, $this->attributes['userCertificate;binary'][$i]);
@ -1954,7 +1944,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
if (isset($pemData['name'])) {
$data[] = $pemData['name'];
}
if (sizeof($data) > 0) {
if ($data !== []) {
$table->addElement(new htmlOutputText(implode(': ', $data)));
}
}
@ -1992,7 +1982,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$pemData = explode("\n", $pemData);
array_shift($pemData);
$last = array_pop($pemData);
while (($last != '-----END CERTIFICATE-----') && sizeof($pemData) > 2) {
while (($last != '-----END CERTIFICATE-----') && (count($pemData) > 2)) {
$last = array_pop($pemData);
}
$pemData = implode('', $pemData);
@ -2005,7 +1995,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
}
}
elseif (isset($this->attributes['userCertificate;binary'])) {
for ($i = 0; $i < sizeof($this->attributes['userCertificate;binary']); $i++) {
for ($i = 0; $i < count($this->attributes['userCertificate;binary']); $i++) {
if (isset($_POST['form_subpage_' . static::class . '_userCertificate_delete_' . $i])) {
unset($this->attributes['userCertificate;binary'][$i]);
$this->attributes['userCertificate;binary'] = array_values($this->attributes['userCertificate;binary']);
@ -2031,10 +2021,9 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$fields['cn'] = _('Common name');
$fields['userPassword'] = _('Password');
}
if (!$this->isSamba3Active($modules)) {
if (!$this->isBooleanConfigOptionSet('inetOrgPerson_hidedisplayName', true)) {
$fields['displayName'] = _('Display name');
}
if (!$this->isSamba3Active($modules)
&& !$this->isBooleanConfigOptionSet('inetOrgPerson_hidedisplayName', true)) {
$fields['displayName'] = _('Display name');
}
return $fields;
}
@ -2132,10 +2121,10 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$this->addSimplePDFField($return, 'departmentNumber', _('Department'));
}
$this->addSimplePDFField($return, 'displayName', _('Display name'));
if (isset($this->clearTextPassword)) {
if ($this->clearTextPassword !== null) {
$this->addPDFKeyValue($return, 'userPassword', _('Password'), $this->clearTextPassword);
}
else if (isset($this->attributes['INFO.userPasswordClearText'])) {
elseif (isset($this->attributes['INFO.userPasswordClearText'])) {
$this->addPDFKeyValue($return, 'userPassword', _('Password'), $this->attributes['INFO.userPasswordClearText']);
}
if (!$this->isBooleanConfigOptionSet('inetOrgPerson_hidejpegPhoto')) {
@ -2221,9 +2210,9 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
if (!$this->isBooleanConfigOptionSet('inetOrgPerson_hideBusinessCategory')) {
$profileElements[] = new htmlResponsiveInputField(_('Business category'), 'inetOrgPerson_businessCategory', null, 'businessCategory');
}
if (sizeof($profileElements) > 0) {
if ($profileElements !== []) {
$profileContainer = new htmlResponsiveRow();
for ($i = 0; $i < sizeof($profileElements); $i++) {
for ($i = 0; $i < count($profileElements); $i++) {
$profileContainer->add($profileElements[$i]);
}
return $profileContainer;
@ -2245,13 +2234,13 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
if (!$this->isUnixActive() && !empty($profile['inetOrgPerson_cn'][0])) {
$this->attributes['cn'][0] = $profile['inetOrgPerson_cn'][0];
}
if (!$this->isBooleanConfigOptionSet('inetOrgPerson_hideDepartments')) {
// departments
if (isset($profile['inetOrgPerson_departmentNumber'][0]) && $profile['inetOrgPerson_departmentNumber'][0] != '') {
$departments = explode(';', $profile['inetOrgPerson_departmentNumber'][0]);
// remove extra spaces and set attributes
$this->attributes['departmentNumber'] = array_map('trim', $departments);
}
// departments
if (!$this->isBooleanConfigOptionSet('inetOrgPerson_hideDepartments')
&& isset($profile['inetOrgPerson_departmentNumber'][0])
&& ($profile['inetOrgPerson_departmentNumber'][0] != '')) {
$departments = explode(';', $profile['inetOrgPerson_departmentNumber'][0]);
// remove extra spaces and set attributes
$this->attributes['departmentNumber'] = array_map('trim', $departments);
}
if (!$this->isBooleanConfigOptionSet('inetOrgPerson_hideOu') && isset($profile['inetOrgPerson_ou'][0])) {
$oList = preg_split('/;[ ]*/', $profile['inetOrgPerson_ou'][0]);
@ -2306,7 +2295,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$messages = parent::check_profileOptions($options, $typeId);
if (!$this->isBooleanConfigOptionSet('inetOrgPerson_hideTelephoneNumber')) {
$telephoneNumberList = preg_split('/;[ ]*/', $options['inetOrgPerson_telephoneNumber'][0]);
for ($i = 0; $i < sizeof($telephoneNumberList); $i++) {
for ($i = 0; $i < count($telephoneNumberList); $i++) {
if (!get_preg($telephoneNumberList[$i], 'telephone')) {
$messages[] = $this->messages['telephoneNumber'][0];
break;
@ -2315,7 +2304,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
}
if (!$this->isBooleanConfigOptionSet('inetOrgPerson_hideFaxNumber')) {
$facsimileTelephoneNumberList = preg_split('/;[ ]*/', $options['inetOrgPerson_facsimileTelephoneNumber'][0]);
for ($i = 0; $i < sizeof($facsimileTelephoneNumberList); $i++) {
for ($i = 0; $i < count($facsimileTelephoneNumberList); $i++) {
if (!get_preg($facsimileTelephoneNumberList[$i], 'telephone')) {
$messages[] = $this->messages['facsimileTelephoneNumber'][0];
break;
@ -2384,14 +2373,14 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$errors = [];
// get list of existing users
$existingUsers = searchLDAPByAttribute('uid', '*', 'inetOrgPerson', ['uid'], ['user']);
for ($e = 0; $e < sizeof($existingUsers); $e++) {
for ($e = 0; $e < count($existingUsers); $e++) {
$existingUsers[$e] = $existingUsers[$e]['uid'][0];
}
$existingMails = searchLDAPByAttribute('mail', '*', 'inetOrgPerson', ['mail'], ['user']);
for ($e = 0; $e < sizeof($existingMails); $e++) {
for ($e = 0; $e < count($existingMails); $e++) {
$existingMails[$e] = $existingMails[$e]['mail'][0];
}
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
if (!in_array("inetOrgPerson", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "inetOrgPerson";
}
@ -2415,22 +2404,22 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$errors[] = $errMsg;
}
}
if (!$this->isUnixActive($selectedModules)) {
// uid
if (isset($ids['inetOrgPerson_userName']) && !empty($rawAccounts[$i][$ids['inetOrgPerson_userName']])) {
if (in_array($rawAccounts[$i][$ids['inetOrgPerson_userName']], $existingUsers)) {
$errMsg = $this->messages['uid'][3];
$errMsg[] = [$i];
$errors[] = $errMsg;
}
if (get_preg($rawAccounts[$i][$ids['inetOrgPerson_userName']], 'username')) {
$partialAccounts[$i]['uid'] = $rawAccounts[$i][$ids['inetOrgPerson_userName']];
}
else {
$errMsg = $this->messages['uid'][1];
$errMsg[] = [$i];
$errors[] = $errMsg;
}
// uid
if (!$this->isUnixActive($selectedModules)
&& isset($ids['inetOrgPerson_userName'])
&& !empty($rawAccounts[$i][$ids['inetOrgPerson_userName']])) {
if (in_array($rawAccounts[$i][$ids['inetOrgPerson_userName']], $existingUsers)) {
$errMsg = $this->messages['uid'][3];
$errMsg[] = [$i];
$errors[] = $errMsg;
}
if (get_preg($rawAccounts[$i][$ids['inetOrgPerson_userName']], 'username')) {
$partialAccounts[$i]['uid'] = $rawAccounts[$i][$ids['inetOrgPerson_userName']];
}
else {
$errMsg = $this->messages['uid'][1];
$errMsg[] = [$i];
$errors[] = $errMsg;
}
}
// initials
@ -2510,7 +2499,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
if (isset($ids['inetOrgPerson_email']) && ($rawAccounts[$i][$ids['inetOrgPerson_email']] != "")) {
$mailList = preg_split('/;[ ]*/', trim($rawAccounts[$i][$ids['inetOrgPerson_email']]));
$partialAccounts[$i]['mail'] = $mailList;
for ($x = 0; $x < sizeof($mailList); $x++) {
for ($x = 0; $x < count($mailList); $x++) {
if (!get_preg($mailList[$x], 'email')) {
$errMsg = $this->messages['email'][1];
$errMsg[] = [$i];
@ -2524,12 +2513,12 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
}
}
}
if (isLAMProVersion() && isset($ids['inetOrgPerson_sendPasswordMail']) && ($rawAccounts[$i][$ids['inetOrgPerson_sendPasswordMail']] != "")) {
if (!in_array($rawAccounts[$i][$ids['inetOrgPerson_sendPasswordMail']], ['true', 'false'])) {
$errMsg = $this->messages['sendPasswordMail'][0];
$errMsg[] = [$i];
$errors[] = $errMsg;
}
if (isLAMProVersion() && isset($ids['inetOrgPerson_sendPasswordMail'])
&& ($rawAccounts[$i][$ids['inetOrgPerson_sendPasswordMail']] != "")
&& !in_array($rawAccounts[$i][$ids['inetOrgPerson_sendPasswordMail']], ['true', 'false'])) {
$errMsg = $this->messages['sendPasswordMail'][0];
$errMsg[] = [$i];
$errors[] = $errMsg;
}
// labeledURI
if (isset($ids['inetOrgPerson_labeledURI']) && ($rawAccounts[$i][$ids['inetOrgPerson_labeledURI']] != "")) {
@ -2547,13 +2536,11 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$errors[] = $errMsg;
}
}
elseif ($partialAccounts[$i]['givenName'] != "") {
$partialAccounts[$i]['cn'] = $partialAccounts[$i]['givenName'] . " " . $partialAccounts[$i]['sn'];
}
else {
if ($partialAccounts[$i]['givenName'] != "") {
$partialAccounts[$i]['cn'] = $partialAccounts[$i]['givenName'] . " " . $partialAccounts[$i]['sn'];
}
else {
$partialAccounts[$i]['cn'] = $partialAccounts[$i]['sn'];
}
$partialAccounts[$i]['cn'] = $partialAccounts[$i]['sn'];
}
// password
$pwd_enabled = true;
@ -2583,18 +2570,16 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
elseif (!empty($this->moduleSettings['posixAccount_pwdHash'][0]) && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'K5KEY')) {
$partialAccounts[$i]['userpassword'] = pwd_hash('x', true, $this->moduleSettings['posixAccount_pwdHash'][0]);
}
// set normal password
else {
if (($rawAccounts[$i][$ids['inetOrgPerson_userPassword']] != "") && (get_preg($rawAccounts[$i][$ids['inetOrgPerson_userPassword']], 'password'))) {
$partialAccounts[$i]['userpassword'] = pwd_hash($rawAccounts[$i][$ids['inetOrgPerson_userPassword']], $pwd_enabled, $this->moduleSettings['posixAccount_pwdHash'][0]);
$partialAccounts[$i]['INFO.userPasswordClearText'] = $rawAccounts[$i][$ids['inetOrgPerson_userPassword']]; // for custom scripts etc.
}
elseif ($rawAccounts[$i][$ids['inetOrgPerson_userPassword']] != "") {
$errMsg = $this->messages['userPassword'][0];
$errMsg[2] = str_replace('%', '%%', $errMsg[2]); // double "%" because of later sprintf
$errMsg[] = [$i];
$errors[] = $errMsg;
}
elseif (($rawAccounts[$i][$ids['inetOrgPerson_userPassword']] != "") && (get_preg($rawAccounts[$i][$ids['inetOrgPerson_userPassword']], 'password'))) {
$partialAccounts[$i]['userpassword'] = pwd_hash($rawAccounts[$i][$ids['inetOrgPerson_userPassword']], $pwd_enabled, $this->moduleSettings['posixAccount_pwdHash'][0]);
$partialAccounts[$i]['INFO.userPasswordClearText'] = $rawAccounts[$i][$ids['inetOrgPerson_userPassword']];
// for custom scripts etc.
}
elseif ($rawAccounts[$i][$ids['inetOrgPerson_userPassword']] != "") {
$errMsg = $this->messages['userPassword'][0];
$errMsg[2] = str_replace('%', '%%', $errMsg[2]); // double "%" because of later sprintf
$errMsg[] = [$i];
$errors[] = $errMsg;
}
}
}
@ -2613,19 +2598,19 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$temp['counter'] = 0;
}
$errors = [];
$dataSize = sizeof($data);
$dataSize = count($data);
if (($temp['counter'] < $dataSize) && !in_array($temp['counter'], $failed)) {
// mail sending is LAM Pro only
if (isLAMProVersion()
&& isset($ids['inetOrgPerson_email'])
&& ($data[$temp['counter']][$ids['inetOrgPerson_email']] != "")) {
if (isset($ids['inetOrgPerson_sendPasswordMail']) && ($data[$temp['counter']][$ids['inetOrgPerson_sendPasswordMail']] == "true")
&& isset($accounts[$temp['counter']]['INFO.userPasswordClearText'])) {
$mailMessages = sendPasswordMail($accounts[$temp['counter']]['INFO.userPasswordClearText'], $accounts[$temp['counter']]);
for ($i = 0; $i < sizeof($mailMessages); $i++) {
if ($mailMessages[$i][0] == 'ERROR') {
$errors[] = $mailMessages[$i];
}
&& ($data[$temp['counter']][$ids['inetOrgPerson_email']] != "")
&& isset($ids['inetOrgPerson_sendPasswordMail'])
&& ($data[$temp['counter']][$ids['inetOrgPerson_sendPasswordMail']] == "true")
&& isset($accounts[$temp['counter']]['INFO.userPasswordClearText'])) {
$mailMessages = sendPasswordMail($accounts[$temp['counter']]['INFO.userPasswordClearText'], $accounts[$temp['counter']]);
for ($i = 0; $i < count($mailMessages); $i++) {
if ($mailMessages[$i][0] == 'ERROR') {
$errors[] = $mailMessages[$i];
}
}
}
@ -2646,19 +2631,20 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
}
}
// set password via exop
if (!empty($this->moduleSettings['posixAccount_pwdHash'][0]) && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'LDAP_EXOP')) {
if (isset($ids['inetOrgPerson_userPassword']) && !empty($data[$temp['counter']][$ids['inetOrgPerson_userPassword']])) {
$dn = $accounts[$temp['counter']]['dn'];
$password = $data[$temp['counter']][$ids['inetOrgPerson_userPassword']];
$success = ldap_exop_passwd($_SESSION['ldap']->server(), $dn, null, $password);
if (!$success) {
$errors[] = [
"ERROR",
_('Unable to set password'),
$dn . '<br>' . getDefaultLDAPErrorString($_SESSION['ldap']->server()),
[$temp['groups'][$temp['counter']]]
];
}
if (!empty($this->moduleSettings['posixAccount_pwdHash'][0])
&& ($this->moduleSettings['posixAccount_pwdHash'][0] === 'LDAP_EXOP')
&& isset($ids['inetOrgPerson_userPassword'])
&& !empty($data[$temp['counter']][$ids['inetOrgPerson_userPassword']])) {
$dn = $accounts[$temp['counter']]['dn'];
$password = $data[$temp['counter']][$ids['inetOrgPerson_userPassword']];
$success = ldap_exop_passwd($_SESSION['ldap']->server(), $dn, null, $password);
if (!$success) {
$errors[] = [
"ERROR",
_('Unable to set password'),
$dn . '<br>' . getDefaultLDAPErrorString($_SESSION['ldap']->server()),
[$temp['groups'][$temp['counter']]]
];
}
}
}
@ -2786,7 +2772,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
if (!empty($attributes['jpegPhoto'][0]) || !$readOnlyPhoto) {
$photoSub = new htmlDiv('inetOrgPersonPhotoUploadContent', $this->getSelfServicePhoto($readOnlyPhoto, false));
$photoRow = new htmlResponsiveRow();
$photoRow->add(self::getSelfServicePhotoJS($readOnlyPhoto), 0);
$photoRow->add($this->getSelfServicePhotoJS($readOnlyPhoto), 0);
$photoRow->addLabel(new htmlOutputText($this->getSelfServiceLabel('jpegPhoto', _('Photo'))));
$photoRow->addField(new htmlDiv('jpegPhotoDiv', $photoSub));
$return['jpegPhoto'] = $photoRow;
@ -2812,7 +2798,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$certTable = new htmlResponsiveRow();
$certTable->add(new htmlDiv('userCertificateDiv', $this->getSelfServiceUserCertificates()));
// JavaScript functions
$certTable->add(self::getSelfServiceUserCertificatesJSBlock());
$certTable->add($this->getSelfServiceUserCertificatesJSBlock());
// upload button
$uploadButtonGroup = new htmlGroup();
$uploadLabel = new htmlLabel('inetOrgPersonCertificate_file', _('Upload a file'));
@ -2986,7 +2972,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
* @param boolean $readOnly content is read-only
* @return htmlJavaScript JS block
*/
private static function getSelfServicePhotoJS($readOnly) {
private function getSelfServicePhotoJS($readOnly) {
if ($readOnly) {
return new htmlGroup();
}
@ -3067,10 +3053,10 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
private function getSelfServiceUserCertificates() {
$userCertificates = $_SESSION[self::SESS_CERTIFICATES_LIST];
$content = new htmlGroup();
if (sizeof($userCertificates) > 0) {
if (count($userCertificates) > 0) {
$certTable = new htmlResponsiveRow();
$tempFilesManager = new LamTemporaryFilesManager();
for ($i = 0; $i < sizeof($userCertificates); $i++) {
for ($i = 0; $i < count($userCertificates); $i++) {
$group = new htmlGroup();
$filename = $tempFilesManager->registerTemporaryFile('.der', 'userCertificate_');
$out = $tempFilesManager->openTemporaryFileForWrite($filename);
@ -3087,7 +3073,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
if (isset($pemData['name'])) {
$data[] = $pemData['name'];
}
if (sizeof($data) > 0) {
if ($data !== []) {
$group->addElement(new htmlOutputText(implode(': ', $data)));
$group->addElement(new htmlSpacer('5px', null));
}
@ -3114,7 +3100,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
*
* @return htmlJavaScript JS block
*/
private static function getSelfServiceUserCertificatesJSBlock() {
private function getSelfServiceUserCertificatesJSBlock() {
$content = '
function inetOrgPersonDeleteCertificate(id) {
var actionJSON = {
@ -3273,20 +3259,18 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$imageManipulator = ImageManipulationFactory::getImageManipulator($data);
$imageManipulator->crop($_POST['croppingDataX'], $_POST['croppingDataY'], $_POST['croppingDataWidth'], $_POST['croppingDataHeight']);
$data = $imageManipulator->getImageData();
$data = inetOrgPerson::resizeAndConvertImage($data, $moduleSettings);
$data = $this->resizeAndConvertImage($data, $moduleSettings);
if (!empty($moduleSettings['inetOrgPerson_jpegPhoto_maxSize'][0]) && ($moduleSettings['inetOrgPerson_jpegPhoto_maxSize'][0] < (strlen($data) / 1024))) {
$msg = $this->messages['file'][3];
$msg[] = null;
$msg[] = htmlspecialchars($moduleSettings['inetOrgPerson_jpegPhoto_maxSize'][0]);
$return['messages'][] = $msg;
}
elseif (!empty($attributes['jpegPhoto'][0])) {
$return['mod']['jpegPhoto'][0] = $data;
}
else {
if (!empty($attributes['jpegPhoto'][0])) {
$return['mod']['jpegPhoto'][0] = $data;
}
else {
$return['add']['jpegPhoto'][0] = $data;
}
$return['add']['jpegPhoto'][0] = $data;
}
}
catch (Exception $e) {
@ -3313,7 +3297,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$userCertificatesAttrName = 'userCertificate';
}
$attributeNames[] = $userCertificatesAttrName;
if (sizeof($userCertificates) > 0) {
if (count($userCertificates) > 0) {
$attributesNew[$userCertificatesAttrName] = $userCertificates;
}
elseif (isset($attributesNew[$userCertificatesAttrName])) {
@ -3349,7 +3333,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$readOnlyFields, null, null, null, 'displayName');
// find differences
for ($i = 0; $i < sizeof($attributeNames); $i++) {
for ($i = 0; $i < count($attributeNames); $i++) {
$attrName = $attributeNames[$i];
if (isset($attributes[$attrName]) && !isset($attributesNew[$attrName])) {
$return['del'][$attrName] = $attributes[$attrName];
@ -3359,7 +3343,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
}
else {
if (isset($attributes[$attrName])) {
for ($a = 0; $a < sizeof($attributes[$attrName]); $a++) {
for ($a = 0; $a < count($attributes[$attrName]); $a++) {
if (!in_array($attributes[$attrName][$a], $attributesNew[$attrName])) {
$return['mod'][$attrName] = $attributesNew[$attrName];
break;
@ -3367,7 +3351,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
}
}
if (isset($attributesNew[$attrName])) {
for ($a = 0; $a < sizeof($attributesNew[$attrName]); $a++) {
for ($a = 0; $a < count($attributesNew[$attrName]); $a++) {
if (!in_array($attributesNew[$attrName][$a], $attributes[$attrName])) {
$return['mod'][$attrName] = $attributesNew[$attrName];
break;
@ -3386,7 +3370,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
* @param array $settings settings
* @return array binary image data
*/
private static function resizeAndConvertImage($data, $settings) {
private function resizeAndConvertImage($data, $settings) {
include_once __DIR__ . '/../imageutils.inc';
$imageManipulator = ImageManipulationFactory::getImageManipulator($data);
// resize if maximum values specified
@ -3442,7 +3426,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$pemData = explode("\n", $pemData);
array_shift($pemData);
$last = array_pop($pemData);
while (($last != '-----END CERTIFICATE-----') && sizeof($pemData) > 2) {
while (($last != '-----END CERTIFICATE-----') && count($pemData) > 2) {
$last = array_pop($pemData);
}
$pemData = implode('', $pemData);
@ -3660,7 +3644,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
$titles = [];
$employeeTypes = [];
$businessCategories = [];
if (sizeof($attrs) > 0) {
if ($attrs !== []) {
$result = searchLDAPByFilter('(objectClass=inetOrgPerson)', $attrs, [$this->get_scope()]);
foreach ($result as $attributes) {
if (isset($attributes['departmentnumber'])) {
@ -3840,7 +3824,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
return $this->emailCheckCache[$mail];
}
$result = searchLDAPByAttribute('mail', $mail, 'inetOrgPerson', ['dn'], ['user']);
$this->emailCheckCache[$mail] = (sizeof($result) > 0);
$this->emailCheckCache[$mail] = (count($result) > 0);
return $this->emailCheckCache[$mail];
}
@ -4171,7 +4155,7 @@ class inetOrgPerson extends baseModule implements passwordService, AccountStatus
return function(array $entry, string $attribute): ?htmlElement {
$group = new htmlGroup();
if (isset($entry[$attribute][0]) && ($entry[$attribute][0] != '')) {
for ($i = 0; $i < sizeof($entry[$attribute]); $i++) {
for ($i = 0; $i < count($entry[$attribute]); $i++) {
if ($i > 0) {
$group->addElement(new htmlOutputText(", "));
}

View file

@ -56,7 +56,7 @@ class kolabGroup extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['group']);
return $this->get_scope() === 'group';
}
/**
@ -302,7 +302,7 @@ class kolabGroup extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// check if extension should be added
if (isset($rawAccounts[$i][$ids['kolabGroup_addExtension']]) && ($rawAccounts[$i][$ids['kolabGroup_addExtension']] != 'true')) {
continue;
@ -320,13 +320,13 @@ class kolabGroup extends baseModule {
}
else {
$errMsg = $this->messages['mail'][3];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$messages[] = $errMsg;
}
}
else {
$errMsg = $this->messages['mail'][1];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$messages[] = $errMsg;
}
}

View file

@ -57,7 +57,7 @@ class kolabSharedFolder extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['kolabSharedFolderType']);
return $this->get_scope() === 'kolabSharedFolderType';
}
/**
@ -261,14 +261,14 @@ class kolabSharedFolder extends baseModule {
// delegates
$delegatesData = searchLDAPByAttribute('mail', '*', 'inetOrgPerson', ['dn'], ['user']);
$delegates = [];
for ($i = 0; $i < sizeof($delegatesData); $i++) {
for ($i = 0; $i < count($delegatesData); $i++) {
$delegates[getAbstractDN($delegatesData[$i]['dn'])] = $delegatesData[$i]['dn'];
}
uksort($delegates, 'compareDN');
$container->add(new htmlSubTitle(_('Delegates')));
$delegatesContainer = new htmlTable();
if (isset($this->attributes['kolabDelegate'])) {
for ($i = 0; $i < sizeof($this->attributes['kolabDelegate']); $i++) {
for ($i = 0; $i < count($this->attributes['kolabDelegate']); $i++) {
$delegateSelect = new htmlSelect('delegate' . $i, $delegates, [$this->attributes['kolabDelegate'][$i]]);
$delegateSelect->setHasDescriptiveElements(true);
$delegateSelect->setSortElements(false);
@ -347,12 +347,12 @@ class kolabSharedFolder extends baseModule {
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
$delegates = searchLDAPByAttribute(null, null, 'inetOrgPerson', ['dn'], ['user']);
for ($d = 0; $d < sizeof($delegates); $d++) {
for ($d = 0; $d < count($delegates); $d++) {
if (isset($delegates[$d]['dn'])) {
$delegates[$d] = $delegates[$d]['dn'];
}
}
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object classes
if (!in_array('kolabSharedFolder', $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = 'kolabSharedFolder';
@ -379,14 +379,14 @@ class kolabSharedFolder extends baseModule {
if ($rawAccounts[$i][$ids['kolabSharedFolder_delegates']] != "") {
$newDelegates = explode(';', $rawAccounts[$i][$ids['kolabSharedFolder_delegates']]);
// check format
for ($d = 0; $d < sizeof($newDelegates); $d++) {
for ($d = 0; $d < count($newDelegates); $d++) {
if (in_array($newDelegates[$d], $delegates)) {
$partialAccounts[$i]['kolabDelegate'][] = $newDelegates[$d];
}
// invalid format
else {
$errMsg = $this->messages['delegate'][0];
array_push($errMsg, [$i, $newDelegates[$d]]);
$errMsg[] = [$i, $newDelegates[$d]];
$messages[] = $errMsg;
}
}
@ -439,7 +439,7 @@ class kolabSharedFolder extends baseModule {
return function(array $entry, string $attribute): ?htmlElement {
$group = new htmlGroup();
if (isset($entry[$attribute][0]) && ($entry[$attribute][0] != '')) {
for ($i = 0; $i < sizeof($entry[$attribute]); $i++) {
for ($i = 0; $i < count($entry[$attribute]); $i++) {
if ($i > 0) {
$group->addElement(new htmlOutputText(", "));
}

View file

@ -264,9 +264,9 @@ class kolabUser extends baseModule {
// default invitation policy
$defaultInvPol = $this->invitationPolicies['ACT_MANUAL'];
if (isset($this->attributes['kolabInvitationPolicy'])) {
for ($i = 0; $i < sizeof($this->attributes['kolabInvitationPolicy']); $i++) {
for ($i = 0; $i < count($this->attributes['kolabInvitationPolicy']); $i++) {
$parts = explode(":", $this->attributes['kolabInvitationPolicy'][$i]);
if (sizeof($parts) == 1) {
if (count($parts) == 1) {
$defaultInvPol = $this->invitationPolicies[$this->attributes['kolabInvitationPolicy'][$i]];
unset($this->attributes['kolabInvitationPolicy'][$i]);
$this->attributes['kolabInvitationPolicy'] = array_values($this->attributes['kolabInvitationPolicy']);
@ -279,9 +279,9 @@ class kolabUser extends baseModule {
$invitationContainer->addElement(new htmlHelpLink('invPol'), true);
// other invitation policies
if (isset($this->attributes['kolabInvitationPolicy'])) {
for ($i = 0; $i < sizeof($this->attributes['kolabInvitationPolicy']); $i++) {
for ($i = 0; $i < count($this->attributes['kolabInvitationPolicy']); $i++) {
$parts = explode(":", $this->attributes['kolabInvitationPolicy'][$i]);
if (sizeof($parts) == 2) {
if (count($parts) == 2) {
$invitationContainer->addElement(new htmlInputField('invPol1' . $i, $parts[0]));
$invitationContainer->addElement(new htmlSelect('invPol2' . $i, array_values($this->invitationPolicies), [$this->invitationPolicies[$parts[1]]]));
$invitationContainer->addElement(new htmlButton('delInvPol' . $i, 'del.svg', true));
@ -301,14 +301,14 @@ class kolabUser extends baseModule {
// delegates
$delegatesData = searchLDAPByAttribute('mail', '*', 'inetOrgPerson', ['dn'], ['user']);
$delegates = [];
for ($i = 0; $i < sizeof($delegatesData); $i++) {
for ($i = 0; $i < count($delegatesData); $i++) {
$delegates[getAbstractDN($delegatesData[$i]['dn'])] = $delegatesData[$i]['dn'];
}
uksort($delegates, 'compareDN');
$return->add(new htmlSubTitle(_('Delegates')));
$delegatesContainer = new htmlTable();
if (isset($this->attributes['kolabDelegate'])) {
for ($i = 0; $i < sizeof($this->attributes['kolabDelegate']); $i++) {
for ($i = 0; $i < count($this->attributes['kolabDelegate']); $i++) {
$delegateSelect = new htmlSelect('delegate' . $i, $delegates, [$this->attributes['kolabDelegate'][$i]]);
$delegateSelect->setSortElements(false);
$delegateSelect->setHasDescriptiveElements(true);
@ -499,12 +499,12 @@ class kolabUser extends baseModule {
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
$delegates = searchLDAPByAttribute(null, null, 'inetOrgPerson', ['mail'], ['user']);
for ($d = 0; $d < sizeof($delegates); $d++) {
for ($d = 0; $d < count($delegates); $d++) {
if (isset($delegates[$d]['dn'])) {
$delegates[$d] = $delegates[$d]['dn'];
}
}
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("kolabInetOrgPerson", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "kolabInetOrgPerson";
@ -529,10 +529,10 @@ class kolabUser extends baseModule {
// check format
$policies = array_keys($this->invitationPolicies);
$defaultFound = false;
for ($p = 0; $p < sizeof($pols); $p++) {
for ($p = 0; $p < count($pols); $p++) {
$parts = explode(":", $pols[$p]);
// default policy
if (sizeof($parts) == 1) {
if (count($parts) == 1) {
if (!$defaultFound && get_preg($parts[0], 'email')) {
$partialAccounts[$i]['kolabInvitationPolicy'][] = $parts[0];
}
@ -544,7 +544,7 @@ class kolabUser extends baseModule {
$defaultFound = true;
}
// additional policies
elseif (sizeof($parts) == 2) {
elseif (count($parts) == 2) {
if (get_preg($parts[0], 'email') && in_array($parts[1], $policies)) {
$partialAccounts[$i]['kolabInvitationPolicy'][] = $pols[$p];
}
@ -568,7 +568,7 @@ class kolabUser extends baseModule {
if ($rawAccounts[$i][$ids['kolabUser_delegates']] != "") {
$newDelegates = explode(';', $rawAccounts[$i][$ids['kolabUser_delegates']]);
// check format
for ($d = 0; $d < sizeof($newDelegates); $d++) {
for ($d = 0; $d < count($newDelegates); $d++) {
if (in_array($newDelegates[$d], $delegates)) {
$partialAccounts[$i]['kolabDelegate'][] = $newDelegates[$d];
}
@ -598,7 +598,7 @@ class kolabUser extends baseModule {
if (isset($this->attributes['kolabInvitationPolicy'][0])) {
// find default policy
$default = "";
for ($i = 0; $i < sizeof($this->attributes['kolabInvitationPolicy']); $i++) {
for ($i = 0; $i < count($this->attributes['kolabInvitationPolicy']); $i++) {
if (!strpos($this->attributes['kolabInvitationPolicy'][$i], ":")) {
$default = $this->attributes['kolabInvitationPolicy'][$i];
break;
@ -608,9 +608,9 @@ class kolabUser extends baseModule {
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell(_('Anyone') . ": " . $this->invitationPolicies[$default]);
$pdfTable->rows[] = $pdfRow;
for ($i = 0; $i < sizeof($this->attributes['kolabInvitationPolicy']); $i++) {
for ($i = 0; $i < count($this->attributes['kolabInvitationPolicy']); $i++) {
$parts = explode(':', $this->attributes['kolabInvitationPolicy'][$i]);
if (sizeof($parts) == 2) {
if (count($parts) == 2) {
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell($parts[0] . ": " . $this->invitationPolicies[$parts[1]]);
$pdfTable->rows[] = $pdfRow;
@ -656,7 +656,7 @@ class kolabUser extends baseModule {
if ($sr) {
$result = ldap_get_entries($_SESSION['ldapHandle']->getServer(), $sr);
cleanLDAPResult($result);
for ($i = 0; $i < sizeof($result); $i++) {
for ($i = 0; $i < count($result); $i++) {
$delegates[getAbstractDN($result[$i]['dn'])] = $result[$i]['dn'];
}
}
@ -664,7 +664,7 @@ class kolabUser extends baseModule {
if (isset($attributes['kolabDelegate'])) {
$kolabDelegate = $attributes['kolabDelegate'];
// do not show existing delegation candidates in selection list
for ($i = 0; $i < sizeof($kolabDelegate); $i++) {
for ($i = 0; $i < count($kolabDelegate); $i++) {
$key = array_search($kolabDelegate[$i], $delegates);
if ($key !== false) {
unset($delegates[$key]);
@ -674,7 +674,7 @@ class kolabUser extends baseModule {
uksort($delegates, 'compareDN');
$_SESSION['kolabUser_kolabDelegate'] = $kolabDelegate;
$delegateContainer = new htmlTable();
for ($i = 0; $i < sizeof($kolabDelegate); $i++) {
for ($i = 0; $i < count($kolabDelegate); $i++) {
$delegateContainer->addElement(new htmlOutputText($kolabDelegate[$i]));
if (!in_array('kolabDelegate', $readOnlyFields)) {
$delegateGroup = new htmlGroup();
@ -710,9 +710,9 @@ class kolabUser extends baseModule {
// default invitation policy
$defaultInvPol = $this->invitationPolicies['ACT_MANUAL'];
if (!empty($attributes['kolabInvitationPolicy'])) {
for ($i = 0; $i < sizeof($attributes['kolabInvitationPolicy']); $i++) {
for ($i = 0; $i < count($attributes['kolabInvitationPolicy']); $i++) {
$parts = explode(":", $attributes['kolabInvitationPolicy'][$i]);
if (sizeof($parts) == 1) {
if (count($parts) == 1) {
$defaultInvPol = $this->invitationPolicies[$attributes['kolabInvitationPolicy'][$i]];
unset($attributes['kolabInvitationPolicy'][$i]);
$attributes['kolabInvitationPolicy'] = array_values($attributes['kolabInvitationPolicy']);
@ -729,9 +729,9 @@ class kolabUser extends baseModule {
}
// other invitation policies
if (!empty($attributes['kolabInvitationPolicy'])) {
for ($i = 0; $i < sizeof($attributes['kolabInvitationPolicy']); $i++) {
for ($i = 0; $i < count($attributes['kolabInvitationPolicy']); $i++) {
$parts = explode(":", $attributes['kolabInvitationPolicy'][$i]);
if (sizeof($parts) == 2) {
if (count($parts) == 2) {
if (!in_array('kolabDelegate', $readOnlyFields)) {
$newPolicyInput = new htmlInputField('invPol1' . $i, $parts[0]);
$newPolicyInput->setAccessibilityLabel(_('Invitation policy'));
@ -809,7 +809,7 @@ class kolabUser extends baseModule {
}
// check for deleted delegations
$postKeys = array_keys($_POST);
for ($i = 0; $i < sizeof($postKeys); $i++) {
for ($i = 0; $i < count($postKeys); $i++) {
if (str_contains($postKeys[$i], 'delDelegate_')) {
$sKey = substr($postKeys[$i], strlen('delDelegate_'));
$key = array_search($_SESSION['kolabUser_kolabDelegate'][$sKey], $attributesNew['kolabDelegate']);
@ -865,7 +865,7 @@ class kolabUser extends baseModule {
}
}
// find differences
for ($i = 0; $i < sizeof($attributeNames); $i++) {
for ($i = 0; $i < count($attributeNames); $i++) {
$attrName = $attributeNames[$i];
if (isset($attributes[$attrName]) && !isset($attributesNew[$attrName])) {
$return['del'][$attrName] = $attributes[$attrName];
@ -875,7 +875,7 @@ class kolabUser extends baseModule {
}
else {
if (isset($attributes[$attrName])) {
for ($a = 0; $a < sizeof($attributes[$attrName]); $a++) {
for ($a = 0; $a < count($attributes[$attrName]); $a++) {
if (!in_array($attributes[$attrName][$a], $attributesNew[$attrName])) {
$return['mod'][$attrName] = $attributesNew[$attrName];
break;
@ -883,7 +883,7 @@ class kolabUser extends baseModule {
}
}
if (isset($attributesNew[$attrName])) {
for ($a = 0; $a < sizeof($attributesNew[$attrName]); $a++) {
for ($a = 0; $a < count($attributesNew[$attrName]); $a++) {
if (!in_array($attributesNew[$attrName][$a], $attributes[$attrName])) {
$return['mod'][$attrName] = $attributesNew[$attrName];
break;

View file

@ -311,7 +311,7 @@ class ldapPublicKey extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if ($this->hasObjectClass() && !in_array($this->getObjectClass(), $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = $this->getObjectClass();
@ -330,7 +330,7 @@ class ldapPublicKey extends baseModule {
$return = [];
if (!empty($this->attributes[$this->getAttributeName()])) {
$pdfTable = new PDFTable(_('SSH public keys'));
for ($i = 0; $i < sizeof($this->attributes[$this->getAttributeName()]); $i++) {
for ($i = 0; $i < count($this->attributes[$this->getAttributeName()]); $i++) {
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell($this->attributes[$this->getAttributeName()][$i]);
$pdfTable->rows[] = $pdfRow;
@ -385,8 +385,8 @@ class ldapPublicKey extends baseModule {
private function getSelfServiceKeys(): htmlResponsiveRow {
$keys = $_SESSION[self::SESS_KEY_LIST];
$content = new htmlResponsiveRow();
if (sizeof($keys) > 0) {
for ($i = 0; $i < sizeof($keys); $i++) {
if (count($keys) > 0) {
for ($i = 0; $i < count($keys); $i++) {
$group = new htmlGroup();
$keyInput = new htmlInputField('sshPublicKey_' . $i, $keys[$i]);
$keyInput->setFieldMaxLength(16384);
@ -395,10 +395,10 @@ class ldapPublicKey extends baseModule {
$delLink->setTitle(_('Delete'));
$delLink->setOnClick('ldapPublicKeyDeleteKey(' . $i . ');return false;');
$group->addElement($delLink);
if ($i == (sizeof($keys) - 1)) {
if ($i === (count($keys) - 1)) {
$addLink = new htmlLink('', '#', '../../graphics/add.svg');
$addLink->setTitle(_('Add'));
$addLink->setOnClick('ldapPublicKeyAddKey(' . sizeof($keys) . ');return false;');
$addLink->setOnClick('ldapPublicKeyAddKey(' . count($keys) . ');return false;');
$group->addElement($addLink);
}
$content->add($group, 12, 12, 12, 'nowrap');
@ -407,7 +407,7 @@ class ldapPublicKey extends baseModule {
else {
$addLink = new htmlLink('', '#', '../../graphics/add.svg');
$addLink->setTitle(_('Add'));
$addLink->setOnClick('ldapPublicKeyAddKey(' . sizeof($keys) . ');return false;');
$addLink->setOnClick('ldapPublicKeyAddKey(' . count($keys) . ');return false;');
$content->add($addLink);
}
// upload button
@ -426,7 +426,7 @@ class ldapPublicKey extends baseModule {
*
* @return htmlJavaScript JS block
*/
private static function getSelfServiceKeysJSBlock() {
private function getSelfServiceKeysJSBlock() {
$content = '
function ldapPublicKeyDeleteKey(id) {
var actionJSON = {
@ -558,9 +558,9 @@ class ldapPublicKey extends baseModule {
$newKeys[] = $_POST['sshPublicKey_' . $counter];
$counter++;
}
$count = sizeof($newKeys);
$count = count($newKeys);
for ($i = 0; $i < $count; $i++) {
if (trim($newKeys[$i]) == '') {
if (trim($newKeys[$i]) === '') {
unset($newKeys[$i]);
}
}
@ -570,11 +570,11 @@ class ldapPublicKey extends baseModule {
$oldKeys = $attributes[$this->getAttributeName()];
}
$update = false;
if (sizeof($newKeys) != sizeof($oldKeys)) {
if (count($newKeys) !== count($oldKeys)) {
$update = true;
}
else {
for ($i = 0; $i < sizeof($newKeys); $i++) {
for ($i = 0; $i < count($newKeys); $i++) {
if (!in_array($newKeys[$i], $oldKeys)) {
$update = true;
break;
@ -582,10 +582,10 @@ class ldapPublicKey extends baseModule {
}
}
if ($update) {
if (sizeof($oldKeys) == 0) {
if (count($oldKeys) == 0) {
$return['add'][$this->getAttributeName()] = $newKeys;
}
elseif (sizeof($newKeys) == 0) {
elseif (count($newKeys) == 0) {
$return['del'][$this->getAttributeName()] = $newKeys;
}
else {

View file

@ -169,14 +169,14 @@ class nisMailAlias extends baseModule {
$mailList = $this->getMailList();
$userList = $this->getUserList();
$autoList = [];
if ((sizeof($userList) + sizeof($mailList)) < 300) {
if ((count($userList) + count($mailList)) < 300) {
$autoList = array_merge($userList, $mailList);
}
$recipientCount = 0;
if (isset($this->attributes['rfc822MailMember'])) {
natcasesort($this->attributes['rfc822MailMember']);
$this->attributes['rfc822MailMember'] = array_values($this->attributes['rfc822MailMember']);
$recipientCount = sizeof($this->attributes['rfc822MailMember']);
$recipientCount = count($this->attributes['rfc822MailMember']);
if ($recipientCount < self::DISPLAY_LIMIT) {
for ($i = 0; $i < $recipientCount; $i++) {
if (($i == 0) && ($recipientCount == 1)) {
@ -189,7 +189,7 @@ class nisMailAlias extends baseModule {
$return->addLabel(new htmlOutputText('&nbsp;', false));
}
$mailField = new htmlInputField('rfc822MailMember' . $i, $this->attributes['rfc822MailMember'][$i]);
if (sizeof($autoList) > 0) {
if ($autoList !== []) {
$mailField->enableAutocompletion($autoList);
}
$mailField->setCSSClasses(['maxwidth20']);
@ -212,14 +212,14 @@ class nisMailAlias extends baseModule {
$return->addLabel(new htmlOutputText(_('New recipient')));
$newMailField = new htmlInputField('rfc822MailMember');
$newMailField->setOnKeyPress('SubmitForm(\'addRec\', event);');
if (sizeof($autoList) > 0) {
if ($autoList !== []) {
$newMailField->enableAutocompletion($autoList);
}
$newMailField->setCSSClasses(['maxwidth20']);
$newGroup = new htmlGroup();
$newGroup->addElement($newMailField);
$newGroup->addElement(new htmlAccountPageButton(static::class, 'selectMail', 'recipient' . 'New', 'mail.svg', true, _('Select mail')));
$newGroup->addElement(new htmlAccountPageButton(static::class, 'selectUser', 'recipient' . 'New', 'user.svg', true, _('Select user')));
$newGroup->addElement(new htmlAccountPageButton(static::class, 'selectMail', 'recipientNew', 'mail.svg', true, _('Select mail')));
$newGroup->addElement(new htmlAccountPageButton(static::class, 'selectUser', 'recipientNew', 'user.svg', true, _('Select user')));
$newGroup->addElement(new htmlButton('addRec', 'add.svg', true));
$newGroup->addElement(new htmlHelpLink('recipient'));
$newGroup->addElement(new htmlHiddenInput('rec_number', $recipientCount));
@ -237,7 +237,7 @@ class nisMailAlias extends baseModule {
function process_attributes() {
$errors = [];
$this->attributes['cn'] = [];
$recipientCount = !empty($this->attributes['rfc822MailMember']) ? sizeof($this->attributes['rfc822MailMember']) : 0;
$recipientCount = empty($this->attributes['rfc822MailMember']) ? 0 : count($this->attributes['rfc822MailMember']);
$this->attributes['rfc822MailMember'] = [];
// check alias name
$this->attributes['cn'][] = $_POST['cn'];
@ -357,14 +357,14 @@ class nisMailAlias extends baseModule {
$return = new htmlResponsiveRow();
$postKeys = array_keys($_POST);
$position = 'New';
for ($i = 0; $i < sizeof($postKeys); $i++) {
for ($i = 0; $i < count($postKeys); $i++) {
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;
}
}
// load list with all mail addresses
$count = sizeof($options);
$count = count($options);
for ($i = 0; $i < $count; $i++) {
if (!get_preg($options[$i], $regex)) {
unset($options[$i]);
@ -436,7 +436,7 @@ class nisMailAlias extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("nisMailAlias", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "nisMailAlias";
@ -448,7 +448,7 @@ class nisMailAlias extends baseModule {
if ($rawAccounts[$i][$ids['nisMailAlias_recipients']] != "") {
$aliases = explode(',', $rawAccounts[$i][$ids['nisMailAlias_recipients']]);
// check format
for ($a = 0; $a < sizeof($aliases); $a++) {
for ($a = 0; $a < count($aliases); $a++) {
if (get_preg($aliases[$a], 'nis_recipient') || get_preg($aliases[$a], 'email')) {
$partialAccounts[$i]['rfc822MailMember'][] = $aliases[$a];
}
@ -484,7 +484,7 @@ class nisMailAlias extends baseModule {
return $this->cachedMailList;
}
$this->cachedMailList = searchLDAPByAttribute('mail', '*', null, ['mail'], ['user']);
for ($i = 0; $i < sizeof($this->cachedMailList); $i++) {
for ($i = 0; $i < count($this->cachedMailList); $i++) {
$this->cachedMailList[$i] = $this->cachedMailList[$i]['mail'][0];
}
$this->cachedMailList = array_values(array_unique($this->cachedMailList));
@ -501,7 +501,7 @@ class nisMailAlias extends baseModule {
return $this->cachedUserList;
}
$this->cachedUserList = searchLDAPByFilter('(|(objectClass=posixAccount)(objectClass=inetOrgPerson))', ['uid'], ['user']);
$count = sizeof($this->cachedUserList);
$count = count($this->cachedUserList);
for ($i = 0; $i < $count; $i++) {
if (empty($this->cachedUserList[$i]['uid'][0])) {
unset($this->cachedUserList[$i]);

View file

@ -126,7 +126,7 @@ class nisMailAliasUser extends baseModule {
return $return;
}
$aliases = $this->getMailAliasList();
$count = sizeof($aliases);
$count = count($aliases);
$userName = $this->getUserName();
$mails = $this->getMailAddresses();
if (!$this->isBooleanConfigOptionSet('nisMailAliasUser_hideUserAliases') && ($userName != null)) {
@ -146,7 +146,7 @@ class nisMailAliasUser extends baseModule {
$remButton->setTitle(_('Remove user from alias entry.'));
$buttonGroup->addElement($remButton);
$delButton = new htmlButton('del_' . $i, 'delete.svg', true);
$delButton->setTitle(sprintf(_('Delete whole alias entry which includes %s recipients.'), sizeof($members)));
$delButton->setTitle(sprintf(_('Delete whole alias entry which includes %s recipients.'), count($members)));
$buttonGroup->addElement($delButton);
$return->addField($buttonGroup);
}
@ -157,8 +157,8 @@ class nisMailAliasUser extends baseModule {
}
if (!$this->isBooleanConfigOptionSet('nisMailAliasUser_hideMailAliases') && !empty($mails)) {
$return->add(new htmlSubTitle(_('Aliases for email')));
for ($m = 0; $m < sizeof($mails); $m++) {
if (sizeof($mails) > 1) {
for ($m = 0; $m < count($mails); $m++) {
if (count($mails) > 1) {
$label = new htmlOutputText($mails[$m]);
$return->add($label);
}
@ -177,7 +177,7 @@ class nisMailAliasUser extends baseModule {
$remButton->setTitle(_('Remove user from alias entry.'));
$buttonGroup->addElement($remButton);
$delButton = new htmlButton('delMail_' . $i . '_' . $m, 'delete.svg', true);
$delButton->setTitle(sprintf(_('Delete whole alias entry which includes %s recipients.'), sizeof($members)));
$delButton->setTitle(sprintf(_('Delete whole alias entry which includes %s recipients.'), count($members)));
$buttonGroup->addElement($delButton);
$return->addField($buttonGroup);
}
@ -185,7 +185,7 @@ class nisMailAliasUser extends baseModule {
$return->addVerticalSpacer('1rem');
$addButton = new htmlAccountPageButton(static::class, 'add', 'mail' . $m, _('Add'));
$return->add($addButton, 12, 12, 12, 'text-center');
if ((sizeof($mails) > 1) && ($m < (sizeof($mails) - 1))) {
if ((count($mails) > 1) && ($m < (count($mails) - 1))) {
$return->addVerticalSpacer('2rem');
}
}
@ -205,7 +205,7 @@ class nisMailAliasUser extends baseModule {
return $errors;
}
$mails = $this->getMailAddresses();
foreach ($_POST as $key => $value) {
foreach (array_keys($_POST) as $key) {
if (str_starts_with($key, 'rem_')) {
$index = substr($key, strlen('rem_'));
$dn = $this->cachedAliasList[$index]['dn'];
@ -237,10 +237,11 @@ class nisMailAliasUser extends baseModule {
* @param String $dn alias DN
*/
private function removeRecipient($recipient, $dn) {
if (!isset($this->aliasesToAdd[$dn])) { // no new entry update existing
if (!isset($this->aliasesToAdd[$dn])) {
// no new entry update existing
if (isset($this->recipientsToAdd[$dn]) && in_array($recipient, $this->recipientsToAdd[$dn])) {
// undo adding of recipient
if (sizeof($this->recipientsToAdd[$dn]) == 1) {
if (count($this->recipientsToAdd[$dn]) == 1) {
// only one entry as marked for adding, remove whole entry
unset($this->recipientsToAdd[$dn]);
}
@ -258,23 +259,22 @@ class nisMailAliasUser extends baseModule {
}
}
}
else { // new entry
if (sizeof($this->aliasesToAdd[$dn]['rfc822mailmember']) == 1) {
// single recipient in new entry, do not create new entry at all
unset($this->aliasesToAdd[$dn]);
foreach ($this->cachedAliasList as $index => $attrs) {
if ($dn == $attrs['dn']) {
unset($this->cachedAliasList[$index]);
$this->cachedAliasList = array_values($this->cachedAliasList);
}
elseif (count($this->aliasesToAdd[$dn]['rfc822mailmember']) == 1) {
// new entry
// single recipient in new entry, do not create new entry at all
unset($this->aliasesToAdd[$dn]);
foreach ($this->cachedAliasList as $index => $attrs) {
if ($dn == $attrs['dn']) {
unset($this->cachedAliasList[$index]);
$this->cachedAliasList = array_values($this->cachedAliasList);
}
}
else {
$this->aliasesToAdd[$dn]['rfc822mailmember'] = array_values(array_delete([$recipient], $this->aliasesToAdd[$dn]['rfc822mailmember']));
foreach ($this->cachedAliasList as &$attrs) {
if ($dn == $attrs['dn']) {
$attrs['rfc822mailmember'] = array_values(array_delete([$recipient], $attrs['rfc822mailmember']));
}
}
else {
$this->aliasesToAdd[$dn]['rfc822mailmember'] = array_values(array_delete([$recipient], $this->aliasesToAdd[$dn]['rfc822mailmember']));
foreach ($this->cachedAliasList as &$attrs) {
if ($dn == $attrs['dn']) {
$attrs['rfc822mailmember'] = array_values(array_delete([$recipient], $attrs['rfc822mailmember']));
}
}
}
@ -326,7 +326,7 @@ class nisMailAliasUser extends baseModule {
$recipient = $userName;
}
else {
for ($m = 0; $m < sizeof($mails); $m++) {
for ($m = 0; $m < count($mails); $m++) {
if (isset($_POST['form_subpage_' . static::class . '_add_mail' . $m])) {
$recipient = $mails[$m];
break;

View file

@ -48,7 +48,7 @@ class nisNetGroupHost extends nisNetGroupUser {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['host']);
return $this->get_scope() === 'host';
}
/**
@ -102,7 +102,7 @@ class nisNetGroupHost extends nisNetGroupUser {
$return->addElement(new htmlOutputText(_('Group')));
$return->addElement(new htmlOutputText(_('User name')));
$return->addElement(new htmlOutputText(_('Domain name')), true);
for ($i = 0; $i < sizeof($this->groups); $i++) {
for ($i = 0; $i < count($this->groups); $i++) {
$group = $this->groups[$i];
$return->addElement(new htmlOutputText($group['name']));
$return->addElement(new htmlInputField('user_' . $i, $group['user']));
@ -116,7 +116,7 @@ class nisNetGroupHost extends nisNetGroupUser {
// new entry
$groupList = [];
$groupData = $this->findGroups();
if (sizeof($groupData) > 0) {
if (count($groupData) > 0) {
$filterGroup = new htmlGroup();
$filterGroup->addElement(new htmlOutputText(_('Filter') . ' '));
$filter = new htmlInputField('group_filter');

View file

@ -186,7 +186,7 @@ class nisNetGroupUser extends baseModule {
$return->addElement(new htmlOutputText(_('Group')));
$return->addElement(new htmlOutputText(_('Host name')));
$return->addElement(new htmlOutputText(_('Domain name')), true);
for ($i = 0; $i < sizeof($this->groups); $i++) {
for ($i = 0; $i < count($this->groups); $i++) {
$group = $this->groups[$i];
$return->addElement(new htmlOutputText($group['name']));
$return->addElement(new htmlInputField('host_' . $i, $group['host']));
@ -200,7 +200,7 @@ class nisNetGroupUser extends baseModule {
// new entry
$groupList = [];
$groupData = $this->findGroups();
if (sizeof($groupData) > 0) {
if (count($groupData) > 0) {
$filterGroup = new htmlGroup();
$filterGroup->addElement(new htmlOutputText(_('Filter') . ' '));
$filter = new htmlInputField('group_filter');
@ -320,7 +320,7 @@ class nisNetGroupUser extends baseModule {
// calculate differences
$toRem = $this->groupsOrig;
$toAdd = $this->groups;
$counter = sizeof($toRem);
$counter = count($toRem);
for ($i = 0; $i < $counter; $i++) {
$group_orig = $toRem[$i];
foreach ($toAdd as $k => $group) {
@ -502,7 +502,7 @@ class nisNetGroupUser extends baseModule {
$groupNames[] = $group['cn'][0];
}
// check input
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// group names
if (!empty($rawAccounts[$i][$ids['nisNetGroup_memberships']])) {
$triples = preg_split('/,[ ]*/', $rawAccounts[$i][$ids['nisNetGroup_memberships']]);
@ -535,7 +535,7 @@ class nisNetGroupUser extends baseModule {
foreach ($groupList as $group) {
$groupMap[$group['cn'][0]] = $group['dn'];
}
for ($i = 0; $i < sizeof($data); $i++) {
for ($i = 0; $i < count($data); $i++) {
if (in_array($i, $failed)) {
continue;
} // ignore failed accounts
@ -560,7 +560,7 @@ class nisNetGroupUser extends baseModule {
];
}
// add users to groups
elseif ($temp['counter'] < sizeof($temp['groupDNs'])) {
elseif ($temp['counter'] < count($temp['groupDNs'])) {
$errors = [];
$dn = $temp['groupDNs'][$temp['counter']];
$current = ldapGetDN($dn, ['nisnetgrouptriple']);
@ -569,7 +569,7 @@ class nisNetGroupUser extends baseModule {
$temp['counter']++;
return [
'status' => 'inProgress',
'progress' => ($temp['counter'] * 100) / sizeof($temp['groupDNs']),
'progress' => ($temp['counter'] * 100) / count($temp['groupDNs']),
'errors' => $errors
];
}
@ -591,7 +591,7 @@ class nisNetGroupUser extends baseModule {
$temp['counter']++;
return [
'status' => 'inProgress',
'progress' => ($temp['counter'] * 100) / sizeof($temp['groupDNs']),
'progress' => ($temp['counter'] * 100) / count($temp['groupDNs']),
'errors' => $errors
];
}
@ -640,7 +640,7 @@ class nisNetGroupUser extends baseModule {
$filter = '(&' . $filter . $typeFilter . ')';
}
$results = searchLDAP($type->getSuffix(), $filter, ['cn', 'dn', 'nisnetgrouptriple']);
for ($i = 0; $i < sizeof($results); $i++) {
for ($i = 0; $i < count($results); $i++) {
if (isset($results[$i]['cn'][0]) && isset($results[$i]['dn'])) {
$return[] = $results[$i];
}

View file

@ -209,7 +209,7 @@ class nisnetgroup extends baseModule {
$subgroupsContainer = new htmlTable();
if (isset($this->attributes['memberNisNetgroup']) && is_array($this->attributes['memberNisNetgroup'])) {
$membergroups = $this->attributes['memberNisNetgroup'];
while (sizeof($membergroups) > 0) {
while ($membergroups !== []) {
$parts = array_splice($membergroups, 0, 8);
$subgroupsContainer->addElement(new htmlOutputText(implode(', ', $parts)), true);
}
@ -228,8 +228,8 @@ class nisnetgroup extends baseModule {
$return->add($membersLabel);
$titles = [_('Host'), _('User'), _('Domain'), ''];
$data = [];
if (isset($this->attributes['nisNetgroupTriple']) && (sizeof($this->attributes['nisNetgroupTriple']) > 0)) {
for ($i = 0; $i < sizeof($this->attributes['nisNetgroupTriple']); $i++) {
if (isset($this->attributes['nisNetgroupTriple']) && (count($this->attributes['nisNetgroupTriple']) > 0)) {
for ($i = 0; $i < count($this->attributes['nisNetgroupTriple']); $i++) {
$triple = substr($this->attributes['nisNetgroupTriple'][$i], 1, strlen($this->attributes['nisNetgroupTriple'][$i]) - 2);
$triple = explode(',', $triple);
if (isset($_POST['form_subpage_nisnetgroup_attributes_select']) && ($_POST['type'] == 'host') && ($_POST['position'] == strval($i))) {
@ -449,7 +449,7 @@ class nisnetgroup extends baseModule {
$selectHost = true;
$postKeys = array_keys($_POST);
$position = 'New';
for ($i = 0; $i < sizeof($postKeys); $i++) {
for ($i = 0; $i < count($postKeys); $i++) {
if (str_starts_with($postKeys[$i], 'form_subpage_nisnetgroup_select_user')) {
$selectHost = false;
$position = substr($postKeys[$i], 36);
@ -463,7 +463,7 @@ class nisnetgroup extends baseModule {
if ($selectHost) {
// load list with all hosts
$options = $this->getHostList();
$count = sizeof($options);
$count = count($options);
for ($i = 0; $i < $count; $i++) {
if (!get_preg($options[$i], 'DNSname')) {
unset($options[$i]);
@ -524,7 +524,7 @@ class nisnetgroup extends baseModule {
$messages = [];
// get list of existing groups
$existingGroups = $this->getGroupList();
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array('nisNetgroup', $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = 'nisNetgroup';
@ -537,7 +537,7 @@ class nisnetgroup extends baseModule {
if ($rawAccounts[$i][$ids['nisnetgroup_subgroups']] != "") {
$groups = explode(",", $rawAccounts[$i][$ids['nisnetgroup_subgroups']]);
$skipSubgroups = false;
for ($g = 0; $g < sizeof($groups); $g++) {
for ($g = 0; $g < count($groups); $g++) {
if (!in_array($groups[$g], $existingGroups)) {
$messages[] = ['ERROR', _('Unable to find group in LDAP.'), $groups[$g]];
$skipSubgroups = true;
@ -559,7 +559,7 @@ class nisnetgroup extends baseModule {
* @return boolean true, if settings are complete
*/
function module_complete() {
return (isset($this->attributes['cn']) && (sizeof($this->attributes['cn']) > 0));
return (isset($this->attributes['cn']) && (count($this->attributes['cn']) > 0));
}
/**
@ -571,14 +571,14 @@ class nisnetgroup extends baseModule {
$this->addSimplePDFField($return, 'cn', _('Group name'));
$this->addSimplePDFField($return, 'description', _('Description'));
$this->addSimplePDFField($return, 'subgroups', _('Subgroups'), 'memberNisNetgroup');
if (sizeof($this->attributes['nisNetgroupTriple']) > 0) {
if (count($this->attributes['nisNetgroupTriple']) > 0) {
$pdfTable = new PDFTable(_('Members'));
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell(_('Host'), '20%', null, true);
$pdfRow->cells[] = new PDFTableCell(_('User'), '20%', null, true);
$pdfRow->cells[] = new PDFTableCell(_('Domain'), '20%', null, true);
$pdfTable->rows[] = $pdfRow;
for ($i = 0; $i < sizeof($this->attributes['nisNetgroupTriple']); $i++) {
for ($i = 0; $i < count($this->attributes['nisNetgroupTriple']); $i++) {
$triple = substr($this->attributes['nisNetgroupTriple'][$i], 1, strlen($this->attributes['nisNetgroupTriple'][$i]) - 2);
$triple = explode(',', $triple);
$pdfRow = new PDFTableRow();
@ -602,7 +602,7 @@ class nisnetgroup extends baseModule {
return $this->cachedGroupList;
}
$this->cachedGroupList = searchLDAPByAttribute('cn', '*', 'nisNetgroup', ['cn'], ['netgroup']);
for ($i = 0; $i < sizeof($this->cachedGroupList); $i++) {
for ($i = 0; $i < count($this->cachedGroupList); $i++) {
$this->cachedGroupList[$i] = $this->cachedGroupList[$i]['cn'][0];
}
return $this->cachedGroupList;
@ -618,7 +618,7 @@ class nisnetgroup extends baseModule {
return $this->cachedUserList;
}
$this->cachedUserList = searchLDAPByAttribute('uid', '*', 'posixAccount', ['uid'], ['user']);
for ($i = 0; $i < sizeof($this->cachedUserList); $i++) {
for ($i = 0; $i < count($this->cachedUserList); $i++) {
$this->cachedUserList[$i] = $this->cachedUserList[$i]['uid'][0];
}
return $this->cachedUserList;

View file

@ -318,12 +318,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
];
}
// available PDF fields
if ($this->get_scope() == 'host') {
$return['PDF_fields'] = ['uid' => _('Host name')];
}
else {
$return['PDF_fields'] = ['uid' => _('User name')];
}
$return['PDF_fields'] = ($this->get_scope() === 'host') ? ['uid' => _('Host name')] : ['uid' => _('User name')];
$return['PDF_fields'] = array_merge($return['PDF_fields'], [
'uidNumber' => _('UID number'),
'gidNumber' => _('GID number'),
@ -563,10 +558,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
if (!isset($this->attributes['gidNumber'][0]) || ($this->attributes['gidNumber'][0] == '')) {
return false;
}
if (!isset($this->attributes['loginShell'][0]) || ($this->attributes['loginShell'][0] == '')) {
return false;
}
return true;
return isset($this->attributes['loginShell'][0]) && ($this->attributes['loginShell'][0] != '');
}
/**
@ -607,7 +599,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$groupFilter = '(&' . $groupFilter . $typeFilter . ')';
}
$groupList = searchLDAPByFilter($groupFilter, ['cn'], ['group']);
for ($i = 0; $i < sizeof($groupList); $i++) {
for ($i = 0; $i < count($groupList); $i++) {
$groups[] = $groupList[$i]['cn'][0];
}
return $groups;
@ -636,7 +628,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$gonListPart = searchLDAPByFilter($gonFilter, ['dn'], [$type]);
$gonList = array_merge($gonList, $gonListPart);
}
for ($i = 0; $i < sizeof($gonList); $i++) {
for ($i = 0; $i < count($gonList); $i++) {
$userGoNs[] = $gonList[$i]['dn'];
}
return array_values(array_unique($userGoNs));
@ -758,7 +750,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
if (isset($this->orig['uid'][0]) && ($this->orig['uid'][0] != '') && ($this->attributes['uid'][0] != $this->orig['uid'][0])) {
// find affected groups
$groupList = searchLDAPByAttribute('memberUid', $this->orig['uid'][0], 'posixGroup', ['dn'], ['group']);
for ($i = 0; $i < sizeof($groupList); $i++) {
for ($i = 0; $i < count($groupList); $i++) {
// replace old user name with new one
$return[$groupList[$i]['dn']]['remove']['memberUid'][] = $this->orig['uid'][0];
$return[$groupList[$i]['dn']]['add']['memberUid'][] = $this->attributes['uid'][0];
@ -770,15 +762,15 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$remove = array_delete($this->groups, $this->groups_orig);
$groupList = searchLDAPByAttribute('cn', '*', 'posixGroup', ['cn', 'dn'], ['group']);
$cn2dn = [];
for ($i = 0; $i < sizeof($groupList); $i++) {
for ($i = 0; $i < count($groupList); $i++) {
$cn2dn[$groupList[$i]['cn'][0]] = $groupList[$i]['dn'];
}
for ($i = 0; $i < sizeof($add); $i++) {
for ($i = 0; $i < count($add); $i++) {
if (isset($cn2dn[$add[$i]])) {
$return[$cn2dn[$add[$i]]]['add']['memberUid'][] = $this->attributes['uid'][0];
}
}
for ($i = 0; $i < sizeof($remove); $i++) {
for ($i = 0; $i < count($remove); $i++) {
if (isset($cn2dn[$remove[$i]])) {
$return[$cn2dn[$remove[$i]]]['remove']['memberUid'][] = $this->attributes['uid'][0];
}
@ -788,7 +780,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
elseif (in_array('posixAccount', $this->orig['objectClass']) && !empty($this->orig['uid'][0])) {
// Unix extension was removed, clean group memberships
$groupList = searchLDAPByAttribute('memberUid', $this->orig['uid'][0], 'posixGroup', ['dn'], ['group']);
for ($i = 0; $i < sizeof($groupList); $i++) {
for ($i = 0; $i < count($groupList); $i++) {
// remove user name
$return[$groupList[$i]['dn']]['remove']['memberUid'][] = $this->orig['uid'][0];
}
@ -817,7 +809,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// create home directories if needed
$homeDirAttr = $this->getHomedirAttrName($modules);
$lamdaemonServerList = $_SESSION['config']->getConfiguredScriptServers();
if (sizeof($this->lamdaemonServers) > 0) {
if (count($this->lamdaemonServers) > 0) {
foreach ($lamdaemonServerList as $lamdaemonServer) {
if (!in_array($lamdaemonServer->getServer(), $this->lamdaemonServers)) {
continue;
@ -837,7 +829,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// lamdaemon results
if (!empty($result)) {
$singleresult = explode(",", $result);
if (($singleresult[0] == 'ERROR') || ($singleresult[0] == 'INFO') || ($singleresult[0] == 'WARN')) {
if (($singleresult[0] === 'ERROR') || ($singleresult[0] === 'INFO') || ($singleresult[0] === 'WARN')) {
$messages[] = $singleresult;
}
else {
@ -873,7 +865,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// lamdaemon results
if (!empty($result)) {
$singleresult = explode(",", $result);
if (($singleresult[0] == 'ERROR') || ($singleresult[0] == 'INFO') || ($singleresult[0] == 'WARN')) {
if (($singleresult[0] === 'ERROR') || ($singleresult[0] === 'INFO') || ($singleresult[0] === 'WARN')) {
$messages[] = $singleresult;
}
}
@ -906,7 +898,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// lamdaemon results
if (!empty($result)) {
$singleresult = explode(",", $result);
if (($singleresult[0] == 'ERROR') || ($singleresult[0] == 'INFO') || ($singleresult[0] == 'WARN')) {
if (($singleresult[0] === 'ERROR') || ($singleresult[0] === 'INFO') || ($singleresult[0] === 'WARN')) {
$messages[] = $singleresult;
}
}
@ -918,15 +910,15 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$toAdd = array_values(array_diff($this->gonList, $this->gonList_orig));
$toRem = array_values(array_diff($this->gonList_orig, $this->gonList));
// update groups if DN changed
if (isset($accountContainer->dn_orig) && (strtolower($accountContainer->dn_orig) != strtolower($accountContainer->finalDN))) {
if (isset($accountContainer->dn_orig) && (strtolower($accountContainer->dn_orig) !== strtolower($accountContainer->finalDN))) {
// update owner/member/uniqueMember attributes
$searchAttrs = ['member', 'uniquemember', 'owner'];
foreach ($searchAttrs as $searchAttr) {
$ownerGroups = searchLDAPByAttribute($searchAttr, $accountContainer->dn_orig, null, ['dn', $searchAttr], ['gon', 'group']);
for ($i = 0; $i < sizeof($ownerGroups); $i++) {
for ($i = 0; $i < count($ownerGroups); $i++) {
$found = false;
$newOwners = $ownerGroups[$i][$searchAttr];
for ($o = 0; $o < sizeof($newOwners); $o++) {
for ($o = 0; $o < count($newOwners); $o++) {
if ($newOwners[$o] == $accountContainer->dn_orig) {
$newOwners[$o] = $accountContainer->finalDN;
$found = true;
@ -947,7 +939,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
}
}
// add groups
for ($i = 0; $i < sizeof($toAdd); $i++) {
for ($i = 0; $i < count($toAdd); $i++) {
if (isset($gons[$toAdd[$i]])) {
$attrName = 'member';
if (in_array_ignore_case('groupOfUniqueNames', $gons[$toAdd[$i]]['objectclass'])) {
@ -964,7 +956,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
}
}
// remove groups
for ($i = 0; $i < sizeof($toRem); $i++) {
for ($i = 0; $i < count($toRem); $i++) {
if (isset($gons[$toRem[$i]])) {
$attrName = 'member';
if (in_array_ignore_case('groupOfUniqueNames', $gons[$toRem[$i]]['objectclass'])) {
@ -998,7 +990,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
*/
public static function createHomeDirectory(Remote $remote, RemoteServerConfiguration $config, string $userName,
string $path, string $uidNumber, string $gidNumber, string $rights) {
if ($rights == '') {
if ($rights === '') {
$rights = '750';
}
if (!str_starts_with($rights, '0')) {
@ -1043,7 +1035,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$return = [];
// remove memberUids if set
$groups = searchLDAPByAttribute('memberUid', $this->attributes['uid'][0], 'posixGroup', ['dn'], ['group']);
for ($i = 0; $i < sizeof($groups); $i++) {
for ($i = 0; $i < count($groups); $i++) {
$return[$groups[$i]['dn']]['remove']['memberUid'][] = $this->attributes['uid'][0];
}
// stop here if referential integrity overlay is active
@ -1055,7 +1047,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$dn = $this->getAccountContainer()->dn_orig;
$filter = '(&(|(member=' . $dn . ')(uniquemember=' . $dn . '))(|(objectClass=groupOfNames)(objectClass=groupOfUniqueNames)(objectClass=groupOfMembers)))';
$gons = searchLDAPByFilter($filter, ['member', 'uniquemember'], ['group', 'gon']);
for ($i = 0; $i < sizeof($gons); $i++) {
for ($i = 0; $i < count($gons); $i++) {
if (isset($gons[$i]['member'])) {
$return[$gons[$i]['dn']]['remove']['member'][] = $dn;
}
@ -1103,7 +1095,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// lamdaemon results
if (!empty($result)) {
$singleresult = explode(",", $result);
if (($singleresult[0] == 'ERROR') || ($singleresult[0] == 'WARN') || ($singleresult[0] == 'INFO')) {
if (($singleresult[0] === 'ERROR') || ($singleresult[0] === 'WARN') || ($singleresult[0] === 'INFO')) {
$return[] = $singleresult;
}
}
@ -1165,10 +1157,8 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
if (isset($_POST['loginShell'])) {
$this->attributes['loginShell'][0] = $_POST['loginShell'];
}
if (!$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegecos')) {
if (isset($_POST['gecos'])) {
$this->attributes['gecos'][0] = $_POST['gecos'];
}
if (!$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegecos') && isset($_POST['gecos'])) {
$this->attributes['gecos'][0] = $_POST['gecos'];
}
if (isset($this->orig['uid'][0]) && ($this->orig['uid'][0] != '') && (trim($_POST['uid']) != $this->attributes['uid'][0])) {
$errors[] = $this->messages['uid'][0];
@ -1216,7 +1206,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// get list of DNS names or IPs
$lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
$this->lamdaemonServers = [];
for ($h = 0; $h < sizeof($lamdaemonServers); $h++) {
for ($h = 0; $h < count($lamdaemonServers); $h++) {
if (isset($_POST['createhomedir_' . $h]) && ($_POST['createhomedir_' . $h] = 'on')) {
$this->lamdaemonServers[] = $lamdaemonServers[$h]->getServer();
}
@ -1261,7 +1251,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$maxID = intval($this->moduleSettings['posixAccount_' . $typeId . '_maxMachine'][0]);
}
$uids = $this->getUIDs($typeId);
if ($this->attributes['uidNumber'][0] == '') {
if ($this->attributes['uidNumber'][0] === '') {
// No id-number given
if (!isset($this->orig['uidNumber'][0]) || ($this->orig['uidNumber'][0] == '')) {
// new account -> we have to find a free id-number
@ -1278,29 +1268,29 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
}
// old account -> return id-number which has been used
}
else {
elseif ($this->getAccountContainer()->isNewAccount || !isset($this->orig['uidNumber'][0]) || ($this->orig['uidNumber'][0] != $this->attributes['uidNumber'][0])) {
// check manual ID
if ($this->getAccountContainer()->isNewAccount || !isset($this->orig['uidNumber'][0]) || ($this->orig['uidNumber'][0] != $this->attributes['uidNumber'][0])) {
// check range
if (($this->get_scope() == 'user') && (!isset($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers']) || ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers'][0] == 'range'))) {
if (!is_numeric($this->attributes['uidNumber'][0]) || ($this->attributes['uidNumber'][0] < $minID) || ($this->attributes['uidNumber'][0] > $maxID)) {
$errors[] = ['ERROR', _('ID-Number'), sprintf(_('Please enter a value between %s and %s!'), $minID, $maxID)];
}
}
if (($this->get_scope() == 'host') && (!isset($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts']) || ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts'][0] == 'range'))) {
if (!is_numeric($this->attributes['uidNumber'][0]) || ($this->attributes['uidNumber'][0] < $minID) || ($this->attributes['uidNumber'][0] > $maxID)) {
$errors[] = ['ERROR', _('ID-Number'), sprintf(_('Please enter a value between %s and %s!'), $minID, $maxID)];
}
}
// id-number is in use and account is a new account
if ((in_array($this->attributes['uidNumber'][0], $uids)) && !isset($this->orig['uidNumber'][0])) {
$errors[] = $this->messages['uidNumber'][3];
}
// id-number is in use, account is existing account and id-number is not used by itself
if ((in_array($this->attributes['uidNumber'][0], $uids)) && isset($this->orig['uidNumber'][0]) && ($this->orig['uidNumber'][0] != $this->attributes['uidNumber'][0])) {
$errors[] = $this->messages['uidNumber'][3];
$this->attributes['uidNumber'][0] = $this->orig['uidNumber'][0];
}
// check range
if (($this->get_scope() === 'user')
&& (!isset($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers']) || ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers'][0] === 'range'))
&& (!is_numeric($this->attributes['uidNumber'][0]) || ($this->attributes['uidNumber'][0] < $minID) || ($this->attributes['uidNumber'][0] > $maxID))) {
$errors[] = ['ERROR', _('ID-Number'), sprintf(_('Please enter a value between %s and %s!'), $minID, $maxID)];
}
if (($this->get_scope() === 'host')
&& (!isset($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts']) || ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts'][0] == 'range'))
&& (!is_numeric($this->attributes['uidNumber'][0]) || ($this->attributes['uidNumber'][0] < $minID) || ($this->attributes['uidNumber'][0] > $maxID))) {
$errors[] = ['ERROR', _('ID-Number'), sprintf(_('Please enter a value between %s and %s!'), $minID, $maxID)];
}
// id-number is in use and account is a new account
if ((in_array($this->attributes['uidNumber'][0], $uids)) && !isset($this->orig['uidNumber'][0])) {
$errors[] = $this->messages['uidNumber'][3];
}
// id-number is in use, account is existing account and id-number is not used by itself
if ((in_array($this->attributes['uidNumber'][0], $uids))
&& isset($this->orig['uidNumber'][0])
&& ($this->orig['uidNumber'][0] != $this->attributes['uidNumber'][0])) {
$errors[] = $this->messages['uidNumber'][3];
$this->attributes['uidNumber'][0] = $this->orig['uidNumber'][0];
}
}
// Create automatic useraccount with number if original user already exists
@ -1349,7 +1339,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
if (!$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegecos')) {
$attributeList[] = 'gecos';
}
for ($i = 0; $i < sizeof($attributeList); $i++) {
for ($i = 0; $i < count($attributeList); $i++) {
if (isset($this->attributes[$attributeList[$i]][0])) {
$value = $this->attributes[$attributeList[$i]][0];
$replacedValue = $this->checkASCII($value);
@ -1648,7 +1638,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
$modules = $this->getAccountContainer()->get_type()->getModules();
$homeDirAttr = $this->getHomedirAttrName($modules);
for ($i = 0; $i < sizeof($lamdaemonServers); $i++) {
for ($i = 0; $i < count($lamdaemonServers); $i++) {
if (isset($_POST['form_subpage_' . static::class . '_homedir_create_' . $i])) {
$remote = new Remote();
try {
@ -1665,7 +1655,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// lamdaemon results
if (!empty($result)) {
$singleresult = explode(",", $result);
if (($singleresult[0] == 'ERROR') || ($singleresult[0] == 'WARN') || ($singleresult[0] == 'INFO')) {
if (($singleresult[0] === 'ERROR') || ($singleresult[0] === 'WARN') || ($singleresult[0] === 'INFO')) {
$return[] = $singleresult;
}
}
@ -1694,7 +1684,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// lamdaemon results
if (!empty($result)) {
$singleresult = explode(",", $result);
if (($singleresult[0] == 'ERROR') || ($singleresult[0] == 'WARN') || ($singleresult[0] == 'INFO')) {
if (($singleresult[0] === 'ERROR') || ($singleresult[0] === 'WARN') || ($singleresult[0] === 'INFO')) {
$return[] = $singleresult;
}
}
@ -1728,7 +1718,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
&& !$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hideCreateGroup');
$groupList = $this->findGroups($modules); // list of all group names
$groups = [];
for ($i = 0; $i < sizeof($groupList); $i++) {
for ($i = 0; $i < count($groupList); $i++) {
$groups[$groupList[$i][1]] = $groupList[$i][0];
}
$groups = natCaseKeySort($groups);
@ -1855,7 +1845,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$homeDirLabel = new htmlOutputText(_('Create home directory'));
$return->addLabel($homeDirLabel);
$homeServerContainer = new htmlResponsiveRow();
for ($h = 0; $h < sizeof($lamdaemonServers); $h++) {
for ($h = 0; $h < count($lamdaemonServers); $h++) {
$createHomedirGroup = new htmlGroup();
$createHomedirGroup->addElement(new htmlInputCheckbox('createhomedir_' . $h, in_array($lamdaemonServers[$h]->getServer(), $this->lamdaemonServers)));
$createHomedirGroup->addElement(new htmlOutputText($lamdaemonServers[$h]->getLabel()));
@ -1960,7 +1950,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
if ($showUnix) {
// load list with all groups
$groups = $this->findGroups($modules);
for ($i = 0; $i < sizeof($groups); $i++) {
for ($i = 0; $i < count($groups); $i++) {
$groups[$i] = $groups[$i][1];
}
// remove groups the user is member of from grouplist
@ -2005,7 +1995,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$gonContainer->add(new htmlSubTitle(_("Groups of names")));
$selectedGons = [];
for ($i = 0; $i < sizeof($this->gonList); $i++) {
for ($i = 0; $i < count($this->gonList); $i++) {
if (isset($gons[$this->gonList[$i]])) {
$selectedGons[getAbstractDN($this->gonList[$i])] = $this->gonList[$i];
}
@ -2074,7 +2064,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$return->addVerticalSpacer('2rem');
// get list of lamdaemon servers
$lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
for ($i = 0; $i < sizeof($lamdaemonServers); $i++) {
for ($i = 0; $i < count($lamdaemonServers); $i++) {
$label = $lamdaemonServers[$i]->getLabel();
$remote = new Remote();
try {
@ -2097,7 +2087,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// lamdaemon results
if (!empty($result)) {
$returnValue = trim($result);
if ($returnValue == 'ok') {
if ($returnValue === 'ok') {
$return->addLabel(new htmlOutputText($label));
$okGroup = new htmlGroup();
$okGroup->addElement(new htmlImage('../../graphics/pass.svg', 16, 16));
@ -2105,7 +2095,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$okGroup->addElement(new htmlAccountPageButton(static::class, 'homedir', 'delete_' . $i, _('Delete')));
$return->addField($okGroup);
}
elseif ($returnValue == 'missing') {
elseif ($returnValue === 'missing') {
$return->addLabel(new htmlOutputText($label));
$failGroup = new htmlGroup();
$failGroup->addElement(new htmlImage('../../graphics/del.svg', 16, 16));
@ -2113,12 +2103,12 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$failGroup->addElement(new htmlAccountPageButton(static::class, 'homedir', 'create_' . $i, _('Create')));
$return->addField($failGroup);
}
elseif (trim($returnValue) != '') {
elseif (trim($returnValue) !== '') {
$messageParams = explode(",", $returnValue);
if (isset($messageParams[2])) {
$message = new htmlStatusMessage($messageParams[0], htmlspecialchars($messageParams[1]), htmlspecialchars($messageParams[2]));
}
elseif (($messageParams[0] == 'ERROR') || ($messageParams[0] == 'WARN') || ($messageParams[0] == 'INFO')) {
elseif (($messageParams[0] === 'ERROR') || ($messageParams[0] === 'WARN') || ($messageParams[0] === 'INFO')) {
$message = new htmlStatusMessage($messageParams[0], htmlspecialchars($messageParams[1]));
}
else {
@ -2142,7 +2132,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$modules = $typeManager->getConfiguredType($typeId)->getModules();
$groupList = $this->findGroups($modules);
$groups = [];
for ($i = 0; $i < sizeof($groupList); $i++) {
for ($i = 0; $i < count($groupList); $i++) {
$groups[$groupList[$i][1]] = $groupList[$i][1];
}
$groups = natCaseKeySort($groups);
@ -2192,7 +2182,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
if ($_SESSION['config']->get_scriptPath() != null) {
$return->add(new htmlSubTitle(_('Create home directory')));
$lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
for ($h = 0; $h < sizeof($lamdaemonServers); $h++) {
for ($h = 0; $h < count($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));
@ -2259,17 +2249,18 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
if (($this->get_scope() == 'user') && $this->getAccountContainer()->isNewAccount) {
$lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
$this->lamdaemonServers = [];
for ($h = 0; $h < sizeof($lamdaemonServers); $h++) {
for ($h = 0; $h < count($lamdaemonServers); $h++) {
if (isset($profile['posixAccount_createHomedir_' . $h][0]) && ($profile['posixAccount_createHomedir_' . $h][0] == 'true')) {
$this->lamdaemonServers[] = $lamdaemonServers[$h]->getServer();
}
}
}
// add extension
if (isset($profile['posixAccount_addExt'][0]) && ($profile['posixAccount_addExt'][0] == "true")) {
if (!$this->skipObjectClass() && !in_array('posixAccount', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'posixAccount';
}
if (isset($profile['posixAccount_addExt'][0])
&& ($profile['posixAccount_addExt'][0] == "true")
&& !$this->skipObjectClass()
&& !in_array('posixAccount', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'posixAccount';
}
}
@ -2320,20 +2311,20 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$this->addSimplePDFField($return, 'gecos', _('Gecos'));
if (self::areGroupOfNamesActive()) {
$gons = [];
for ($i = 0; $i < sizeof($this->gonList); $i++) {
for ($i = 0; $i < count($this->gonList); $i++) {
$gons[] = $this->gonList[$i];
}
usort($gons, 'compareDN');
$gonCount = sizeof($gons);
$gonCount = count($gons);
for ($i = 0; $i < $gonCount; $i++) {
$gons[$i] = getAbstractDN($gons[$i]);
}
$this->addPDFKeyValue($return, 'gon', _('Groups of names'), $gons, "\n");
}
if (isset($this->clearTextPassword)) {
if ($this->clearTextPassword !== null) {
$this->addPDFKeyValue($return, 'userPassword', _('Password'), $this->clearTextPassword);
}
else if (isset($this->attributes['INFO.userPasswordClearText'])) {
elseif (isset($this->attributes['INFO.userPasswordClearText'])) {
$this->addPDFKeyValue($return, 'userPassword', _('Password'), $this->attributes['INFO.userPasswordClearText']);
}
return $return;
@ -2368,10 +2359,10 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$configUserContainer = new htmlResponsiveRow();
$configUserContainer->add(new htmlSubTitle(_("Users")));
foreach ($allScopes[static::class] as $typeId) {
if (!(getScopeFromTypeId($typeId) === 'user')) {
if (getScopeFromTypeId($typeId) !== 'user') {
continue;
}
if (sizeof($allScopes[static::class]) > 1) {
if (count($allScopes[static::class]) > 1) {
$title = new htmlDiv(null, new htmlOutputText($typeManager->getConfiguredType($typeId)->getAlias()));
$title->setCSSClasses(['bold', 'responsiveLabel']);
$configUserContainer->add($title, 12, 6);
@ -2439,10 +2430,10 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$configHostContainer = new htmlResponsiveRow();
$configHostContainer->add(new htmlSubTitle(_("Hosts")));
foreach ($allScopes[static::class] as $typeId) {
if (!(getScopeFromTypeId($typeId) === 'host')) {
if (getScopeFromTypeId($typeId) !== 'host') {
continue;
}
if (sizeof($allScopes[static::class]) > 1) {
if (count($allScopes[static::class]) > 1) {
$title = new htmlDiv(null, new htmlOutputText($typeManager->getConfiguredType($typeId)->getAlias()));
$title->setCSSClasses(['bold', 'responsiveLabel']);
$configHostContainer->add($title, 12, 6);
@ -2521,17 +2512,17 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
if (getScopeFromTypeId($typeId) === 'user') {
if ($options['posixAccount_' . $typeId . '_uidGeneratorUsers'][0] == 'range') {
// min/maxUID are required, check if they are numeric
if (!isset($options['posixAccount_' . $typeId . '_minUID'][0]) || !preg_match('/^[0-9]+$/', $options['posixAccount_' . $typeId . '_minUID'][0])) {
if (!isset($options['posixAccount_' . $typeId . '_minUID'][0]) || !preg_match('/^\d+$/', $options['posixAccount_' . $typeId . '_minUID'][0])) {
$return[] = $this->messages['minUID'][0];
}
if (!isset($options['posixAccount_' . $typeId . '_maxUID'][0]) || !preg_match('/^[0-9]+$/', $options['posixAccount_' . $typeId . '_maxUID'][0])) {
if (!isset($options['posixAccount_' . $typeId . '_maxUID'][0]) || !preg_match('/^\d+$/', $options['posixAccount_' . $typeId . '_maxUID'][0])) {
$return[] = $this->messages['maxUID'][0];
}
// minUID < maxUID
if (isset($options['posixAccount_' . $typeId . '_minUID'][0]) && isset($options['posixAccount_' . $typeId . '_maxUID'][0])) {
if ($options['posixAccount_' . $typeId . '_minUID'][0] >= $options['posixAccount_' . $typeId . '_maxUID'][0]) {
$return[] = $this->messages['cmp_UID'][0];
}
if (isset($options['posixAccount_' . $typeId . '_minUID'][0])
&& isset($options['posixAccount_' . $typeId . '_maxUID'][0])
&& ($options['posixAccount_' . $typeId . '_minUID'][0] >= $options['posixAccount_' . $typeId . '_maxUID'][0])) {
$return[] = $this->messages['cmp_UID'][0];
}
$ranges[] = [$options['posixAccount_' . $typeId . '_minUID'][0], $options['posixAccount_' . $typeId . '_maxUID'][0]];
}
@ -2550,17 +2541,17 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
if (getScopeFromTypeId($typeId) === 'host') {
if ($options['posixAccount_' . $typeId . '_uidGeneratorHosts'][0] == 'range') {
// min/maxUID are required, check if they are numeric
if (!isset($options['posixAccount_' . $typeId . '_minMachine'][0]) || !preg_match('/^[0-9]+$/', $options['posixAccount_' . $typeId . '_minMachine'][0])) {
if (!isset($options['posixAccount_' . $typeId . '_minMachine'][0]) || !preg_match('/^\d+$/', $options['posixAccount_' . $typeId . '_minMachine'][0])) {
$return[] = $this->messages['minMachine'][0];
}
if (!isset($options['posixAccount_' . $typeId . '_maxMachine'][0]) || !preg_match('/^[0-9]+$/', $options['posixAccount_' . $typeId . '_maxMachine'][0])) {
if (!isset($options['posixAccount_' . $typeId . '_maxMachine'][0]) || !preg_match('/^\d+$/', $options['posixAccount_' . $typeId . '_maxMachine'][0])) {
$return[] = $this->messages['maxMachine'][0];
}
// minUID < maxUID
if (isset($options['posixAccount_' . $typeId . '_minMachine'][0]) && isset($options['posixAccount_' . $typeId . '_maxMachine'][0])) {
if ($options['posixAccount_' . $typeId . '_minMachine'][0] >= $options['posixAccount_' . $typeId . '_maxMachine'][0]) {
$return[] = $this->messages['cmp_Machine'][0];
}
if (isset($options['posixAccount_' . $typeId . '_minMachine'][0])
&& isset($options['posixAccount_' . $typeId . '_maxMachine'][0])
&& ($options['posixAccount_' . $typeId . '_minMachine'][0] >= $options['posixAccount_' . $typeId . '_maxMachine'][0])) {
$return[] = $this->messages['cmp_Machine'][0];
}
$ranges[] = [$options['posixAccount_' . $typeId . '_minMachine'][0], $options['posixAccount_' . $typeId . '_maxMachine'][0]];
}
@ -2659,7 +2650,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// get list of existing groups
$groupList = $this->findGroups($selectedModules);
$groupMap = [];
for ($i = 0; $i < sizeof($groupList); $i++) {
for ($i = 0; $i < count($groupList); $i++) {
$groupMap[$groupList[$i][1]] = $groupList[$i][0];
}
$existingGroups = array_keys($groupMap);
@ -2768,7 +2759,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// additional groups
if ($rawAccount[$ids['posixAccount_additionalGroups']] != "") {
$groups = explode(",", $rawAccount[$ids['posixAccount_additionalGroups']]);
for ($g = 0; $g < sizeof($groups); $g++) {
for ($g = 0; $g < count($groups); $g++) {
if (!in_array($groups[$g], $existingGroups)) {
$errors[] = ['ERROR', _('Unable to find group in LDAP.'), $groups[$g]];
}
@ -2777,7 +2768,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// group of names
if (self::areGroupOfNamesActive() && isset($ids['posixAccount_gon']) && ($rawAccount[$ids['posixAccount_gon']] != "")) {
$groups = explode(",", $rawAccount[$ids['posixAccount_gon']]);
for ($g = 0; $g < sizeof($groups); $g++) {
for ($g = 0; $g < count($groups); $g++) {
if (!in_array($groups[$g], $gonList)) {
$errors[] = ['ERROR', _('Unable to find group in LDAP.'), $groups[$g]];
}
@ -2870,18 +2861,16 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
elseif (!empty($this->moduleSettings['posixAccount_pwdHash'][0]) && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'K5KEY')) {
$partialAccounts[$i][$pwdAttrName] = pwd_hash('x', true, $this->moduleSettings['posixAccount_pwdHash'][0]);
}
// set normal password
else {
if (($rawAccount[$ids['posixAccount_password']] != "") && (get_preg($rawAccount[$ids['posixAccount_password']], 'password'))) {
$partialAccounts[$i][$pwdAttrName] = pwd_hash($rawAccount[$ids['posixAccount_password']], $pwd_enabled, $this->moduleSettings['posixAccount_pwdHash'][0]);
$partialAccounts[$i]['INFO.userPasswordClearText'] = $rawAccount[$ids['posixAccount_password']]; // for custom scripts etc.
}
elseif ($rawAccount[$ids['posixAccount_password']] != "") {
$errMsg = $this->messages['userPassword'][4];
$errMsg[2] = str_replace('%', '%%', $errMsg[2]); // double "%" because of later sprintf
$errMsg[] = [$i];
$errors[] = $errMsg;
}
elseif (($rawAccount[$ids['posixAccount_password']] != "") && (get_preg($rawAccount[$ids['posixAccount_password']], 'password'))) {
$partialAccounts[$i][$pwdAttrName] = pwd_hash($rawAccount[$ids['posixAccount_password']], $pwd_enabled, $this->moduleSettings['posixAccount_pwdHash'][0]);
$partialAccounts[$i]['INFO.userPasswordClearText'] = $rawAccount[$ids['posixAccount_password']];
// for custom scripts etc.
}
elseif ($rawAccount[$ids['posixAccount_password']] != "") {
$errMsg = $this->messages['userPassword'][4];
$errMsg[2] = str_replace('%', '%%', $errMsg[2]); // double "%" because of later sprintf
$errMsg[] = [$i];
$errors[] = $errMsg;
}
}
// cn
@ -2896,16 +2885,14 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$errors[] = $errMsg;
}
}
elseif ($partialAccounts[$i]['givenName']) {
$partialAccounts[$i]['cn'] = $partialAccounts[$i]['givenName'] . " " . $partialAccounts[$i]['sn'];
}
elseif ($partialAccounts[$i]['sn']) {
$partialAccounts[$i]['cn'] = $partialAccounts[$i]['sn'];
}
else {
if ($partialAccounts[$i]['givenName']) {
$partialAccounts[$i]['cn'] = $partialAccounts[$i]['givenName'] . " " . $partialAccounts[$i]['sn'];
}
elseif ($partialAccounts[$i]['sn']) {
$partialAccounts[$i]['cn'] = $partialAccounts[$i]['sn'];
}
else {
$partialAccounts[$i]['cn'] = $partialAccounts[$i]['uid'];
}
$partialAccounts[$i]['cn'] = $partialAccounts[$i]['uid'];
}
}
}
@ -2943,9 +2930,9 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
}
}
// fill in autoUIDs
if (sizeof($needAutoUID) > 0) {
if ($needAutoUID !== []) {
$errorsTemp = [];
$uids = $this->getNextUIDs(sizeof($needAutoUID), $errorsTemp, $typeId);
$uids = $this->getNextUIDs(count($needAutoUID), $errorsTemp, $typeId);
if (is_array($uids)) {
foreach ($needAutoUID as $i => $index) {
$partialAccounts[$index]['uidNumber'] = $uids[$i];
@ -2985,7 +2972,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// get list of existing groups
$groupList = $this->findGroups($selectedModules);
$groupMap = [];
for ($i = 0; $i < sizeof($groupList); $i++) {
for ($i = 0; $i < count($groupList); $i++) {
$groupMap[$groupList[$i][0]] = $groupList[$i][1];
}
// get list of existing group of names
@ -3011,13 +2998,11 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$groups[] = $groupMap[$dataRow[$ids['posixAccount_group']]];
}
}
else {
if (!in_array($groupMap[$dataRow[$ids['posixAccount_group']]], $groups)) {
$groups[] = $dataRow[$ids['posixAccount_group']];
}
elseif (!in_array($groupMap[$dataRow[$ids['posixAccount_group']]], $groups)) {
$groups[] = $dataRow[$ids['posixAccount_group']];
}
}
for ($g = 0; $g < sizeof($groups); $g++) {
for ($g = 0; $g < count($groups); $g++) {
if (!in_array($groups[$g], $temp['groups'])) {
$temp['groups'][] = $groups[$g];
}
@ -3026,7 +3011,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
if (isset($ids['posixAccount_gon']) && ($dataRow[$ids['posixAccount_gon']] != "")) {
$gons = explode(",", $dataRow[$ids['posixAccount_gon']]);
$memberAttr = 'member';
for ($g = 0; $g < sizeof($gons); $g++) {
for ($g = 0; $g < count($gons); $g++) {
if (in_array_ignore_case('groupOfUniqueNames', $gonList[$gonMap[$gons[$g]]]['objectclass'])) {
$memberAttr = 'uniquemember';
}
@ -3036,10 +3021,11 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
if (isset($ids['posixAccount_createHomeDir']) && !empty($dataRow[$ids['posixAccount_createHomeDir']])) {
$temp['createHomes'][] = $i;
}
if (!empty($this->moduleSettings['posixAccount_pwdHash'][0]) && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'LDAP_EXOP')) {
if (isset($ids['posixAccount_password']) && !empty($dataRow[$ids['posixAccount_password']])) {
$temp['exop'][] = [$accounts[$i]['dn'], $dataRow[$ids['posixAccount_password']]];
}
if (!empty($this->moduleSettings['posixAccount_pwdHash'][0])
&& ($this->moduleSettings['posixAccount_pwdHash'][0] === 'LDAP_EXOP')
&& isset($ids['posixAccount_password'])
&& !empty($dataRow[$ids['posixAccount_password']])) {
$temp['exop'][] = [$accounts[$i]['dn'], $dataRow[$ids['posixAccount_password']]];
}
}
$temp['dn_gon_keys'] = array_keys($temp['dn_gon']);
@ -3053,7 +3039,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
elseif (!isset($temp['dn'])) {
$temp['dn'] = [];
$ldapEntries = searchLDAPByAttribute('cn', '*', 'posixGroup', ['dn', 'cn'], ['group']);
for ($i = 0; $i < sizeof($ldapEntries); $i++) {
for ($i = 0; $i < count($ldapEntries); $i++) {
$temp['dn'][$ldapEntries[$i]['cn'][0]] = $ldapEntries[$i]['dn'];
}
return [
@ -3063,7 +3049,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
];
}
// add users to groups
elseif ($temp['counter'] < sizeof($temp['groups'])) {
elseif ($temp['counter'] < count($temp['groups'])) {
if (isset($temp['dn'][$temp['groups'][$temp['counter']]])) {
$memberUid = $temp['members'][$temp['groups'][$temp['counter']]];
$dnToUpdate = $temp['dn'][$temp['groups'][$temp['counter']]];
@ -3088,7 +3074,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$temp['counter']++;
return [
'status' => 'inProgress',
'progress' => ($temp['counter'] * 100) / (sizeof($temp['groups']) + sizeof($temp['createHomes']) + sizeof($temp['dn_gon']) + sizeof($temp['exop'])),
'progress' => ($temp['counter'] * 100) / (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']) + count($temp['exop'])),
'errors' => $errors
];
}
@ -3096,14 +3082,14 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$temp['counter']++;
return [
'status' => 'inProgress',
'progress' => ($temp['counter'] * 100) / (sizeof($temp['groups'] + sizeof($temp['createHomes']) + sizeof($temp['dn_gon']) + sizeof($temp['exop']))),
'progress' => ($temp['counter'] * 100) / (count($temp['groups'] + count($temp['createHomes']) + count($temp['dn_gon']) + count($temp['exop']))),
'errors' => [['ERROR', _('Unable to find group in LDAP.'), $temp['groups'][$temp['counter']]]]
];
}
}
// create home directories
elseif ($temp['counter'] < (sizeof($temp['groups']) + sizeof($temp['createHomes']))) {
$pos = $temp['createHomes'][$temp['counter'] - sizeof($temp['groups'])];
elseif ($temp['counter'] < (count($temp['groups']) + count($temp['createHomes']))) {
$pos = $temp['createHomes'][$temp['counter'] - count($temp['groups'])];
try {
$remote = new Remote();
$remoteServer = $_SESSION['config']->getScriptServerByName($data[$pos][$ids['posixAccount_createHomeDir']]);
@ -3126,13 +3112,13 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$temp['counter']++;
return [
'status' => 'inProgress',
'progress' => ($temp['counter'] * 100) / (sizeof($temp['groups']) + sizeof($temp['createHomes']) + sizeof($temp['dn_gon']) + sizeof($temp['exop'])),
'progress' => ($temp['counter'] * 100) / (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']) + count($temp['exop'])),
'errors' => $errors
];
}
// add users to group of names
elseif ($temp['counter'] < (sizeof($temp['groups']) + sizeof($temp['createHomes']) + sizeof($temp['dn_gon']))) {
$gonDn = $temp['dn_gon_keys'][$temp['counter'] - sizeof($temp['groups']) - sizeof($temp['createHomes'])];
elseif ($temp['counter'] < (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']))) {
$gonDn = $temp['dn_gon_keys'][$temp['counter'] - count($temp['groups']) - count($temp['createHomes'])];
$gonAttrToAdd = $temp['dn_gon'][$gonDn];
$gonAttrNames = array_keys($gonAttrToAdd);
$gonAttrs = ldapGetDN($gonDn, $gonAttrNames);
@ -3160,13 +3146,13 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$temp['counter']++;
return [
'status' => 'inProgress',
'progress' => ($temp['counter'] * 100) / (sizeof($temp['groups']) + sizeof($temp['createHomes']) + sizeof($temp['dn_gon']) + sizeof($temp['exop'])),
'progress' => ($temp['counter'] * 100) / (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']) + count($temp['exop'])),
'errors' => $errors
];
}
// run password exop commands
elseif ($temp['counter'] < (sizeof($temp['groups']) + sizeof($temp['createHomes']) + sizeof($temp['dn_gon']) + sizeof($temp['exop']))) {
$data = $temp['exop'][$temp['counter'] - sizeof($temp['groups']) - sizeof($temp['createHomes']) - sizeof($temp['dn_gon'])];
elseif ($temp['counter'] < (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']) + count($temp['exop']))) {
$data = $temp['exop'][$temp['counter'] - count($temp['groups']) - count($temp['createHomes']) - count($temp['dn_gon'])];
$dn = $data[0];
$password = $data[1];
$success = ldap_exop_passwd($_SESSION['ldap']->server(), $dn, null, $password);
@ -3182,7 +3168,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$temp['counter']++;
return [
'status' => 'inProgress',
'progress' => ($temp['counter'] * 100) / (sizeof($temp['groups']) + sizeof($temp['createHomes']) + sizeof($temp['dn_gon']) + sizeof($temp['exop'])),
'progress' => ($temp['counter'] * 100) / (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']) + count($temp['exop'])),
'errors' => $errors
];
}
@ -3448,56 +3434,53 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
*/
function checkSelfServiceOptions($fields, $attributes, $passwordChangeOnly, $readOnlyFields) {
$return = ['messages' => [], 'add' => [], 'del' => [], 'mod' => [], 'info' => []];
if (in_array('password', $fields)) {
if (isset($_POST['posixAccount_password']) && ($_POST['posixAccount_password'] != '')) {
if ($_POST['posixAccount_password'] != $_POST['posixAccount_password2']) {
$return['messages'][] = $this->messages['userPassword'][0];
if (in_array('password', $fields)
&& (isset($_POST['posixAccount_password']) && ($_POST['posixAccount_password'] != ''))) {
if ($_POST['posixAccount_password'] != $_POST['posixAccount_password2']) {
$return['messages'][] = $this->messages['userPassword'][0];
}
elseif (!get_preg($_POST['posixAccount_password'], 'password')) {
$return['messages'][] = $this->messages['userPassword'][1];
}
else {
$userName = empty($attributes['uid'][0]) ? null : $attributes['uid'][0];
$additionalAttrs = [];
if (!empty($attributes['sn'][0])) {
$additionalAttrs[] = $attributes['sn'][0];
}
else {
if (!get_preg($_POST['posixAccount_password'], 'password')) {
$return['messages'][] = $this->messages['userPassword'][1];
if (!empty($attributes['givenName'][0])) {
$additionalAttrs[] = $attributes['givenName'][0];
}
$pwdPolicyResult = checkPasswordStrength($_POST['posixAccount_password'], $userName, $additionalAttrs);
if ($pwdPolicyResult === true) {
$passwordHash = $this->selfServiceSettings->moduleSettings['posixAccount_pwdHash'][0];
if (empty($this->selfServiceSettings->moduleSettings['posixAccount_useOldPwd']) || ($this->selfServiceSettings->moduleSettings['posixAccount_useOldPwd'][0] != 'true')) {
// set SASL password
if (!empty($attributes['uid'][0]) && ($passwordHash === 'SASL')) {
$return['mod']['userpassword'][0] = '{SASL}' . $attributes['uid'][0];
}
elseif ($passwordHash === 'LDAP_EXOP') {
// no LDAP modify action, use ldap_exop_passwd
$return['info']['userPasswordModify'][0] = 'exop';
}
// set other password hashes
else {
$return['mod']['userpassword'][0] = pwd_hash($_POST['posixAccount_password'], true, $passwordHash);
}
}
else {
$userName = empty($attributes['uid'][0]) ? null : $attributes['uid'][0];
$additionalAttrs = [];
if (!empty($attributes['sn'][0])) {
$additionalAttrs[] = $attributes['sn'][0];
}
if (!empty($attributes['givenName'][0])) {
$additionalAttrs[] = $attributes['givenName'][0];
}
$pwdPolicyResult = checkPasswordStrength($_POST['posixAccount_password'], $userName, $additionalAttrs);
if ($pwdPolicyResult === true) {
$passwordHash = $this->selfServiceSettings->moduleSettings['posixAccount_pwdHash'][0];
if (empty($this->selfServiceSettings->moduleSettings['posixAccount_useOldPwd']) || ($this->selfServiceSettings->moduleSettings['posixAccount_useOldPwd'][0] != 'true')) {
// set SASL password
if (!empty($attributes['uid'][0]) && ($passwordHash === 'SASL')) {
$return['mod']['userpassword'][0] = '{SASL}' . $attributes['uid'][0];
}
elseif ($passwordHash === 'LDAP_EXOP') {
// no LDAP modify action, use ldap_exop_passwd
$return['info']['userPasswordModify'][0] = 'exop';
}
// set other password hashes
else {
$return['mod']['userpassword'][0] = pwd_hash($_POST['posixAccount_password'], true, $passwordHash);
}
}
else {
$return['add']['userpassword'][0] = pwd_hash($_POST['posixAccount_password'], true, $passwordHash);
$return['del']['userpassword'][0] = $_POST['posixAccount_passwordOld'];
}
$return['info']['userPasswordClearText'][0] = $_POST['posixAccount_password'];
if (isset($attributes['shadowlastchange'][0])) {
$return['mod']['shadowlastchange'][0] = intval(time() / 3600 / 24);
}
$_SESSION['selfService_clientPasswordNew'] = $_POST['posixAccount_password'];
}
else {
$return['messages'][] = ['ERROR', $pwdPolicyResult];
}
$return['add']['userpassword'][0] = pwd_hash($_POST['posixAccount_password'], true, $passwordHash);
$return['del']['userpassword'][0] = $_POST['posixAccount_passwordOld'];
}
$return['info']['userPasswordClearText'][0] = $_POST['posixAccount_password'];
if (isset($attributes['shadowlastchange'][0])) {
$return['mod']['shadowlastchange'][0] = intval(time() / 3600 / 24);
}
$_SESSION['selfService_clientPasswordNew'] = $_POST['posixAccount_password'];
}
else {
$return['messages'][] = ['ERROR', $pwdPolicyResult];
}
}
}
@ -3640,7 +3623,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
*/
private function getGID($groupname) {
$results = searchLDAPByAttribute('cn', $groupname, 'posixGroup', ['gidnumber'], ['group']);
if ((sizeof($results) > 0) && isset($results[0]['gidnumber'][0])) {
if ((count($results) > 0) && isset($results[0]['gidnumber'][0])) {
return $results[0]['gidnumber'][0];
}
return null;
@ -3654,7 +3637,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
*/
private function getGroupName($groupID) {
$results = searchLDAPByAttribute('gidNumber', $groupID, 'posixGroup', ['cn'], ['group']);
if ((sizeof($results) > 0) && isset($results[0]['cn'][0])) {
if ((count($results) > 0) && isset($results[0]['cn'][0])) {
return $results[0]['cn'][0];
}
return null;
@ -3684,7 +3667,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$filter = '(&' . $filter . $typeFilter . ')';
}
$results = searchLDAP($type->getSuffix(), $filter, ['cn', 'gidnumber']);
for ($i = 0; $i < sizeof($results); $i++) {
for ($i = 0; $i < count($results); $i++) {
if (isset($results[$i]['cn'][0]) && isset($results[$i]['gidnumber'][0])) {
$this->groupCache[] = [$results[$i]['gidnumber'][0], $results[$i]['cn'][0]];
}
@ -3708,7 +3691,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
foreach ($types as $type) {
$typeFilter = get_ldap_filter($type->getId());
$results = searchLDAP($type->getSuffix(), $typeFilter, ['cn', 'dn', 'objectClass']);
for ($i = 0; $i < sizeof($results); $i++) {
for ($i = 0; $i < count($results); $i++) {
if ((in_array_ignore_case('groupOfNames', $results[$i]['objectclass'])
|| in_array_ignore_case('groupOfMembers', $results[$i]['objectclass'])
|| in_array_ignore_case('groupOfUniqueNames', $results[$i]['objectclass']))
@ -3873,7 +3856,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// search for @key@ wildcards in format string and replace with first character of attribute
$wildcards = [];
if (preg_match_all('/@([^@]|[a-zA-Z_-])+@/', $format, $wildcards) > 0) {
for ($i = 0; $i < sizeof($wildcards[0]); $i++) {
for ($i = 0; $i < count($wildcards[0]); $i++) {
$wc = substr($wildcards[0][$i], 1, strlen($wildcards[0][$i]) - 2);
$value = '';
if (!empty($attributes[$wc][0])) {
@ -3885,7 +3868,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
// search for %key% wildcards in format string and replace with attribute
$wildcards = [];
if (preg_match_all('/%([^%]|[a-zA-Z_-])+%/', $format, $wildcards) > 0) {
for ($i = 0; $i < sizeof($wildcards[0]); $i++) {
for ($i = 0; $i < count($wildcards[0]); $i++) {
$wc = substr($wildcards[0][$i], 1, strlen($wildcards[0][$i]) - 2);
$value = '';
if (isset($attributes[$wc][0])) {
@ -3916,11 +3899,8 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
* @return boolean lockable
*/
public function isLockable(&$modules) {
if (isset($this->attributes[$this->getPasswordAttrName($modules)][0])
&& pwd_is_lockable($this->attributes[$this->getPasswordAttrName($modules)][0])) {
return true;
}
return false;
return isset($this->attributes[$this->getPasswordAttrName($modules)][0])
&& pwd_is_lockable($this->attributes[$this->getPasswordAttrName($modules)][0]);
}
/**
@ -3999,7 +3979,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$suffix = '$';
}
// Last character is no number
if (!preg_match('/^([0-9])+$/', $lastchar)) {
if (!preg_match('/^(\d)+$/', $lastchar)) {
// Last character is no number. Therefore we only have to add "2" to it.
$userName = $userName . '2' . $suffix;
}
@ -4014,7 +3994,7 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$mark = false;
// Set $i to the last character which is a number in $account_new->general_username
while (!$mark && ($i >= 0)) {
if (preg_match('/^([0-9])+$/', substr($userName, $i, strlen($userName) - $i))) {
if (preg_match('/^(\d)+$/', substr($userName, $i, strlen($userName) - $i))) {
$i--;
}
else {
@ -4037,13 +4017,15 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
*/
private function getShells() {
// self service
if (!isLoggedIn() && isset($this->selfServiceSettings) && isset($this->selfServiceSettings->moduleSettings['posixAccount_shells'])
&& (sizeof($this->selfServiceSettings->moduleSettings['posixAccount_shells'])) > 0) {
if (!isLoggedIn() && ($this->selfServiceSettings !== null)
&& isset($this->selfServiceSettings->moduleSettings['posixAccount_shells'])
&& (count($this->selfServiceSettings->moduleSettings['posixAccount_shells'])) > 0) {
return $this->selfServiceSettings->moduleSettings['posixAccount_shells'];
}
// server profile
if (!isset($this->selfServiceSettings) && isset($this->moduleSettings) && isset($this->moduleSettings['posixAccount_shells'])
&& (sizeof($this->moduleSettings['posixAccount_shells'])) > 0) {
if (($this->selfServiceSettings === null) && ($this->moduleSettings !== null)
&& isset($this->moduleSettings['posixAccount_shells'])
&& (count($this->moduleSettings['posixAccount_shells'])) > 0) {
return $this->moduleSettings['posixAccount_shells'];
}
// fall back to default
@ -4165,18 +4147,17 @@ class posixAccount extends baseModule implements passwordService, AccountStatusP
$replacements['user'] = $this->attributes['uid'][0];
}
// group name
if (isset($this->attributes['gidNumber'][0]) && ($this->attributes['gidNumber'][0] === self::CREATE_GROUP_WITH_SAME_NAME)) {
if (isset($this->attributes['gidNumber'][0])
&& ($this->attributes['gidNumber'][0] === self::CREATE_GROUP_WITH_SAME_NAME)) {
if (isset($replacements['user'])) {
$replacements['group'] = $replacements['user'];
}
}
else {
if (!empty($_POST['gidNumber'])) {
$replacements['group'] = $this->getGroupName($_POST['gidNumber']);
}
elseif (!empty($this->attributes['gidNumber'][0])) {
$replacements['group'] = $this->getGroupName($this->attributes['gidNumber'][0]);
}
elseif (!empty($_POST['gidNumber'])) {
$replacements['group'] = $this->getGroupName($_POST['gidNumber']);
}
elseif (!empty($this->attributes['gidNumber'][0])) {
$replacements['group'] = $this->getGroupName($this->attributes['gidNumber'][0]);
}
return $replacements;
}

View file

@ -100,7 +100,7 @@ class posixGroup extends baseModule implements passwordService {
$error_messages = [];
$needAutoGID = [];
$typeId = $type->getId();
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
if (!in_array("posixGroup", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "posixGroup";
}
@ -118,7 +118,7 @@ class posixGroup extends baseModule implements passwordService {
}
else {
$errMsg = $this->messages['gidNumber'][8];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$error_messages[] = $errMsg;
}
if ($this->manageCnAndDescription($selectedModules)) {
@ -137,7 +137,7 @@ class posixGroup extends baseModule implements passwordService {
}
else {
$errMsg = $this->messages['memberUID'][0];
array_push($errMsg, $i);
$errMsg[] = $i;
$error_messages[] = $errMsg;
}
}
@ -152,11 +152,11 @@ class posixGroup extends baseModule implements passwordService {
}
}
// fill in autoGIDs
if (sizeof($needAutoGID) > 0) {
if ($needAutoGID !== []) {
$errorsTemp = [];
$gids = $this->getNextGIDs(sizeof($needAutoGID), $errorsTemp, $type);
$gids = $this->getNextGIDs(count($needAutoGID), $errorsTemp, $type);
if (is_array($gids)) {
for ($i = 0; $i < sizeof($needAutoGID); $i++) {
for ($i = 0; $i < count($needAutoGID); $i++) {
$partialAccounts[$i]['gidNumber'] = $gids[$i];
}
}
@ -174,10 +174,10 @@ class posixGroup extends baseModule implements passwordService {
function delete_attributes(): array {
$return = [];
$result = searchLDAPByFilter('(&(objectClass=posixAccount)(gidNumber=' . $this->attributes['gidNumber'][0] . '))', ['dn'], ['user', 'host']);
if (sizeof($result) > 0) {
if (count($result) > 0) {
$max = 5;
if (sizeof($result) < 5) {
$max = sizeof($result);
if (count($result) < 5) {
$max = count($result);
}
$users = [];
for ($i = 0; $i < $max; $i++) {
@ -249,12 +249,7 @@ class posixGroup extends baseModule implements passwordService {
$members = [];
if (isset($this->attributes['memberUid'][0])) {
foreach ($this->attributes['memberUid'] as $uid) {
if (isset($users[$uid]) && isset($users[$uid]['cn'])) {
$members[] = $uid . ' (' . $users[$uid]['cn'] . ')';
}
else {
$members[] = $uid;
}
$members[] = (isset($users[$uid]) && isset($users[$uid]['cn'])) ? $uid . ' (' . $users[$uid]['cn'] . ')' : $uid;
}
}
$members = array_unique($members);
@ -363,7 +358,7 @@ class posixGroup extends baseModule implements passwordService {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['group']);
return $this->get_scope() === 'group';
}
/**
@ -510,7 +505,7 @@ class posixGroup extends baseModule implements passwordService {
$configContainer = new htmlResponsiveRow();
$configContainer->add(new htmlSubTitle(_("Groups")), 12);
foreach ($allScopes[static::class] as $typeId) {
if (sizeof($allScopes[static::class]) > 1) {
if (count($allScopes[static::class]) > 1) {
$title = new htmlDiv(null, new htmlOutputText($typeManager->getConfiguredType($typeId)->getAlias()));
$title->setCSSClasses(['bold', 'responsiveLabel']);
$configContainer->add($title, 12, 6);
@ -673,7 +668,7 @@ class posixGroup extends baseModule implements passwordService {
$this->addSimplePDFField($return, 'gidNumber', _('GID number'));
$this->addSimplePDFField($return, 'description', _('Description'));
if (in_array(static::class . '_memberUidPrimary', $pdfKeys)) {
$members = !empty($this->attributes['memberUid']) ? $this->attributes['memberUid'] : [];
$members = empty($this->attributes['memberUid']) ? [] : $this->attributes['memberUid'];
if (!empty($this->attributes['gidNumber'])) {
$filter = "(&(&" . get_ldap_filter('user') . ")(gidNumber=" . $this->attributes['gidNumber'][0] . "))";
$entries = searchLDAPByFilter($filter, ['uid'], ['user']);
@ -756,10 +751,7 @@ class posixGroup extends baseModule implements passwordService {
if ($this->manageCnAndDescription($modules) && ($this->attributes['cn'][0] == '')) {
return false;
}
if ((!isset($this->attributes['gidNumber'][0])) || $this->attributes['gidNumber'][0] === '') {
return false;
}
return true;
return isset($this->attributes['gidNumber'][0]) && $this->attributes['gidNumber'][0] !== '';
}
@ -825,12 +817,7 @@ class posixGroup extends baseModule implements passwordService {
if (isset($_POST['removePassword'])) {
unset($this->attributes[$this->passwordAttrName]);
}
if (isset($_POST['changegids'])) {
$this->changegids = true;
}
else {
$this->changegids = false;
}
$this->changegids = isset($_POST['changegids']);
if (!isset($this->attributes['gidNumber'][0]) || ($this->attributes['gidNumber'][0] != $_POST['gidNumber'])) {
// Check if GID is valid. If none value was entered, the next usable value will be inserted
$this->attributes['gidNumber'][0] = $_POST['gidNumber'];
@ -902,11 +889,11 @@ class posixGroup extends baseModule implements passwordService {
// get last character of group name
$lastchar = substr($this->attributes['cn'][0], strlen($this->attributes['cn'][0]) - 1, 1);
// Last character is no number
if (!preg_match('/^([0-9])+$/', $lastchar)) {
if (!preg_match('/^(\d)+$/', $lastchar)) {
/* Last character is no number. Therefore we only have to
* add "2" to it.
*/
$this->attributes['cn'][0] = $this->attributes['cn'][0] . '2';
$this->attributes['cn'][0] .= '2';
}
else {
/* Last character is a number -> we have to increase the number until we've
@ -918,7 +905,7 @@ class posixGroup extends baseModule implements passwordService {
$i = strlen($this->attributes['cn'][0]) - 1;
// Set $i to the last character which is a number in $account_new->general_username
while (true) {
if (preg_match('/^([0-9])+$/', substr($this->attributes['cn'][0], $i, strlen($this->attributes['cn'][0]) - $i))) {
if (preg_match('/^(\d)+$/', substr($this->attributes['cn'][0], $i, strlen($this->attributes['cn'][0]) - $i))) {
$i--;
}
else {
@ -994,7 +981,7 @@ class posixGroup extends baseModule implements passwordService {
$gon = $this->getAccountContainer()->getAccountModule('groupOfMembers');
}
if ($gon == null) {
return;
return $return;
}
if (!isset($this->attributes['memberUid'])) {
$this->attributes['memberUid'] = [];
@ -1099,8 +1086,8 @@ class posixGroup extends baseModule implements passwordService {
if ($this->changegids) {
// find all accounts to change
$result = searchLDAPByFilter('(&(objectClass=posixAccount)(gidNumber=' . $this->orig['gidNumber'][0] . '))', ['dn'], ['user', 'host']);
if (sizeof($result) > 0) {
for ($i = 0; $i < sizeof($result); $i++) {
if (count($result) > 0) {
for ($i = 0; $i < count($result); $i++) {
$return[$result[$i]['dn']]['modify']['gidNumber'][0] = $this->attributes['gidNumber'][0];
}
}
@ -1314,7 +1301,7 @@ class posixGroup extends baseModule implements passwordService {
$suffix = $this->moduleSettings['posixGroup_' . $typeId . '_gidCheckSuffix'][0];
}
$result = searchLDAP($suffix, $filter, $attrs);
for ($i = 0; $i < sizeof($result); $i++) {
for ($i = 0; $i < count($result); $i++) {
$this->cachedGIDList[] = $result[$i]['gidnumber'][0];
}
sort($this->cachedGIDList, SORT_NUMERIC);
@ -1338,7 +1325,7 @@ class posixGroup extends baseModule implements passwordService {
$filter = '(&(objectClass=user)(gidNumber=*)(uid=*))';
}
$result = searchLDAPByFilter($filter, ['uid', 'gidNumber', 'cn'], ['user']);
$resultCount = sizeof($result);
$resultCount = count($result);
for ($i = 0; $i < $resultCount; $i++) {
$this->cachedUserToGIDList[$result[$i]['uid'][0]] = [
'gid' => $result[$i]['gidnumber'][0],
@ -1378,7 +1365,7 @@ class posixGroup extends baseModule implements passwordService {
$suffix = $this->moduleSettings['posixGroup_' . $typeId . '_gidCheckSuffix'][0];
}
$result = searchLDAP($suffix, $filter, $attrs);
for ($i = 0; $i < sizeof($result); $i++) {
for ($i = 0; $i < count($result); $i++) {
$this->cachedGroupNameList[] = $result[$i]['cn'][0];
}
return $this->cachedGroupNameList;

View file

@ -64,7 +64,7 @@ class puppetClient extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['host']);
return $this->get_scope() === 'host';
}
/**
@ -250,17 +250,17 @@ class puppetClient extends baseModule {
if (isset($this->attributes['environment'][0])) {
$environments = $this->attributes['environment'];
}
if (sizeof($environments) == 0) {
if (count($environments) == 0) {
$environments[] = '';
}
$environmentLabel = new htmlOutputText(_('Environment'));
$return->addLabel($environmentLabel);
$environmentContainer = new htmlGroup();
for ($i = 0; $i < sizeof($environments); $i++) {
for ($i = 0; $i < count($environments); $i++) {
$environmentField = new htmlInputField('environment' . $i, $environments[$i]);
$environmentField->enableAutocompletion($autocompleteEnvironment);
$environmentContainer->addElement($environmentField);
if ($i < (sizeof($environments) - 1)) {
if ($i < (count($environments) - 1)) {
$environmentContainer->addElement(new htmlOutputText('<br>', false));
}
else {
@ -303,7 +303,7 @@ class puppetClient extends baseModule {
function process_attributes() {
if (isset($_POST['form_subpage_puppetClient_attributes_remObjectClass'])) {
$this->attributes['objectClass'] = array_delete(['puppetClient'], $this->attributes['objectClass']);
for ($i = 0; $i < sizeof($this->meta['attributes']); $i++) {
for ($i = 0; $i < count($this->meta['attributes']); $i++) {
if (isset($this->attributes[$this->meta['attributes'][$i]])) {
unset($this->attributes[$this->meta['attributes'][$i]]);
}
@ -357,7 +357,7 @@ class puppetClient extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("puppetClient", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "puppetClient";
@ -408,7 +408,7 @@ class puppetClient extends baseModule {
$this->addSimplePDFField($return, 'parentnode', _('Parent node'));
if (isset($this->attributes['puppetclass'][0])) {
$pdfTable = new PDFTable(_('Classes'));
for ($i = 0; $i < sizeof($this->attributes['puppetclass']); $i++) {
for ($i = 0; $i < count($this->attributes['puppetclass']); $i++) {
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell($this->attributes['puppetclass'][$i]);
$pdfTable->rows[] = $pdfRow;
@ -417,7 +417,7 @@ class puppetClient extends baseModule {
}
if (isset($this->attributes['puppetvar'][0])) {
$pdfTable = new PDFTable(_('Variables'));
for ($i = 0; $i < sizeof($this->attributes['puppetvar']); $i++) {
for ($i = 0; $i < count($this->attributes['puppetvar']); $i++) {
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell($this->attributes['puppetvar'][$i]);
$pdfTable->rows[] = $pdfRow;
@ -448,10 +448,10 @@ class puppetClient extends baseModule {
// profile mappings in meta data
parent::load_profile($profile);
// add extension
if (isset($profile['puppetClient_addExt'][0]) && ($profile['puppetClient_addExt'][0] == "true")) {
if (!in_array('puppetClient', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'puppetClient';
}
if (isset($profile['puppetClient_addExt'][0])
&& ($profile['puppetClient_addExt'][0] == "true")
&& !in_array('puppetClient', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'puppetClient';
}
// parent node
if (isset($profile['puppetClient_parentnode'][0]) && ($profile['puppetClient_parentnode'][0] != "-")) {
@ -475,7 +475,7 @@ class puppetClient extends baseModule {
private function getPossibleParentNodes() {
$searchResult = searchLDAPByAttribute('cn', '*', 'puppetClient', ['cn'], ['host']);
$possibleParentNodes = [];
for ($i = 0; $i < sizeof($searchResult); $i++) {
for ($i = 0; $i < count($searchResult); $i++) {
if (!get_preg($searchResult[$i]['cn'][0], 'ascii')) {
continue;
}

View file

@ -49,7 +49,7 @@ class pykotaBillingCode extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['pykotaBillingCodeType']);
return $this->get_scope() === 'pykotaBillingCodeType';
}
/**
@ -231,7 +231,7 @@ class pykotaBillingCode extends baseModule {
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
$this->loadCodeCache();
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object classes
if (!in_array('pykotaBilling', $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = 'pykotaBilling';
@ -242,12 +242,12 @@ class pykotaBillingCode extends baseModule {
// pykotaBillingCode
if (!get_preg($rawAccounts[$i][$ids['pykotaBillingCode_pykotaBillingCode']], 'username')) {
$errMsg = $this->messages['pykotaBillingCode'][1];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$messages[] = $errMsg;
}
elseif ($this->codeExists($rawAccounts[$i][$ids['pykotaBillingCode_pykotaBillingCode']])) {
$errMsg = $this->messages['pykotaBillingCode'][3];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$messages[] = $errMsg;
}
else {

View file

@ -83,7 +83,7 @@ class pykotaGroup extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['group']);
return $this->get_scope() === 'group';
}
/**
@ -420,7 +420,7 @@ class pykotaGroup extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object classes
if (!in_array('pykotaGroup', $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = 'pykotaGroup';
@ -432,12 +432,12 @@ class pykotaGroup extends baseModule {
if ($this->isUnixOrGonInactive($selectedModules) && !empty($rawAccounts[$i][$ids['pykotaGroup_cn']])) {
if (!get_preg($rawAccounts[$i][$ids['pykotaGroup_cn']], 'groupname')) {
$errMsg = $this->messages['cn'][1];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$messages[] = $errMsg;
}
elseif ($this->cnExists($rawAccounts[$i][$ids['pykotaGroup_cn']])) {
$errMsg = $this->messages['cn'][3];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$messages[] = $errMsg;
}
else {
@ -450,12 +450,12 @@ class pykotaGroup extends baseModule {
if (!empty($rawAccounts[$i][$ids['pykotaGroup_pykotaGroupName']])) {
if (!get_preg($rawAccounts[$i][$ids['pykotaGroup_pykotaGroupName']], 'groupname')) {
$errMsg = $this->messages['pykotaGroupName'][1];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$messages[] = $errMsg;
}
elseif ($this->pykotaGroupNameExists($rawAccounts[$i][$ids['pykotaGroup_pykotaGroupName']])) {
$errMsg = $this->messages['pykotaGroupName'][3];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$messages[] = $errMsg;
}
else {
@ -469,7 +469,7 @@ class pykotaGroup extends baseModule {
}
else {
$errMsg = $this->messages['pykotaLimitBy'][0];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$messages[] = $errMsg;
}
}

View file

@ -267,7 +267,7 @@ class pykotaPrinter extends baseModule {
foreach ($groups as $groupDN) {
$parentPrinters[] = $this->printerCache[$groupDN]['cn'];
}
if (sizeof($parentPrinters) > 0) {
if ($parentPrinters !== []) {
$container->addLabel(new htmlOutputText(_('Printer groups')));
$parentPrinterText = new htmlOutputText(implode(', ', $parentPrinters));
$container->addField($parentPrinterText, true);
@ -282,7 +282,7 @@ class pykotaPrinter extends baseModule {
$memberTable = new htmlTable();
if (!empty($this->attributes['uniqueMember'][0])) {
$memberTable->alignment = htmlElement::ALIGN_TOP;
for ($i = 0; $i < sizeof($this->attributes['uniqueMember']); $i++) {
for ($i = 0; $i < count($this->attributes['uniqueMember']); $i++) {
$member = $this->attributes['uniqueMember'][$i];
if (isset($this->printerCache[$member]['cn'])) {
$member = $this->printerCache[$member]['cn'];
@ -291,7 +291,7 @@ class pykotaPrinter extends baseModule {
$delButton = new htmlButton('uniqueMemberDel_' . $i, 'del.svg', true);
$delButton->setTitle(_('Delete'));
$memberTable->addElement($delButton);
if ($i == (sizeof($this->attributes['uniqueMember']) - 1)) {
if ($i === count($this->attributes['uniqueMember']) - 1) {
$memberTable->addElement($addMemberButton);
$memberTable->addElement($memberHelp);
}
@ -376,7 +376,7 @@ class pykotaPrinter extends baseModule {
// passthrough
$this->attributes['pykotaPassThrough'][0] = $_POST['pykotaPassThrough'];
// delete members
foreach ($_POST as $key => $value) {
foreach (array_keys($_POST) as $key) {
if (str_starts_with($key, 'uniqueMemberDel_')) {
$index = substr($key, strlen('uniqueMemberDel_'));
unset($this->attributes['uniqueMember'][$index]);
@ -397,12 +397,7 @@ class pykotaPrinter extends baseModule {
$options = [];
$this->loadPrinterNameCache();
foreach ($this->printerCache as $dn => $attrs) {
if (!empty($attrs['description'])) {
$label = $attrs['cn'] . ' (' . $attrs['description'] . ')';
}
else {
$label = $attrs['cn'];
}
$label = empty($attrs['description']) ? $attrs['cn'] : $attrs['cn'] . ' (' . $attrs['description'] . ')';
// skip own entry
if (!$this->getAccountContainer()->isNewAccount && ($this->getAccountContainer()->dn_orig == $dn)) {
continue;
@ -414,8 +409,8 @@ class pykotaPrinter extends baseModule {
$options[$label] = $dn;
}
$size = 20;
if (sizeof($options) < 20) {
$size = sizeof($options);
if (count($options) < 20) {
$size = count($options);
}
$membersSelect = new htmlSelect('members', $options, [], $size);
$membersSelect->setHasDescriptiveElements(true);
@ -448,7 +443,7 @@ class pykotaPrinter extends baseModule {
function process_members() {
$return = [];
if (isset($_POST['form_subpage_' . static::class . '_attributes_addMembers']) && isset($_POST['members'])) {
for ($i = 0; $i < sizeof($_POST['members']); $i++) {
for ($i = 0; $i < count($_POST['members']); $i++) {
$this->attributes['uniqueMember'][] = $_POST['members'][$i];
}
}
@ -462,7 +457,7 @@ class pykotaPrinter extends baseModule {
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
$this->loadPrinterNameCache();
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object classes
if (!in_array('pykotaPrinter', $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = 'pykotaPrinter';
@ -568,7 +563,7 @@ class pykotaPrinter extends baseModule {
$messages[] = $errMsg;
}
}
if (sizeof($memberDNs) > 0) {
if ($memberDNs !== []) {
$partialAccounts[$i]['uniqueMember'] = $memberDNs;
}
}
@ -599,12 +594,7 @@ class pykotaPrinter extends baseModule {
if (!empty($this->attributes['uniqueMember'][0])) {
$members = [];
foreach ($this->attributes['uniqueMember'] as $member) {
if (!empty($this->printerCache[$member]['cn'])) {
$members[] = $this->printerCache[$member]['cn'];
}
else {
$members[] = getAbstractDN($member);
}
$members[] = empty($this->printerCache[$member]['cn']) ? getAbstractDN($member) : $this->printerCache[$member]['cn'];
}
$this->addPDFKeyValue($return, 'uniqueMember', _('Group members'), implode(', ', $members));
}
@ -612,14 +602,9 @@ class pykotaPrinter extends baseModule {
$parentGroups = [];
$groups = $this->getPrinterGroups();
foreach ($groups as $group) {
if (!empty($this->printerCache[$group]['cn'])) {
$parentGroups[] = $this->printerCache[$group]['cn'];
}
else {
$parentGroups[] = getAbstractDN($group);
}
$parentGroups[] = empty($this->printerCache[$group]['cn']) ? getAbstractDN($group) : $this->printerCache[$group]['cn'];
}
if (sizeof($parentGroups) > 0) {
if ($parentGroups !== []) {
$this->addPDFKeyValue($return, 'parentUniqueMember', _('Printer groups'), implode(', ', $parentGroups));
}
return $return;

View file

@ -261,7 +261,7 @@ class pykotaUser extends baseModule {
'pykotaJobHistory' => _('Job history'),
];
// self service settings
if (static::class == 'pykotaUser') {
if (static::class === 'pykotaUser') {
$selfServiceContainer = new htmlResponsiveRow();
$selfServiceContainer->add(new htmlResponsiveInputField(_('Job suffix'), 'pykotaUser_jobSuffix', null, ['jobSuffix', static::class]));
$return['selfServiceSettings'] = $selfServiceContainer;
@ -510,12 +510,7 @@ class pykotaUser extends baseModule {
$this->processMultiValueInputTextField('description', $errors);
}
// overcharge factor
if (!empty($_POST['pykotaOverCharge'])) {
$this->attributes['pykotaOverCharge'][0] = $_POST['pykotaOverCharge'];
}
else {
$this->attributes['pykotaOverCharge'][0] = '1.0';
}
$this->attributes['pykotaOverCharge'][0] = empty($_POST['pykotaOverCharge']) ? '1.0' : $_POST['pykotaOverCharge'];
// add payment
if (isset($_POST['addPayment'])) {
$amount = $_POST['pykotaBalanceAdd'];
@ -761,7 +756,7 @@ class pykotaUser extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object classes
if (!in_array('pykotaAccount', $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = 'pykotaAccount';
@ -920,7 +915,7 @@ class pykotaUser extends baseModule {
$pdfRow->cells[] = new PDFTableCell(_('Amount'), '10%', null, true);
$pdfRow->cells[] = new PDFTableCell(_('Comment'), '70%', null, true);
$pdfTable->rows[] = $pdfRow;
for ($i = 0; $i < sizeof($this->attributes['pykotaPayments']); $i++) {
for ($i = 0; $i < count($this->attributes['pykotaPayments']); $i++) {
$parts = explode(' # ', $this->attributes['pykotaPayments'][$i]);
$comment = ' ';
if (!empty($parts[2])) {
@ -1046,7 +1041,7 @@ class pykotaUser extends baseModule {
*/
public function checkSelfServiceSettings(&$options, &$profile) {
$errors = [];
if ((static::class == 'pykotaUser')
if ((static::class === 'pykotaUser')
&& !empty($options['pykotaUser_jobSuffix'][0])
&& !get_preg($options['pykotaUser_jobSuffix'][0], 'dn')) {
$errors[] = $this->messages['jobSuffix'][0];
@ -1183,7 +1178,7 @@ class pykotaUser extends baseModule {
$jobs[$job['createtimestamp'][0] . $index] = $job;
}
krsort($jobs);
if (sizeof($jobs) > 100) {
if (count($jobs) > 100) {
$jobs = array_slice($jobs, 0, 100);
}
return array_values($jobs);
@ -1221,7 +1216,7 @@ class pykotaUser extends baseModule {
return function(array $entry, string $attribute): ?htmlElement {
$group = new htmlGroup();
if (isset($entry[$attribute][0]) && ($entry[$attribute][0] != '')) {
for ($i = 0; $i < sizeof($entry[$attribute]); $i++) {
for ($i = 0; $i < count($entry[$attribute]); $i++) {
if ($i > 0) {
$group->addElement(new htmlOutputText(", "));
}

View file

@ -173,7 +173,7 @@ class quota extends baseModule {
* @param RemoteServerConfiguration[] $lamdaemonServers server configurations
*/
function initQuotas($userName = null, $lamdaemonServers = null) {
if (isset($this->quota)) {
if ($this->quota !== null) {
return;
}
if ($userName === null) {
@ -185,7 +185,7 @@ class quota extends baseModule {
}
$userName = $this->attributes['uid'][0];
}
else if ($this->get_scope() == 'group') {
elseif ($this->get_scope() == 'group') {
if (!isset($this->attributes['cn'][0])) {
return;
}
@ -215,7 +215,7 @@ class quota extends baseModule {
}
$allQuotas = explode(":", $quotas);
array_pop($allQuotas); // remove empty element at the end
for ($i = 0; $i < sizeof($allQuotas); $i++) {
for ($i = 0; $i < count($allQuotas); $i++) {
if (!str_starts_with($allQuotas[$i], self::$QUOTA_PREFIX)) {
continue;
}
@ -358,7 +358,7 @@ class quota extends baseModule {
*/
private function getCn() {
$modules = ['posixGroup', 'windowsPosixGroup', 'rfc2307bisPosixGroup', 'groupOfNames', 'groupOfUniqueNames', 'windowsGroup'];
for ($i = 0; $i < sizeof($modules); $i++) {
for ($i = 0; $i < count($modules); $i++) {
if ($this->getAccountContainer()->getAccountModule($modules[$i]) != null) {
$attrs = $this->getAccountContainer()->getAccountModule($modules[$i])->getAttributes();
if (isset($attrs['cn'][0])) {
@ -396,7 +396,7 @@ class quota extends baseModule {
*/
public function postModifyActions($newAccount, $attributes) {
$messages = [];
if (!isset($this->quota) || !is_array($this->quota)
if (!is_array($this->quota)
|| ($this->getAccountContainer() === null)
|| ($this->getAccountContainer()->finalDN === null)) {
return $messages;
@ -411,10 +411,10 @@ class quota extends baseModule {
}
// get list of lamdaemon servers
$servers = array_keys($this->quota);
for ($q = 0; $q < sizeof($servers); $q++) {
for ($q = 0; $q < count($servers); $q++) {
$server = $servers[$q];
$quotastring = "";
for ($i = 0; $i < sizeof($this->quota[$server]); $i++) {
for ($i = 0; $i < count($this->quota[$server]); $i++) {
$quotastring .= $this->quota[$server][$i][0];
$quotastring .= ',' . $this->getQuotaNumber($this->quota[$server][$i][2]);
$quotastring .= ',' . $this->getQuotaNumber($this->quota[$server][$i][3]);
@ -488,7 +488,7 @@ class quota extends baseModule {
catch (LAMException $e) {
return [['ERROR', $e->getTitle(), $e->getMessage()]];
}
if (!isset($this->quota) || !is_array($this->quota)) {
if (!is_array($this->quota)) {
return [];
}
// determine if this is a user or group account
@ -502,7 +502,7 @@ class quota extends baseModule {
$messages = [];
// get list of lamdaemon servers
$servers = array_keys($this->quota);
for ($q = 0; $q < sizeof($servers); $q++) {
for ($q = 0; $q < count($servers); $q++) {
$server = $servers[$q];
$i = 0;
$quotastring = "";
@ -532,13 +532,13 @@ class quota extends baseModule {
* @return array list of info/error messages
*/
function process_attributes() {
if (!isset($this->quota) || !is_array($this->quota)) {
if (!is_array($this->quota)) {
return [];
}
$errors = [];
// get list of lamdaemon servers
$servers = array_keys($this->quota);
for ($q = 0; $q < sizeof($servers); $q++) {
for ($q = 0; $q < count($servers); $q++) {
$server = $servers[$q];
$id = $this->replaceSpecialChars($server);
$i = 0;
@ -594,12 +594,12 @@ class quota extends baseModule {
// get list of lamdaemon servers
$serverDescriptions = [];
$lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
for ($s = 0; $s < sizeof($lamdaemonServers); $s++) {
for ($s = 0; $s < count($lamdaemonServers); $s++) {
$lamdaemonServer = $lamdaemonServers[$s];
$serverDescriptions[$lamdaemonServer->getServer()] = $lamdaemonServer->getLabel();
}
$servers = array_keys($this->quota);
for ($q = 0; $q < sizeof($servers); $q++) {
for ($q = 0; $q < count($servers); $q++) {
$server = $servers[$q];
$id = $this->replaceSpecialChars($server);
$title = $server;
@ -688,7 +688,7 @@ class quota extends baseModule {
if (empty($dirs)) {
continue;
}
for ($i = 0; $i < sizeof($dirs); $i++) {
for ($i = 0; $i < count($dirs); $i++) {
if (!str_starts_with($dirs[$i], self::$QUOTA_PREFIX)) {
unset($dirs[$i]);
$dirs = array_values($dirs);
@ -700,12 +700,12 @@ class quota extends baseModule {
$dirs[$i] = $dirs[$i][0];
}
$dirs = array_values($dirs);
if (sizeof($dirs) < 1) {
if (count($dirs) < 1) {
continue; // stop if no quota directories were found
}
$optionsAvailable = true;
$return->add(new htmlSubTitle($description));
for ($i = 0; $i < sizeof($dirs); $i++) {
for ($i = 0; $i < count($dirs); $i++) {
$return->add(new htmlOutputText($dirs[$i]));
$sbLimit = new htmlResponsiveInputField(_('Soft block limit'), "quota_softblock_" . $id . "_" . $dirs[$i], null, 'SoftBlockLimit');
$sbLimit->setFieldMaxLength(20);
@ -806,14 +806,14 @@ class quota extends baseModule {
catch (LAMException $e) {
logNewMessage(LOG_ERR, $e->getTitle() . ' - ' . $e->getMessage());
}
if (!isset($this->quota) || !is_array($this->quota)) {
if (!is_array($this->quota)) {
return;
}
$servers = array_keys($this->quota);
for ($s = 0; $s < sizeof($servers); $s++) {
for ($s = 0; $s < count($servers); $s++) {
$server = $servers[$s];
$id = $this->replaceSpecialChars($server);
for ($i = 0; $i < sizeof($this->quota[$server]); $i++) {
for ($i = 0; $i < count($this->quota[$server]); $i++) {
$dir = $this->quota[$server][$i][0];
if (isset($profile["quota_softblock_" . $id . "_" . $dir])) {
$this->quota[$server][$i][2] = $profile["quota_softblock_" . $id . "_" . $dir][0];
@ -843,10 +843,10 @@ class quota extends baseModule {
logNewMessage(LOG_ERR, $e->getTitle() . ' - ' . $e->getMessage());
return [];
}
if (!isset($this->quota) || !is_array($this->quota)) {
if (!is_array($this->quota)) {
return [];
}
if (sizeof($this->quota) > 0) {
if ($this->quota !== []) {
$pdfTable = new PDFTable();
// get list of lamdaemon servers
$lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
@ -856,7 +856,7 @@ class quota extends baseModule {
if ($description != $server) {
$description = $description . " (" . $server . ")";
}
if (!isset($this->quota[$server]) || (sizeof($this->quota[$server]) < 1)) {
if (!isset($this->quota[$server]) || (count($this->quota[$server]) < 1)) {
continue;
}
$pdfRow = new PDFTableRow();
@ -869,7 +869,7 @@ class quota extends baseModule {
$pdfRow->cells[] = new PDFTableCell(_('Soft inode'), '18%', null, true);
$pdfRow->cells[] = new PDFTableCell(_('Hard inode'), '18%', null, true);
$pdfTable->rows[] = $pdfRow;
for ($i = 0; $i < sizeof($this->quota[$server]); $i++) {
for ($i = 0; $i < count($this->quota[$server]); $i++) {
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell($this->quota[$server][$i][0], '28%');
$pdfRow->cells[] = new PDFTableCell($this->quota[$server][$i][2], '18%');
@ -903,11 +903,11 @@ class quota extends baseModule {
logNewMessage(LOG_ERR, $e->getTitle() . ' - ' . $e->getMessage());
return [];
}
if (!isset($this->quota) || !is_array($this->quota)) {
if (!is_array($this->quota)) {
return [];
}
$return = [];
if (sizeof($this->quota) > 0) {
if ($this->quota !== []) {
// get list of lamdaemon servers
$lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
foreach ($lamdaemonServers as $lamdaemonServer) {
@ -925,7 +925,7 @@ class quota extends baseModule {
$remote->disconnect();
$dirs = explode(":", $quotas);
array_pop($dirs); // remove empty element at the end
for ($i = 0; $i < sizeof($dirs); $i++) {
for ($i = 0; $i < count($dirs); $i++) {
if (!str_starts_with($dirs[$i], self::$QUOTA_PREFIX)) {
unset($dirs[$i]);
$i--;
@ -936,7 +936,7 @@ class quota extends baseModule {
$dirs[$i] = $dirs[$i][0];
}
$dirs = array_values($dirs);
for ($i = 0; $i < sizeof($dirs); $i++) {
for ($i = 0; $i < count($dirs); $i++) {
$return[] = [
'name' => 'quota_' . $server . ':' . $dirs[$i],
'description' => sprintf(_('Quota for %s on %s'), $dirs[$i], $server),
@ -960,7 +960,7 @@ class quota extends baseModule {
// create list of quota columns
$temp['quotas'] = [];
$columns = array_keys($ids);
for ($i = 0; $i < sizeof($columns); $i++) {
for ($i = 0; $i < count($columns); $i++) {
if (str_starts_with($columns[$i], 'quota_')) {
$temp['quotas'][] = substr($columns[$i], 6);
}
@ -975,16 +975,16 @@ class quota extends baseModule {
$col = $ids['posixGroup_cn'];
}
// create list of account names and their quota values
for ($i = 0; $i < sizeof($data); $i++) {
for ($i = 0; $i < count($data); $i++) {
if (in_array($i, $failed)) {
continue; // ignore failed accounts
}
$name = $data[$i][$col];
for ($m = 0; $m < sizeof($temp['quotas']); $m++) {
for ($m = 0; $m < count($temp['quotas']); $m++) {
if ($data[$i][$ids['quota_' . $temp['quotas'][$m]]] != '') {
$parts = explode(',', $data[$i][$ids['quota_' . $temp['quotas'][$m]]]);
// check syntax
if (sizeof($parts) != 4) {
if (count($parts) != 4) {
$errMsg = $this->messages['upload'][0];
$errMsg[] = [$i, 'quota_' . $temp['quotas'][$m]];
$errors[] = $errMsg;
@ -1038,12 +1038,12 @@ class quota extends baseModule {
return ['status' => 'inProgress', 'progress' => 5, 'errors' => $errors];
}
// quotas are ready to set
elseif ($temp['counter'] < sizeof($temp['accounts'])) {
elseif ($temp['counter'] < count($temp['accounts'])) {
$names = array_keys($temp['accounts']);
$name = $names[$temp['counter']];
$mountPoints = array_keys($temp['accounts'][$name]);
// set quota
for ($m = 0; $m < sizeof($mountPoints); $m++) {
for ($m = 0; $m < count($mountPoints); $m++) {
$mpParts = explode(":", $mountPoints[$m]);
$server = $mpParts[0];
$dir = $mpParts[1];
@ -1062,7 +1062,7 @@ class quota extends baseModule {
$remote->disconnect();
if (!empty($result)) {
$parts = explode(",", $result);
if ($parts[0] == 'ERROR') {
if ($parts[0] === 'ERROR') {
$errors[] = ['ERROR', $parts[1], $parts[2]];
}
}
@ -1071,7 +1071,7 @@ class quota extends baseModule {
$temp['counter']++;
return [
'status' => 'inProgress',
'progress' => 5 + (95 * ($temp['counter'] / sizeof($temp['accounts']))),
'progress' => 5 + (95 * ($temp['counter'] / count($temp['accounts']))),
'errors' => $errors];
}
return ['status' => 'finished'];

View file

@ -263,20 +263,20 @@ class range extends baseModule {
$ex_subnet = explode(".", $this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0]);
$dhcpAttrs = $this->getAccountContainer()->getAccountModule('dhcp_settings')->getAttributes();
$mask = $this->getAccountContainer()->getAccountModule('dhcp_settings')->getDHCPOption('subnet-mask');
foreach ($this->ranges as $id => $arr) {
if (!empty($this->ranges[$id]['range_start']) && !range::check_subnet_range($this->ranges[$id]['range_start'], $dhcpAttrs['cn'][0], $mask)) {
// Range anpassen:
$ex = explode(".", $this->ranges[$id]['range_start']);
$tmp = $this->ranges[$id]['range_start'];
foreach ($this->ranges as $id => $range) {
if (!empty($range['range_start']) && !range::check_subnet_range($range['range_start'], $dhcpAttrs['cn'][0], $mask)) {
// adapt range
$ex = explode(".", $range['range_start']);
$tmp = $range['range_start'];
$this->ranges[$id]['range_start'] = $ex_subnet['0'] . "." . $ex_subnet['1'] . "." . $ex_subnet['2'] . "." . $ex['3'];
if ($tmp != $this->ranges[$id]['range_start']) {
$range_edit = true;
}
}
if (!empty($this->ranges[$id]['range_end']) && !range::check_subnet_range($this->ranges[$id]['range_end'], $dhcpAttrs['cn'][0], $mask)) {
// Range anpassen:
$ex = explode(".", $this->ranges[$id]['range_end']);
$tmp = $this->ranges[$id]['range_end'];
if (!empty($range['range_end']) && !range::check_subnet_range($range['range_end'], $dhcpAttrs['cn'][0], $mask)) {
// adapt range
$ex = explode(".", $range['range_end']);
$tmp = $range['range_end'];
$this->ranges[$id]['range_end'] = $ex_subnet['0'] . "." . $ex_subnet['1'] . "." . $ex_subnet['2'] . "." . $ex['3'];
if ($tmp != $this->ranges[$id]['range_end']) {
$range_edit = true;
@ -285,8 +285,8 @@ class range extends baseModule {
}
if ($range_edit) {
// sort the range new, id it was edit.
foreach ($this->ranges as $id => $arr) {
$this->attributes['dhcpRange'][$id] = $this->ranges[$id]['range_start'] . " " . $this->ranges[$id]['range_end'];
foreach ($this->ranges as $id => $range) {
$this->attributes['dhcpRange'][$id] = $range['range_start'] . " " . $range['range_end'];
}
}
}
@ -479,39 +479,39 @@ class range extends baseModule {
$this->reset_overlapped_range();
$mask = $this->getAccountContainer()->getAccountModule('dhcp_settings')->getDHCPOption('subnet-mask');
$subnet = $this->getAccountContainer()->getAccountModule('dhcp_settings')->attributes['cn'][0];
foreach ($this->ranges as $id => $arr) {
foreach ($this->ranges as $id => $range) {
// Range start
$error = "";
if (isset($this->ranges[$id]['range_start']) && !empty($this->ranges[$id]['range_start'])) {
if ($this->processed && !check_ip($this->ranges[$id]['range_start'])) {
if (isset($range['range_start']) && !empty($range['range_start'])) {
if ($this->processed && !check_ip($range['range_start'])) {
$error = _("The IP address is invalid.");
}
elseif ($this->processed && !$this->check_range($this->ranges[$id]['range_start'], $this->ranges[$id]['range_end'])) {
elseif ($this->processed && !$this->check_range($range['range_start'], $range['range_end'])) {
$error = _("The range end needs to be greater than the range start.");
}
elseif ($this->processed && !range::check_subnet_range($this->ranges[$id]['range_start'], $subnet, $mask)) {
elseif ($this->processed && !range::check_subnet_range($range['range_start'], $subnet, $mask)) {
$error = _("The IP does not match the subnet.");
}
elseif ($this->processed && !$this->isNotOverlappedRange($this->ranges[$id]['range_start'], $this->ranges[$id]['range_end'])) {
elseif ($this->processed && !$this->isNotOverlappedRange($range['range_start'], $range['range_end'])) {
$error = _("The range conflicts with another range.");
}
}
$fromInput = new htmlResponsiveInputField(_('Range from'), 'range_start_' . $id, $this->ranges[$id]['range_start'], 'range_from', true);
$fromInput = new htmlResponsiveInputField(_('Range from'), 'range_start_' . $id, $range['range_start'], 'range_from', true);
$return->add($fromInput);
if (!empty($error)) {
$return->add(new htmlOutputText($error));
}
// Range end
$error = "";
if (isset($this->ranges[$id]['range_end']) && !empty($this->ranges[$id]['range_end'])) {
if ($this->processed && !check_ip($this->ranges[$id]['range_end'])) {
if (isset($range['range_end']) && !empty($range['range_end'])) {
if ($this->processed && !check_ip($range['range_end'])) {
$error = _("The IP address is invalid.");
}
elseif ($this->processed && !range::check_subnet_range($this->ranges[$id]['range_end'], $subnet, $mask)) {
elseif ($this->processed && !range::check_subnet_range($range['range_end'], $subnet, $mask)) {
$error = _("The IP does not match the subnet.");
}
}
$toInput = new htmlResponsiveInputField(_('Range to'), 'range_end_' . $id, $this->ranges[$id]['range_end'], 'range_to', true);
$toInput = new htmlResponsiveInputField(_('Range to'), 'range_end_' . $id, $range['range_end'], 'range_to', true);
$return->add($toInput);
if (!empty($error)) {
$return->add(new htmlOutputText($error));
@ -532,7 +532,7 @@ class range extends baseModule {
if (!empty($this->poolsNew)) {
$return->add(new htmlSubTitle(_('Pools')));
foreach ($this->poolsNew as $index => $poolAttrs) {
$cn = !empty($poolAttrs['cn'][0]) ? $poolAttrs['cn'][0] : '';
$cn = empty($poolAttrs['cn'][0]) ? '' : $poolAttrs['cn'][0];
$nameField = new htmlResponsiveInputField(_('Name'), 'pool_cn_' . $index, $cn, 'poolName', true);
$return->add($nameField);
$peer = '';
@ -551,8 +551,8 @@ class range extends baseModule {
if (!empty($poolAttrs['dhcprange'])) {
foreach ($poolAttrs['dhcprange'] as $rIndex => $range) {
$range = explode(' ', $range);
$from = !empty($range[0]) ? $range[0] : '';
$to = !empty($range[1]) ? $range[1] : '';
$from = empty($range[0]) ? '' : $range[0];
$to = empty($range[1]) ? '' : $range[1];
$fromInput = new htmlResponsiveInputField(_('Range from'), 'pool_from_' . $index . '_' . $rIndex, $from, 'range_from', true);
$toInput = new htmlResponsiveInputField(_('Range to'), 'pool_to_' . $index . '_' . $rIndex, $to, 'range_to', true);
$return->add($fromInput);
@ -660,7 +660,7 @@ class range extends baseModule {
}
if ((!empty($pool[$attr]) && empty($poolOrig[$attr]))
|| (empty($pool[$attr]) && !empty($poolOrig[$attr]))
|| (sizeof($pool[$attr]) != sizeof($poolOrig[$attr]))) {
|| (count($pool[$attr]) !== count($poolOrig[$attr]))) {
$changed = true;
}
else {
@ -743,9 +743,9 @@ class range extends baseModule {
*/
function get_pdfEntries($pdfKeys, $typeId) {
$return = [];
if (is_array($this->ranges) && (sizeof($this->ranges) > 0)) {
if (is_array($this->ranges) && ($this->ranges !== [])) {
$pdfTable = new PDFTable(_('Ranges'));
for ($i = 0; $i < sizeof($this->ranges); $i++) {
for ($i = 0; $i < count($this->ranges); $i++) {
$start = $this->ranges[$i]['range_start'];
$end = $this->ranges[$i]['range_end'];
$pdfRow = new PDFTableRow();
@ -756,7 +756,7 @@ class range extends baseModule {
if (!empty($this->poolsNew)) {
foreach ($this->poolsNew as $poolAttrs) {
$cn = !empty($poolAttrs['cn'][0]) ? $poolAttrs['cn'][0] : '';
$cn = empty($poolAttrs['cn'][0]) ? '' : $poolAttrs['cn'][0];
$peer = '';
if (!empty($poolAttrs['dhcpstatements'])) {
foreach ($poolAttrs['dhcpstatements'] as $statement) {
@ -768,8 +768,8 @@ class range extends baseModule {
if (!empty($poolAttrs['dhcprange'])) {
foreach ($poolAttrs['dhcprange'] as $range) {
$range = explode(' ', $range);
$from = !empty($range[0]) ? $range[0] : '';
$to = !empty($range[1]) ? $range[1] : '';
$from = empty($range[0]) ? '' : $range[0];
$to = empty($range[1]) ? '' : $range[1];
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell($cn . $peer . ': ' . $from . " - " . $to);
$pdfTable->rows[] = $pdfRow;

View file

@ -47,7 +47,7 @@ class sambaDomain extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['smbDomain']);
return $this->get_scope() === 'smbDomain';
}
/**
@ -424,14 +424,14 @@ class sambaDomain extends baseModule {
$this->attributes['sambaSID'][0] = $_POST['sambaSID'];
}
// RID base
if (!get_preg($_POST['RIDbase'], 'digit') && !($_POST['RIDbase'] == '')) {
if (!get_preg($_POST['RIDbase'], 'digit') && ($_POST['RIDbase'] != '')) {
$errors[] = $this->messages['RIDbase'][0];
}
else {
$this->attributes['sambaAlgorithmicRidBase'][0] = $_POST['RIDbase'];
}
// domain name
if (!get_preg($_POST['sambaDomainName'], 'domainname') && !($_POST['sambaDomainName'] == '')) {
if (!get_preg($_POST['sambaDomainName'], 'domainname') && ($_POST['sambaDomainName'] != '')) {
$errors[] = $this->messages['domainName'][0];
}
else {
@ -510,13 +510,11 @@ class sambaDomain extends baseModule {
unset($this->attributes['sambaLockoutThreshold'][0]);
}
}
elseif (is_numeric($_POST['lockoutThreshold']) && ($_POST['lockoutThreshold'] >= 0) && ($_POST['lockoutThreshold'] < 1000)) {
$this->attributes['sambaLockoutThreshold'][0] = $_POST['lockoutThreshold'];
}
else {
if (is_numeric($_POST['lockoutThreshold']) && ($_POST['lockoutThreshold'] >= 0) && ($_POST['lockoutThreshold'] < 1000)) {
$this->attributes['sambaLockoutThreshold'][0] = $_POST['lockoutThreshold'];
}
else {
$errors[] = $this->messages['lockoutThreshold'][0];
}
$errors[] = $this->messages['lockoutThreshold'][0];
}
// Minimum password age
if (!isset($_POST['minPwdAge']) || ($_POST['minPwdAge'] == '')) {
@ -524,13 +522,11 @@ class sambaDomain extends baseModule {
unset($this->attributes['sambaMinPwdAge'][0]);
}
}
elseif (is_numeric($_POST['minPwdAge']) && ($_POST['minPwdAge'] > -2)) {
$this->attributes['sambaMinPwdAge'][0] = $_POST['minPwdAge'];
}
else {
if (is_numeric($_POST['minPwdAge']) && ($_POST['minPwdAge'] > -2)) {
$this->attributes['sambaMinPwdAge'][0] = $_POST['minPwdAge'];
}
else {
$errors[] = $this->messages['pwdAgeMin'][0];
}
$errors[] = $this->messages['pwdAgeMin'][0];
}
// Maximum password age
if (!isset($_POST['maxPwdAge']) || ($_POST['maxPwdAge'] == '')) {
@ -538,16 +534,14 @@ class sambaDomain extends baseModule {
unset($this->attributes['sambaMaxPwdAge'][0]);
}
}
elseif (!is_numeric($_POST['maxPwdAge']) || ($_POST['maxPwdAge'] < -1)) {
$errors[] = $this->messages['pwdAgeMax'][0];
}
elseif (($_POST['maxPwdAge'] > 1) && ($_POST['maxPwdAge'] < $_POST['minPwdAge'])) {
$errors[] = $this->messages['pwdAge_cmp'][0];
}
else {
if (!is_numeric($_POST['maxPwdAge']) || ($_POST['maxPwdAge'] < -1)) {
$errors[] = $this->messages['pwdAgeMax'][0];
}
elseif (($_POST['maxPwdAge'] > 1) && ($_POST['maxPwdAge'] < $_POST['minPwdAge'])) {
$errors[] = $this->messages['pwdAge_cmp'][0];
}
else {
$this->attributes['sambaMaxPwdAge'][0] = $_POST['maxPwdAge'];
}
$this->attributes['sambaMaxPwdAge'][0] = $_POST['maxPwdAge'];
}
// Lockout duration
if (!isset($_POST['lockoutDuration']) || ($_POST['lockoutDuration'] == '')) {
@ -555,13 +549,11 @@ class sambaDomain extends baseModule {
unset($this->attributes['sambaLockoutDuration'][0]);
}
}
elseif (is_numeric($_POST['lockoutDuration']) && ($_POST['lockoutDuration'] > -2)) {
$this->attributes['sambaLockoutDuration'][0] = $_POST['lockoutDuration'];
}
else {
if (is_numeric($_POST['lockoutDuration']) && ($_POST['lockoutDuration'] > -2)) {
$this->attributes['sambaLockoutDuration'][0] = $_POST['lockoutDuration'];
}
else {
$errors[] = $this->messages['lockoutDuration'][0];
}
$errors[] = $this->messages['lockoutDuration'][0];
}
// Reset time after lockout
if (!isset($_POST['lockoutObservationWindow']) || ($_POST['lockoutObservationWindow'] == '')) {
@ -569,13 +561,11 @@ class sambaDomain extends baseModule {
unset($this->attributes['sambaLockoutObservationWindow'][0]);
}
}
elseif (is_numeric($_POST['lockoutObservationWindow']) && ($_POST['lockoutObservationWindow'] > -1)) {
$this->attributes['sambaLockoutObservationWindow'][0] = $_POST['lockoutObservationWindow'];
}
else {
if (is_numeric($_POST['lockoutObservationWindow']) && ($_POST['lockoutObservationWindow'] > -1)) {
$this->attributes['sambaLockoutObservationWindow'][0] = $_POST['lockoutObservationWindow'];
}
else {
$errors[] = $this->messages['lockoutObservationWindow'][0];
}
$errors[] = $this->messages['lockoutObservationWindow'][0];
}
return $errors;
@ -587,7 +577,7 @@ class sambaDomain extends baseModule {
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("sambaDomain", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "sambaDomain";

View file

@ -198,7 +198,7 @@ class sambaGroupMapping extends baseModule {
*/
private function getGID() {
$modules = ['posixGroup', 'rfc2307bisPosixGroup'];
for ($i = 0; $i < sizeof($modules); $i++) {
for ($i = 0; $i < count($modules); $i++) {
if ($this->getAccountContainer()->getAccountModule($modules[$i]) != null) {
$attrs = $this->getAccountContainer()->getAccountModule($modules[$i])->getAttributes();
if (isset($attrs['gidNumber'][0])) {
@ -216,7 +216,7 @@ class sambaGroupMapping extends baseModule {
*/
private function getCn() {
$modules = ['posixGroup', 'groupOfNames', 'groupOfUniqueNames'];
for ($i = 0; $i < sizeof($modules); $i++) {
for ($i = 0; $i < count($modules); $i++) {
if ($this->getAccountContainer()->getAccountModule($modules[$i]) != null) {
$attrs = $this->getAccountContainer()->getAccountModule($modules[$i])->getAttributes();
if (isset($attrs['cn'][0])) {
@ -235,7 +235,7 @@ class sambaGroupMapping extends baseModule {
$return = parent::get_uploadColumns($selectedModules, $type);
$domains = $this->getDomains();
$domainNames = [];
for ($i = 0; $i < sizeof($domains); $i++) $domainNames[] = $domains[$i]->name;
for ($i = 0; $i < count($domains); $i++) $domainNames[] = $domains[$i]->name;
$return[] = [
'name' => 'sambaGroupMapping_domain',
'description' => _('Samba domain name'),
@ -256,16 +256,16 @@ class sambaGroupMapping extends baseModule {
$domains = $this->getDomains();
$nameToSID = [];
// get domain SIDs
for ($i = 0; $i < sizeof($domains); $i++) {
for ($i = 0; $i < count($domains); $i++) {
$nameToSID[$domains[$i]->name] = $domains[$i]->SID;
}
// get domain RID bases
$nameToRIDBase = [];
for ($i = 0; $i < sizeof($domains); $i++) {
for ($i = 0; $i < count($domains); $i++) {
$nameToRIDBase[$domains[$i]->name] = $domains[$i]->RIDbase;
}
$errors = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// group type
if ($rawAccounts[$i][$ids['sambaGroupMapping_groupType']] != "") {
if (in_array($rawAccounts[$i][$ids['sambaGroupMapping_groupType']], $this->sambaGroupTypes)) { // number given
@ -331,7 +331,7 @@ class sambaGroupMapping extends baseModule {
$return = new htmlResponsiveRow();
if (in_array('sambaGroupMapping', $this->attributes['objectClass'])) {
$sambaDomains = $this->getDomains();
if (sizeof($sambaDomains) == 0) {
if (count($sambaDomains) == 0) {
$return->add(new htmlStatusMessage("ERROR", _('No Samba 3 domains found in LDAP! Please create one first.')));
return $return;
}
@ -395,7 +395,7 @@ class sambaGroupMapping extends baseModule {
$this->loadSIDCache();
$memberTable = new htmlTable();
$memberTable->alignment = htmlElement::ALIGN_TOP;
for ($i = 0; $i < sizeof($this->attributes['sambaSIDList']); $i++) {
for ($i = 0; $i < count($this->attributes['sambaSIDList']); $i++) {
$member = $this->attributes['sambaSIDList'][$i];
if (isset($this->sidCache[$member])) {
$member = $this->sidCache[$member];
@ -404,7 +404,7 @@ class sambaGroupMapping extends baseModule {
$delButton = new htmlButton('sambaSIDListDel_' . $i, 'del.svg', true);
$delButton->setTitle(_('Delete'));
$memberTable->addElement($delButton);
if ($i == (sizeof($this->attributes['sambaSIDList']) - 1)) {
if ($i === (count($this->attributes['sambaSIDList']) - 1)) {
$memberTable->addElement($addMemberButton);
$memberTable->addElement($memberHelp);
}
@ -446,7 +446,7 @@ class sambaGroupMapping extends baseModule {
$options = [];
$filter = get_ldap_filter($type->getId());
$entries = searchLDAP($type->getSuffix(), $filter, ['dn', 'cn', 'uid', 'sambaSID']);
$entryCount = sizeof($entries);
$entryCount = count($entries);
for ($i = 0; $i < $entryCount; $i++) {
// require SID
if (empty($entries[$i]['sambasid'][0])) {
@ -454,19 +454,14 @@ class sambaGroupMapping extends baseModule {
}
$sid = $entries[$i]['sambasid'][0];
// get label
if (!empty($this->sidCache[$sid])) {
$label = $this->sidCache[$sid];
}
else {
$label = $sid;
}
$label = empty($this->sidCache[$sid]) ? $sid : $this->sidCache[$sid];
if (empty($this->attributes['sambaSIDList'][0]) || !in_array($sid, $this->attributes['sambaSIDList'])) {
$options[$label] = $sid;
}
}
$size = 20;
if (sizeof($options) < 20) {
$size = sizeof($options);
if (count($options) < 20) {
$size = count($options);
}
$membersSelect = new htmlSelect('members', $options, [], $size);
$membersSelect->setHasDescriptiveElements(true);
@ -515,7 +510,7 @@ class sambaGroupMapping extends baseModule {
function process_members() {
$return = [];
if (isset($_POST['form_subpage_' . static::class . '_attributes_addMembers']) && isset($_POST['members'])) {
for ($i = 0; $i < sizeof($_POST['members']); $i++) {
for ($i = 0; $i < count($_POST['members']); $i++) {
$this->attributes['sambaSIDList'][] = $_POST['members'][$i];
}
}
@ -538,12 +533,7 @@ class sambaGroupMapping extends baseModule {
$this->loadSIDCache();
$members = [];
foreach ($this->attributes['sambaSIDList'] as $member) {
if (!empty($this->sidCache[$member])) {
$members[] = $this->sidCache[$member];
}
else {
$members[] = $member;
}
$members[] = empty($this->sidCache[$member]) ? $member : $this->sidCache[$member];
}
$this->addPDFKeyValue($return, 'sambaSIDList', _('Local members'), implode(', ', $members));
}
@ -578,7 +568,7 @@ class sambaGroupMapping extends baseModule {
if (isset($profile['sambaGroupMapping_sambaDomainName'][0])) {
// get list of domains
$sambaDomains = $this->getDomains();
for ($i = 0; $i < sizeof($sambaDomains); $i++) {
for ($i = 0; $i < count($sambaDomains); $i++) {
if ($sambaDomains[$i]->name == $profile['sambaGroupMapping_sambaDomainName'][0]) {
$this->attributes['sambaSID'][0] = $sambaDomains[$i]->SID . "-0";
break;
@ -604,10 +594,7 @@ class sambaGroupMapping extends baseModule {
* @return boolean true, if page can be displayed
*/
function module_ready() {
if (($this->getGID() == null) || ($this->getGID() == '')) {
return false;
}
return true;
return ($this->getGID() != null) && ($this->getGID() != '');
}
/**
@ -621,10 +608,7 @@ class sambaGroupMapping extends baseModule {
if (!in_array('sambaGroupMapping', $this->attributes['objectClass'])) {
return true;
}
if (!isset($this->attributes['sambaSID']) || ($this->attributes['sambaSID'] == '')) {
return false;
}
return true;
return isset($this->attributes['sambaSID']) && ($this->attributes['sambaSID'] != '');
}
/**
@ -638,13 +622,13 @@ class sambaGroupMapping extends baseModule {
if (isset($_POST['remObjectClass'])) {
// check for users that have this group as primary group
$result = searchLDAPByAttribute('sambaPrimaryGroupSID', $this->attributes['sambaSID'][0], 'sambaSamAccount', ['dn'], ['user', 'host']);
if (sizeof($result) > 0) {
if (count($result) > 0) {
return [$this->messages['primaryGroup'][0]];
}
// remove attributes
$this->attributes['objectClass'] = array_delete(['sambaGroupMapping'], $this->attributes['objectClass']);
$attrKeys = array_keys($this->attributes);
for ($k = 0; $k < sizeof($attrKeys); $k++) {
for ($k = 0; $k < count($attrKeys); $k++) {
if (strpos($attrKeys[$k], 'samba') > -1) {
unset($this->attributes[$attrKeys[$k]]);
}
@ -659,7 +643,7 @@ class sambaGroupMapping extends baseModule {
}
$errors = [];
$sambaDomains = $this->getDomains();
if (sizeof($sambaDomains) == 0) {
if (count($sambaDomains) == 0) {
return [];
}
// Save attributes
@ -688,7 +672,7 @@ class sambaGroupMapping extends baseModule {
// Do a check if special group is unique
if ($this->getAccountContainer()->isNewAccount) {
$result = searchLDAPByAttribute('sambaSID', $SID . "-" . $this->rids[$rids[$i]], 'sambaGroupMapping', ['sambaSID'], ['group']);
if (sizeof($result) > 0) {
if (count($result) > 0) {
$message = $this->messages['sambaSID'][0];
$message[] = $rids[$i];
$errors[] = $message;
@ -700,7 +684,7 @@ class sambaGroupMapping extends baseModule {
$this->attributes['sambaSID'][0] = $SID . "-" . ($this->getGID() * 2 + $RIDbase + 1);
}
// delete local members
foreach ($_POST as $key => $value) {
foreach (array_keys($_POST) as $key) {
if (str_starts_with($key, 'sambaSIDListDel_')) {
$index = substr($key, strlen('sambaSIDListDel_'));
unset($this->attributes['sambaSIDList'][$index]);

View file

@ -37,7 +37,7 @@ use function LAM\ACCOUNTLIST\isPasswordChangeByDefault;
/** terminals server options */
include_once('sambaSamAccount/sambaMungedDial.inc');
include_once(__DIR__ . '/sambaSamAccount/sambaMungedDial.inc');
/**
* Manages the object class "sambaSamAccount" for users and hosts.
@ -623,10 +623,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
return false;
}
}
if (!isset($this->attributes['sambaSID']) || ($this->attributes['sambaSID'] == '')) {
return false;
}
return true;
return isset($this->attributes['sambaSID']) && ($this->attributes['sambaSID'] != '');
}
@ -638,18 +635,8 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
function load_attributes($attr) {
parent::load_attributes($attr);
if (isset($this->attributes['sambaacctflags'][0])) {
if (strpos($this->attributes['sambaacctflags'][0], "N")) {
$this->nopwd = true;
}
else {
$this->nopwd = false;
}
if (strpos($this->attributes['sambaacctflags'][0], "X")) {
$this->noexpire = true;
}
else {
$this->noexpire = false;
}
$this->nopwd = str_contains($this->attributes['sambaacctflags'][0], "N");
$this->noexpire = str_contains($this->attributes['sambaacctflags'][0], "X");
}
if (isset($this->attributes['sambaPwdLastSet'][0]) && ($this->attributes['sambaPwdLastSet'][0] === '0')) {
$this->expirePassword = true;
@ -707,7 +694,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
elseif (isset($_POST['remObjectClass'])) {
$this->attributes['objectClass'] = array_delete(['sambaSamAccount'], $this->attributes['objectClass']);
$attrKeys = array_keys($this->attributes);
for ($k = 0; $k < sizeof($attrKeys); $k++) {
for ($k = 0; $k < count($attrKeys); $k++) {
if (strpos($attrKeys[$k], 'samba') > -1) {
unset($this->attributes[$attrKeys[$k]]);
}
@ -724,7 +711,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
$this->getAccountContainer()->replaceWildcardsInPOST($this->getWildcardTargetAttributeNames());
$errors = [];
$sambaDomains = $this->getDomains();
if (sizeof($sambaDomains) == 0) {
if (count($sambaDomains) == 0) {
return [];
}
$unixAttributes = $this->getAccountContainer()->getAccountModule('posixAccount')->getAttributes();
@ -771,12 +758,12 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
// Expand string to fixed length
$flag = str_pad($flag, 12);
// End character
$flag = $flag . "]";
$flag .= "]";
$this->attributes['sambaacctflags'][0] = $flag;
// display name
$this->attributes['displayName'][0] = $_POST['displayName'];
if (!($this->attributes['displayName'][0] == '') && !(get_preg($this->attributes['displayName'][0], 'realname'))) {
if (($this->attributes['displayName'][0] != '') && !get_preg($this->attributes['displayName'][0], 'realname')) {
$errors[] = $this->messages['displayName'][1];
}
@ -802,12 +789,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
}
}
if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideHomeDrive')) {
if ($_POST['sambaHomeDrive'] == "-") {
$this->attributes['sambaHomeDrive'][0] = '';
}
else {
$this->attributes['sambaHomeDrive'][0] = $_POST['sambaHomeDrive'];
}
$this->attributes['sambaHomeDrive'][0] = ($_POST['sambaHomeDrive'] === "-") ? '' : $_POST['sambaHomeDrive'];
}
if (!$this->isBooleanConfigOptionSet('sambaSamAccount_hideLogonScript')) {
$this->attributes['sambaLogonScript'][0] = $_POST['sambaLogonScript'];
@ -823,7 +805,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
if ($this->attributes['sambaProfilePath'][0] != $_POST['sambaProfilePath']) {
$errors[] = $this->messages['profilePath'][1];
}
if (!($this->attributes['sambaProfilePath'][0] == '') &&
if (($this->attributes['sambaProfilePath'][0] != '') &&
!(get_preg($this->attributes['sambaProfilePath'][0], 'UNC') xor get_preg($this->attributes['sambaProfilePath'][0], 'homeDirectory'))) {
$errors[] = $this->messages['profilePath'][0];
}
@ -844,14 +826,13 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
$this->attributes['sambaPrimaryGroupSID'][0] = $groups[$gidnumber];
}
}
$specialRids = array_flip($this->userRids);
// set special RID if selected
if (in_array($_POST['sambaSID'], $specialRids)) {
$this->attributes['sambaSID'][0] = $SID . '-' . $this->userRids[$_POST['sambaSID']];
}
// standard RID
else if ($_POST['sambaSID'] == "-") {
elseif ($_POST['sambaSID'] == "-") {
$rid = '';
if (isset($this->attributes['sambaSID'][0])) {
$rid = substr($this->attributes['sambaSID'][0], strrpos($this->attributes['sambaSID'][0], '-') + 1, strlen($this->attributes['sambaSID'][0]));
@ -864,17 +845,11 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
}
}
}
else { // host
if (!isset($this->attributes['sambaSID'][0])) {
$this->attributes['sambaSID'][0] = $SID . "-" . (($unixAttributes['uidNumber'][0] * 2) + $RIDbase);
}
}
if (isset($_POST['forcePasswordChangeOption'])) {
$this->expirePassword = true;
}
else {
$this->expirePassword = false;
elseif (!isset($this->attributes['sambaSID'][0])) {
// host
$this->attributes['sambaSID'][0] = $SID . "-" . (($unixAttributes['uidNumber'][0] * 2) + $RIDbase);
}
$this->expirePassword = isset($_POST['forcePasswordChangeOption']);
return $errors;
}
@ -893,7 +868,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
$temp = str_replace(' ', '', $this->attributes['sambaUserWorkstations'][0]);
$workstations = explode(',', $temp);
for ($i = 0; $i < count($workstations); $i++) {
if ($workstations[$i] == '') {
if ($workstations[$i] === '') {
unset($workstations[$i]);
}
}
@ -918,7 +893,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
$temp = str_replace(' ', '', $this->attributes['sambaUserWorkstations'][0]);
$workstations = explode(',', $temp);
for ($i = 0; $i < count($workstations); $i++) {
if ($workstations[$i] == '') {
if ($workstations[$i] === '') {
unset($workstations[$i]);
}
}
@ -927,7 +902,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
$workstations = array_delete($_POST['workstations_1'], $workstations);
// Recreate workstation string
unset($this->attributes['sambaUserWorkstations'][0]);
if (sizeof($workstations) > 0) {
if (count($workstations) > 0) {
$this->attributes['sambaUserWorkstations'][0] = $workstations[0];
for ($i = 1; $i < count($workstations); $i++) {
$this->attributes['sambaUserWorkstations'][0] = $this->attributes['sambaUserWorkstations'][0] . "," . $workstations[$i];
@ -961,7 +936,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
$byte['hi'] = substr($part, 0, 4);
$byte['low'] = substr($part, 4, 4);
$hex = $bitstring2hex[$byte['hi']] . $bitstring2hex[$byte['low']];
$logonHoursNew = $logonHoursNew . $hex;
$logonHoursNew .= $hex;
}
$this->attributes['sambaLogonHours'][0] = $logonHoursNew;
return [];
@ -977,7 +952,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
// find button name
$buttonName = '';
$postKeys = array_keys($_POST);
for ($i = 0; $i < sizeof($postKeys); $i++) {
for ($i = 0; $i < count($postKeys); $i++) {
if (str_contains($postKeys[$i], 'form_subpage_sambaSamAccount_attributes_')) {
$buttonName = $postKeys[$i];
}
@ -990,7 +965,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
if (str_contains($buttonName, 'sambaKickoffTime')) {
$attr = 'sambaKickoffTime';
}
if ($attr == '') {
if ($attr === '') {
return [];
}
// determine action
@ -1083,10 +1058,8 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
if ($this->isExtensionEnabled()) {
$this->getAccountContainer()->replaceWildcardsInArray($this->getWildcardTargetAttributeNames(), $this->attributes);
$unixAttributes = $this->getAccountContainer()->getAccountModule('posixAccount')->getAttributes();
if ($this->get_scope() == "host") {
if (!str_ends_with($unixAttributes['uid'][0], '$')) {
$return->add(new htmlStatusMessage("ERROR", _('Host name must end with $!'), _('Please check your settings on the Unix page!')));
}
if (($this->get_scope() == "host") && !str_ends_with($unixAttributes['uid'][0], '$')) {
$return->add(new htmlStatusMessage("ERROR", _('Host name must end with $!'), _('Please check your settings on the Unix page!')));
}
$personalAttributes = [];
if ($this->getAccountContainer()->getAccountModule('inetOrgPerson') != null) {
@ -1094,7 +1067,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
}
// Get Domain SID from user SID
$sambaDomains = $this->getDomains();
if (sizeof($sambaDomains) == 0) {
if (count($sambaDomains) == 0) {
$return->add(new htmlStatusMessage("ERROR", _('No Samba 3 domains found in LDAP! Please create one first.')));
return $return;
}
@ -1122,7 +1095,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
if (!empty($this->attributes['displayName'][0])) {
$displayName = $this->attributes['displayName'][0];
}
else if ($this->getAccountContainer()->isNewAccount && empty($this->attributes['displayName'][0])) {
elseif ($this->getAccountContainer()->isNewAccount && empty($this->attributes['displayName'][0])) {
if (isset($personalAttributes['givenName'][0]) && $personalAttributes['givenName'][0] && isset($personalAttributes['sn'][0]) && $personalAttributes['sn'][0]) {
$displayName = $personalAttributes['givenName'][0] . " " . $personalAttributes['sn'][0];
}
@ -1190,12 +1163,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
for ($i = 90; $i > 67; $i--) {
$drives[] = chr($i) . ':';
}
if (isset($this->attributes['sambaHomeDrive'][0])) {
$selected = [$this->attributes['sambaHomeDrive'][0]];
}
else {
$selected = ['-'];
}
$selected = isset($this->attributes['sambaHomeDrive'][0]) ? [$this->attributes['sambaHomeDrive'][0]] : ['-'];
$return->add(new htmlResponsiveSelect('sambaHomeDrive', $drives, $selected, _('Home drive'), 'homeDrive'));
}
// home path
@ -1215,12 +1183,12 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
$return->addLabel(new htmlOutputText(_('Profile path')));
$sambaProfilePathGroup = new htmlGroup();
$sambaProfilePathGroup->addElement(new htmlInputField('sambaProfilePath', $sambaProfilePath));
if (($_SESSION['config']->get_scriptPath() != null) && ($_SESSION['config']->get_scriptPath() != '')) {
if (get_preg($sambaProfilePath, 'homeDirectory')) {
$sambaProfilePathButton = new htmlAccountPageButton(static::class, 'profilePath', 'manage', '../graphics/folder.svg', true);
$sambaProfilePathButton->setTitle(_('Manage profile directory'));
$sambaProfilePathGroup->addElement($sambaProfilePathButton);
}
if (($_SESSION['config']->get_scriptPath() != null)
&& ($_SESSION['config']->get_scriptPath() != '')
&& get_preg($sambaProfilePath, 'homeDirectory')) {
$sambaProfilePathButton = new htmlAccountPageButton(static::class, 'profilePath', 'manage', '../graphics/folder.svg', true);
$sambaProfilePathButton->setTitle(_('Manage profile directory'));
$sambaProfilePathGroup->addElement($sambaProfilePathButton);
}
$sambaProfilePathGroup->addElement(new htmlHelpLink('profilePath'));
$return->addField($sambaProfilePathGroup);
@ -1265,12 +1233,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
if (isset($this->attributes['sambaSID'][0]) && ($this->attributes['sambaSID'][0] != '')) {
$rid = substr($this->attributes['sambaSID'][0], strrpos($this->attributes['sambaSID'][0], '-') + 1, strlen($this->attributes['sambaSID'][0]));
$specialRids = array_flip($this->userRids);
if (in_array($rid, $this->userRids)) {
$selected = [$specialRids[$rid]];
}
else {
$selected = ['-'];
}
$selected = in_array($rid, $this->userRids) ? [$specialRids[$rid]] : ['-'];
}
else {
$selected[] = "-";
@ -1421,10 +1384,10 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
for ($i = 0; $i < 24 * 7; $i++) {
$hr = $i + $timeZone;
if ($hr < 0) {
$hr = $hr + 24 * 7;
$hr += 24 * 7;
}
elseif ($hr >= 24 * 7) {
$hr = $hr - 24 * 7;
$hr -= 24 * 7;
}
$checkbox = new htmlInputCheckbox('lh_' . $hr, $hour[$hr]);
$boxes[$i % 24][floor($i / 24)] = $checkbox;
@ -1608,7 +1571,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
$return->addVerticalSpacer('2rem');
// get list of remote servers
$remoteServers = $_SESSION['config']->getConfiguredScriptServers();
for ($i = 0; $i < sizeof($remoteServers); $i++) {
for ($i = 0; $i < count($remoteServers); $i++) {
$remoteServer = $remoteServers[$i];
$label = $remoteServer->getLabel();
$remote = new Remote();
@ -1632,7 +1595,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
// remote command results
if (!empty($result)) {
$returnValue = trim($result);
if ($returnValue == 'ok') {
if ($returnValue === 'ok') {
$return->addLabel(new htmlOutputText($label));
$editGroup = new htmlGroup();
$editGroup->addElement(new htmlImage('../../graphics/pass.svg', 16, 16));
@ -1640,7 +1603,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
$editGroup->addElement(new htmlAccountPageButton(static::class, 'homedir', 'delete_' . $i, _('Delete')));
$return->addField($editGroup);
}
elseif ($returnValue == 'missing') {
elseif ($returnValue === 'missing') {
$return->addLabel(new htmlOutputText($label));
$editGroup = new htmlGroup();
$editGroup->addElement(new htmlImage('../../graphics/del.svg', 16, 16));
@ -1648,12 +1611,12 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
$editGroup->addElement(new htmlAccountPageButton(static::class, 'homedir', 'create_' . $i, _('Create')));
$return->addField($editGroup);
}
elseif (trim($returnValue) != '') {
elseif (trim($returnValue) !== '') {
$messageParams = explode(",", $returnValue);
if (isset($messageParams[2])) {
$message = new htmlStatusMessage($messageParams[0], htmlspecialchars($messageParams[1]), htmlspecialchars($messageParams[2]));
}
elseif (($messageParams[0] == 'ERROR') || ($messageParams[0] == 'WARN') || ($messageParams[0] == 'INFO')) {
elseif (($messageParams[0] === 'ERROR') || ($messageParams[0] === 'WARN') || ($messageParams[0] === 'INFO')) {
$message = new htmlStatusMessage($messageParams[0], htmlspecialchars($messageParams[1]));
}
else {
@ -1684,7 +1647,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
}
// get list of remote servers
$remoteServers = $_SESSION['config']->getConfiguredScriptServers();
for ($i = 0; $i < sizeof($remoteServers); $i++) {
for ($i = 0; $i < count($remoteServers); $i++) {
$remoteServer = $remoteServers[$i];
if (isset($_POST['form_subpage_' . static::class . '_homedir_create_' . $i])) {
$remote = new Remote();
@ -1711,7 +1674,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
// remote command results
if (!empty($result)) {
$singleresult = explode(",", $result);
if (($singleresult[0] == 'ERROR') || ($singleresult[0] == 'WARN') || ($singleresult[0] == 'INFO')) {
if (($singleresult[0] === 'ERROR') || ($singleresult[0] === 'WARN') || ($singleresult[0] === 'INFO')) {
$return[] = $singleresult;
}
}
@ -1740,7 +1703,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
// remote command results
if (!empty($result)) {
$singleresult = explode(",", $result);
if (($singleresult[0] == 'ERROR') || ($singleresult[0] == 'WARN') || ($singleresult[0] == 'INFO')) {
if (($singleresult[0] === 'ERROR') || ($singleresult[0] === 'WARN') || ($singleresult[0] === 'INFO')) {
$return[] = $singleresult;
}
}
@ -1850,10 +1813,10 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
// profile mappings in meta data
parent::load_profile($profile);
// add extension
if (isset($profile['sambaSamAccount_addExt'][0]) && ($profile['sambaSamAccount_addExt'][0] == "true")) {
if (!in_array('sambaSamAccount', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'sambaSamAccount';
}
if (isset($profile['sambaSamAccount_addExt'][0])
&& ($profile['sambaSamAccount_addExt'][0] == "true")
&& !in_array('sambaSamAccount', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'sambaSamAccount';
}
// use no password
if (isset($profile['sambaSamAccount_sambaAcctFlagsN'][0]) && ($profile['sambaSamAccount_sambaAcctFlagsN'][0] == "true")) {
@ -1891,42 +1854,42 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
$this->attributes['sambaKickoffTime'][0] = $date->format('U');
}
// domain -> change SID
if (isset($this->attributes['sambaSID'][0])) {
if (isset($profile['sambaSamAccount_sambaDomainName'][0]) && ($profile['sambaSamAccount_sambaDomainName'][0] != "")) {
$domains = $this->getDomains();
$domSID = '';
// find domain SID
for ($i = 0; $i < sizeof($domains); $i++) {
if ($domains[$i]->name == $profile['sambaSamAccount_sambaDomainName'][0]) {
$domSID = $domains[$i]->SID;
break;
}
}
// replace domain part of SID
if ($domSID != '') {
$SID = $this->attributes['sambaSID'][0];
$rid = substr($SID, strrpos($SID, '-') + 1);
$SID = $domSID . '-' . $rid;
$this->attributes['sambaSID'][0] = $SID;
if (isset($this->attributes['sambaSID'][0])
&& isset($profile['sambaSamAccount_sambaDomainName'][0])
&& ($profile['sambaSamAccount_sambaDomainName'][0] != "")) {
$domains = $this->getDomains();
$domSID = '';
// find domain SID
for ($i = 0; $i < count($domains); $i++) {
if ($domains[$i]->name == $profile['sambaSamAccount_sambaDomainName'][0]) {
$domSID = $domains[$i]->SID;
break;
}
}
// replace domain part of SID
if ($domSID != '') {
$SID = $this->attributes['sambaSID'][0];
$rid = substr($SID, strrpos($SID, '-') + 1);
$SID = $domSID . '-' . $rid;
$this->attributes['sambaSID'][0] = $SID;
}
}
// primary group
if (isset($profile['sambaSamAccount_sambaDomainName'][0])) {
$domains = $this->getDomains();
$domSID = '';
// find domain SID
for ($i = 0; $i < sizeof($domains); $i++) {
for ($i = 0; $i < count($domains); $i++) {
if ($domains[$i]->name == $profile['sambaSamAccount_sambaDomainName'][0]) {
$domSID = $domains[$i]->SID;
break;
}
}
if ($domSID != '') {
// set primary group if selected
if (isset($profile['sambaSamAccount_group'][0]) && ($profile['sambaSamAccount_group'][0] != "-")) {
$this->attributes['sambaPrimaryGroupSID'][0] = $domSID . "-" . $profile['sambaSamAccount_group'][0];
}
// set primary group if selected
if (($domSID != '')
&& isset($profile['sambaSamAccount_group'][0])
&& ($profile['sambaSamAccount_group'][0] != "-")) {
$this->attributes['sambaPrimaryGroupSID'][0] = $domSID . "-" . $profile['sambaSamAccount_group'][0];
}
}
}
@ -2075,7 +2038,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
// get list of Unix groups and their sambaSID + gidNumber
$groupList = searchLDAPByFilter('objectClass=posixGroup', ['cn', 'sambaSID', 'gidNumber'], ['group']);
$groups_cn = [];
for ($i = 0; $i < sizeof($groupList); $i++) {
for ($i = 0; $i < count($groupList); $i++) {
if (isset($groupList[$i]['sambasid'][0])) {
$groups_cn[$groupList[$i]['cn'][0]]['SID'] = $groupList[$i]['sambasid'][0];
}
@ -2084,7 +2047,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
}
}
if ($this->get_scope() == 'user') {
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
if (!in_array("sambaSamAccount", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "sambaSamAccount";
}
@ -2160,16 +2123,16 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
// set flags
$flags = "[";
if ($flag_deactivated) {
$flags = $flags . "D";
$flags .= "D";
}
if (!$flag_expire) {
$flags = $flags . "X";
$flags .= "X";
}
$flags = $flags . "U";
$flags .= "U";
// Expand string to fixed length
$flags = str_pad($flags, 12);
// End character
$flags = $flags . "]";
$flags .= "]";
$partialAccounts[$i]['sambaacctflags'] = $flags;
// expiration date
if ($rawAccounts[$i][$ids['sambaSamAccount_expireDate']] != "") {
@ -2209,7 +2172,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
'workstations', $this->messages['workstations'][1], $errors);
// domain
$domIndex = -1;
for ($d = 0; $d < sizeof($domains); $d++) {
for ($d = 0; $d < count($domains); $d++) {
if ($domains[$d]->name == $rawAccounts[$i][$ids['sambaSamAccount_domain']]) {
$domIndex = $d;
break;
@ -2275,13 +2238,13 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
}
}
else { // hosts
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
if (!in_array("sambaSamAccount", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "sambaSamAccount";
}
// domain
$domIndex = -1;
for ($d = 0; $d < sizeof($domains); $d++) {
for ($d = 0; $d < count($domains); $d++) {
if ($domains[$d]->name == $rawAccounts[$i][$ids['sambaSamAccount_domain']]) {
$domIndex = $d;
break;
@ -2401,7 +2364,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
*
* Calling this method does not require the existence of an enclosing {@link accountContainer}.
*
* @param string $fields input fields
* @param array $fields input fields
* @param array $attributes LDAP attributes
* @param boolean $passwordChangeOnly indicates that the user is only allowed to change his password and no LDAP content is readable
* @param array $readOnlyFields list of read-only fields
@ -2412,37 +2375,35 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
if (!isset($attributes['objectClass']) || !in_array_ignore_case('sambaSamAccount', $attributes['objectClass'])) {
return $return;
}
if (in_array('password', $fields)) {
if (isset($_POST['sambaSamAccount_password']) && ($_POST['sambaSamAccount_password'] != '')) {
if ($_POST['sambaSamAccount_password'] != $_POST['sambaSamAccount_password2']) {
$return['messages'][] = $this->messages['sambaNTPassword'][0];
if (in_array('password', $fields)
&& isset($_POST['sambaSamAccount_password'])
&& ($_POST['sambaSamAccount_password'] != '')) {
if ($_POST['sambaSamAccount_password'] != $_POST['sambaSamAccount_password2']) {
$return['messages'][] = $this->messages['sambaNTPassword'][0];
}
elseif (!get_preg($_POST['sambaSamAccount_password'], 'password')) {
$return['messages'][] = $this->messages['sambaNTPassword'][1];
}
else {
$userName = empty($attributes['uid'][0]) ? null : $attributes['uid'][0];
$additionalAttrs = [];
if (!empty($attributes['sn'][0])) {
$additionalAttrs[] = $attributes['sn'][0];
}
if (!empty($attributes['givenName'][0])) {
$additionalAttrs[] = $attributes['givenName'][0];
}
$pwdPolicyResult = checkPasswordStrength($_POST['sambaSamAccount_password'], $userName, $additionalAttrs);
if ($pwdPolicyResult === true) {
$return['mod']['sambaNTPassword'][0] = ntPassword($_POST['sambaSamAccount_password']);
$return['info']['sambaUserPasswordClearText'][0] = $_POST['sambaSamAccount_password'];
$this->doSelfServicePasswordHistoryAndMinAge($attributes, $return);
if (array_key_exists('sambaPwdLastSet', $attributes)) {
$return['mod']['sambaPwdLastSet'][0] = time();
}
}
else {
if (!get_preg($_POST['sambaSamAccount_password'], 'password')) {
$return['messages'][] = $this->messages['sambaNTPassword'][1];
}
else {
$userName = empty($attributes['uid'][0]) ? null : $attributes['uid'][0];
$additionalAttrs = [];
if (!empty($attributes['sn'][0])) {
$additionalAttrs[] = $attributes['sn'][0];
}
if (!empty($attributes['givenName'][0])) {
$additionalAttrs[] = $attributes['givenName'][0];
}
$pwdPolicyResult = checkPasswordStrength($_POST['sambaSamAccount_password'], $userName, $additionalAttrs);
if ($pwdPolicyResult === true) {
$return['mod']['sambaNTPassword'][0] = ntPassword($_POST['sambaSamAccount_password']);
$return['info']['sambaUserPasswordClearText'][0] = $_POST['sambaSamAccount_password'];
$this->doSelfServicePasswordHistoryAndMinAge($attributes, $return);
if (array_key_exists('sambaPwdLastSet', $attributes)) {
$return['mod']['sambaPwdLastSet'][0] = time();
}
}
else {
$return['messages'][] = ['ERROR', $pwdPolicyResult];
}
}
$return['messages'][] = ['ERROR', $pwdPolicyResult];
}
}
}
@ -2450,23 +2411,21 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
if ($_POST['posixAccount_password'] != $_POST['posixAccount_password2']) {
return $return;
}
elseif (!get_preg($_POST['posixAccount_password'], 'password')) {
return $return;
}
else {
if (!get_preg($_POST['posixAccount_password'], 'password')) {
return $return;
$setPassword = false;
// sync password
if (in_array('syncNTPassword', $fields)) {
$return['mod']['sambaNTPassword'][0] = ntPassword($_POST['posixAccount_password']);
$setPassword = true;
}
else {
$setPassword = false;
// sync password
if (in_array('syncNTPassword', $fields)) {
$return['mod']['sambaNTPassword'][0] = ntPassword($_POST['posixAccount_password']);
$setPassword = true;
}
if ($setPassword) {
$return['info']['sambaUserPasswordClearText'][0] = $_POST['posixAccount_password'];
$this->doSelfServicePasswordHistoryAndMinAge($attributes, $return);
if (in_array('syncSambaPwdLastSet', $fields)) {
$return['mod']['sambaPwdLastSet'][0] = time();
}
if ($setPassword) {
$return['info']['sambaUserPasswordClearText'][0] = $_POST['posixAccount_password'];
$this->doSelfServicePasswordHistoryAndMinAge($attributes, $return);
if (in_array('syncSambaPwdLastSet', $fields)) {
$return['mod']['sambaPwdLastSet'][0] = time();
}
}
}
@ -2492,32 +2451,30 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
if (sambaSamAccount::oldPasswordUsed($return['info']['sambaUserPasswordClearText'][0], $attributes, $sambaDomain)) {
$return['messages'][] = ['ERROR', _('You are reusing an old password. Please choose a different password.')];
}
else {
elseif (sambaSamAccount::isPasswordHistoryEnabled($this->selfServiceSettings->moduleSettings)) {
// update password history
if (sambaSamAccount::isPasswordHistoryEnabled($this->selfServiceSettings->moduleSettings)) {
$sambaPasswordHistory = empty($attributes['sambaPasswordHistory']) ? [] : $attributes['sambaPasswordHistory'];
while (sizeof($sambaPasswordHistory) > ($sambaDomain->pwdHistoryLength - 1)) {
if (empty($this->selfServiceSettings->moduleSettings['sambaSamAccount_history'][0]) || ($this->selfServiceSettings->moduleSettings['sambaSamAccount_history'][0] == 'yes_deleteLast')) {
array_pop($sambaPasswordHistory);
}
else {
array_shift($sambaPasswordHistory);
}
}
$sambaPasswordHistory = empty($attributes['sambaPasswordHistory']) ? [] : $attributes['sambaPasswordHistory'];
while (count($sambaPasswordHistory) > ($sambaDomain->pwdHistoryLength - 1)) {
if (empty($this->selfServiceSettings->moduleSettings['sambaSamAccount_history'][0]) || ($this->selfServiceSettings->moduleSettings['sambaSamAccount_history'][0] == 'yes_deleteLast')) {
array_unshift($sambaPasswordHistory, sambaSamAccount::createHistoryEntry($return['info']['sambaUserPasswordClearText'][0]));
array_pop($sambaPasswordHistory);
}
else {
$sambaPasswordHistory[] = sambaSamAccount::createHistoryEntry($return['info']['sambaUserPasswordClearText'][0]);
}
$sambaPasswordHistory = array_values($sambaPasswordHistory);
if (empty($attributes['sambaPasswordHistory'])) {
$return['add']['sambaPasswordHistory'] = $sambaPasswordHistory;
}
else {
$return['mod']['sambaPasswordHistory'] = $sambaPasswordHistory;
array_shift($sambaPasswordHistory);
}
}
if (empty($this->selfServiceSettings->moduleSettings['sambaSamAccount_history'][0]) || ($this->selfServiceSettings->moduleSettings['sambaSamAccount_history'][0] == 'yes_deleteLast')) {
array_unshift($sambaPasswordHistory, sambaSamAccount::createHistoryEntry($return['info']['sambaUserPasswordClearText'][0]));
}
else {
$sambaPasswordHistory[] = sambaSamAccount::createHistoryEntry($return['info']['sambaUserPasswordClearText'][0]);
}
$sambaPasswordHistory = array_values($sambaPasswordHistory);
if (empty($attributes['sambaPasswordHistory'])) {
$return['add']['sambaPasswordHistory'] = $sambaPasswordHistory;
}
else {
$return['mod']['sambaPasswordHistory'] = $sambaPasswordHistory;
}
}
}
// check min age
@ -2590,7 +2547,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
else {
$this->attributes['sambaPasswordHistory'] = [];
}
while (sizeof($this->attributes['sambaPasswordHistory']) > ($historyLength - 1)) {
while (count($this->attributes['sambaPasswordHistory']) > ($historyLength - 1)) {
if (empty($this->moduleSettings['sambaSamAccount_history'][0]) || ($this->moduleSettings['sambaSamAccount_history'][0] == 'yes_deleteLast')) {
array_pop($this->attributes['sambaPasswordHistory']);
}
@ -2640,7 +2597,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
public function getUserDomain($attributes, $server = null, $suffix = null) {
$attributes = array_change_key_case($attributes);
$sambaDomains = $this->getDomains($server, $suffix);
if (sizeof($sambaDomains) > 0) {
if (count($sambaDomains) > 0) {
$domainSID = null;
if (isset($attributes['sambasid'][0]) && $attributes['sambasid'][0] != '') {
$domainSID = substr($attributes['sambasid'][0], 0, strrpos($attributes['sambasid'][0], "-"));
@ -2669,7 +2626,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
*/
private function getGroupName($groupID) {
$results = searchLDAPByAttribute('gidNumber', $groupID, 'posixGroup', ['cn'], ['group']);
if ((sizeof($results) > 0) && isset($results[0]['cn'][0])) {
if ((count($results) > 0) && isset($results[0]['cn'][0])) {
return $results[0]['cn'][0];
}
return null;
@ -2682,7 +2639,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
* @param String $selectedDomain selected domain name
*/
private function getPasswordMustChangeTime($domains, $selectedDomain) {
if (is_array($selectedDomain) && (sizeof($selectedDomain) > 0)) {
if (is_array($selectedDomain) && ($selectedDomain !== [])) {
$selectedDomain = $selectedDomain[0];
}
$return = '-';
@ -2694,7 +2651,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
if (!isset($this->attributes['sambaPwdLastSet'][0])) {
return $return;
}
for ($i = 0; $i < sizeof($domains); $i++) {
for ($i = 0; $i < count($domains); $i++) {
if ($domains[$i]->name == $selectedDomain) {
// check if a domain policy is set
if (!isset($domains[$i]->maxPwdAge) || ($domains[$i]->maxPwdAge < 0)) {
@ -2716,7 +2673,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
* @param String $selectedDomain selected domain name
*/
private function getPasswordCanChangeTime($domains, $selectedDomain) {
if (is_array($selectedDomain) && (sizeof($selectedDomain) > 0)) {
if (is_array($selectedDomain) && ($selectedDomain !== [])) {
$selectedDomain = $selectedDomain[0];
}
$return = '-';
@ -2724,7 +2681,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
if (!isset($this->attributes['sambaPwdLastSet'][0])) {
return $return;
}
for ($i = 0; $i < sizeof($domains); $i++) {
for ($i = 0; $i < count($domains); $i++) {
if ($domains[$i]->name == $selectedDomain) {
// check if a domain policy is set
if (!isset($domains[$i]->minPwdAge) || ($domains[$i]->minPwdAge < 0)) {
@ -2749,7 +2706,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
return $this->cachedHostList;
}
$this->cachedHostList = searchLDAPByAttribute('uid', '*', 'sambaSamAccount', ['uid'], ['host']);
for ($i = 0; $i < sizeof($this->cachedHostList); $i++) {
for ($i = 0; $i < count($this->cachedHostList); $i++) {
$this->cachedHostList[$i] = $this->cachedHostList[$i]['uid'][0];
}
return $this->cachedHostList;
@ -2766,7 +2723,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
}
$this->cachedGroupSIDList = [];
$result = searchLDAPByAttribute('sambaSID', '*', 'sambaGroupMapping', ['gidNumber', 'sambaSID'], ['group']);
for ($i = 0; $i < sizeof($result); $i++) {
for ($i = 0; $i < count($result); $i++) {
if (isset($result[$i]['gidnumber'][0])) {
$this->cachedGroupSIDList[$result[$i]['gidnumber'][0]] = $result[$i]['sambasid'][0];
}
@ -2854,12 +2811,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
*/
public function deactivate(array &$attributes) {
if (!isset($attributes['sambaacctflags'][0])) {
if ($this->get_scope() === 'host') {
$attributes['sambaacctflags'][0] = '[W ]';
}
else {
$attributes['sambaacctflags'][0] = '[ XU ]';
}
$attributes['sambaacctflags'][0] = ($this->get_scope() === 'host') ? '[W ]' : '[ XU ]';
}
$flags = $attributes['sambaacctflags'][0];
if (!str_contains($flags, 'D')) {
@ -2875,12 +2827,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
*/
public function activate(array &$attributes) {
if (!isset($attributes['sambaacctflags'][0])) {
if ($this->get_scope() === 'host') {
$attributes['sambaacctflags'][0] = '[W ]';
}
else {
$attributes['sambaacctflags'][0] = '[ XU ]';
}
$attributes['sambaacctflags'][0] = ($this->get_scope() === 'host') ? '[W ]' : '[ XU ]';
}
$attributes['sambaacctflags'][0] = str_replace('D', ' ', $attributes['sambaacctflags'][0]);
}
@ -2926,7 +2873,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
$hash = substr($historyEntry, 32, 32);
$md4hash = ntPassword($password);
$md5hash = md5($salt . hex2bin($md4hash));
return strtolower($md5hash) == strtolower($hash);
return strtolower($md5hash) === strtolower($hash);
}
/**
@ -2977,14 +2924,13 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
*/
public function getPasswordQuickChangeChanges(string $password): array {
$attrs = [];
if (isset($_POST['unlockAccountSamba']) && isset($this->attributes['sambaacctflags'][0])) {
if ((str_contains($this->attributes['sambaacctflags'][0], 'L'))
|| (str_contains($this->attributes['sambaacctflags'][0], 'D'))) {
$sambaFlags = $this->attributes['sambaacctflags'][0];
$sambaFlags = str_replace('L', ' ', $sambaFlags);
$sambaFlags = str_replace('D', ' ', $sambaFlags);
$attrs['sambaacctflags'][0] = $sambaFlags;
}
if (isset($_POST['unlockAccountSamba'])
&& isset($this->attributes['sambaacctflags'][0])
&& ((str_contains($this->attributes['sambaacctflags'][0], 'L')) || (str_contains($this->attributes['sambaacctflags'][0], 'D')))) {
$sambaFlags = $this->attributes['sambaacctflags'][0];
$sambaFlags = str_replace('L', ' ', $sambaFlags);
$sambaFlags = str_replace('D', ' ', $sambaFlags);
$attrs['sambaacctflags'][0] = $sambaFlags;
}
if (isset($_POST['syncSambaNT'])) {
$attrs['sambaNTPassword'][0] = ntPassword($password);
@ -3003,7 +2949,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
else {
$attrs['sambaPasswordHistory'] = [];
}
while (sizeof($attrs['sambaPasswordHistory']) > ($domain->pwdHistoryLength - 1)) {
while (count($attrs['sambaPasswordHistory']) > ($domain->pwdHistoryLength - 1)) {
array_pop($attrs['sambaPasswordHistory']);
}
array_unshift($attrs['sambaPasswordHistory'], self::createHistoryEntry($password));
@ -3120,7 +3066,7 @@ class sambaSamAccount extends baseModule implements passwordService, AccountStat
* @inheritDoc
*/
public function getListFilterFunction(string $attributeName): ?callable {
if ($attributeName == 'sambakickofftime') {
if ($attributeName === 'sambakickofftime') {
return function(?array $values, ?string $filterValue): bool {
$regex = str_replace(['*'], ['.*'], $filterValue);
$regex = '/' . $regex . '/i';

View file

@ -262,7 +262,7 @@ class sambaMungedDial {
}
/* Decode parameters */
while ($ctxField != "") {
while ($ctxField !== "") {
/* Read value lengths */
$ctxParmNameLength = ord($ctxField[0]) + 16 * ord($ctxField[1]);
@ -324,15 +324,7 @@ class sambaMungedDial {
/** Gets Terminal-Server-Login value: enabled/disabled */
function getTsLogin() {
$flags = ord(substr($this->ctx['CtxCfgFlags1'], 5, 1));
if ($flags & 1) {
$result = false;
}
else {
$result = true;
}
return $result;
return ($flags & 1) === 0;
}
/** Sets Terminal-Server-Login value: enabled/disabled */
@ -352,14 +344,7 @@ class sambaMungedDial {
/** gets Broken-Connection value: disconnect/reset */
function getBrokenConn() {
$flags = ord(substr($this->ctx['CtxCfgFlags1'], 5, 1));
if ($flags & 4) {
$result = "1";
}
else {
$result = "0";
}
return $result;
return (($flags & 4) !== 0) ? "1" : "0";
}
/** sets Broken-Connection value: disconnect/reset */
@ -379,14 +364,7 @@ class sambaMungedDial {
/** gets Reconnection value: from any client/from previous client only */
function getReConn() {
$flags = ord(substr($this->ctx['CtxCfgFlags1'], 5, 1));
if ($flags & 2) {
$result = "1";
}
else {
$result = "0";
}
return $result;
return (($flags & 2) !== 0) ? "1" : "0";
}
/** sets Reconnection value: from any client/from previous client only */
@ -405,24 +383,12 @@ class sambaMungedDial {
/** gets Inherit-config-from-client value: enabled/disabled */
function getInheritMode() {
if (substr($this->ctx['CtxCfgFlags1'], 6, 1) == "1") {
$result = true;
}
else {
$result = false;
}
return $result;
return substr($this->ctx['CtxCfgFlags1'], 6, 1) === "1";
}
/** sets Inherit-config-from-client value: enabled/disabled */
function setInheritMode($checked) {
if ($checked) {
$this->ctx['CtxCfgFlags1'][6] = "1";
}
else {
$this->ctx['CtxCfgFlags1'][6] = "0";
}
$this->ctx['CtxCfgFlags1'][6] = $checked ? "1" : "0";
}
/** gets shadow value (enum): 0-4
@ -433,13 +399,7 @@ class sambaMungedDial {
* 4: input off, notify off
*/
function getShadow() {
if ($this->old_behavior) {
$result = substr($this->ctx['CtxCfgFlags1'], 1, 1);
}
else {
$result = substr($this->ctx['CtxShadow'], 1, 1);
}
return $result;
return $this->old_behavior ? substr($this->ctx['CtxCfgFlags1'], 1, 1) : substr($this->ctx['CtxShadow'], 1, 1);
}
/** sets shadow value */
@ -456,14 +416,8 @@ class sambaMungedDial {
/** gets connect-client-drive-at-logon value: enabled/disabled */
function getConnectClientDrives() {
$connections = hexdec(substr($this->ctx['CtxCfgFlags1'], 2, 1));
if ($connections & 8) {
$result = true;
}
else {
$result = false;
}
return $result;
return $connections & 8;
}
/** sets connect-client-drive-at-logon value: enabled/disabled */
@ -482,14 +436,8 @@ class sambaMungedDial {
/** gets connect-client-printers-at-logon value: enabled/disabled */
function getConnectClientPrinters() {
$connections = hexdec(substr($this->ctx['CtxCfgFlags1'], 2, 1));
if ($connections & 4) {
$result = true;
}
else {
$result = false;
}
return $result;
return $connections & 4;
}
/** sets connect-client-printers-at-logon value: enabled/disabled */
@ -509,14 +457,8 @@ class sambaMungedDial {
/** gets set-client-printer-to-default value: enabled/disabled */
function getDefaultPrinter() {
$connections = hexdec(substr($this->ctx['CtxCfgFlags1'], 2, 1));
if ($connections & 2) {
$result = true;
}
else {
$result = false;
}
return $result;
return $connections & 2;
}
/** sets set-client-printer-to-default value: enabled/disabled */
@ -536,14 +478,7 @@ class sambaMungedDial {
/** SMARTY: gets the checkbox state of "Connection" */
function getCtxMaxConnectionTimeF() {
// Connection Time is 0 if disabled
if (isset($this->ctx['CtxMaxConnectionTime']) && ($this->ctx['CtxMaxConnectionTime'] != 0)) {
$result = true;
}
else {
$result = false;
}
return $result;
return isset($this->ctx['CtxMaxConnectionTime']) && ($this->ctx['CtxMaxConnectionTime'] != 0);
}
/** SMARTY: sets the checkbox "Connection" to unchecked */
@ -556,14 +491,7 @@ class sambaMungedDial {
/** SMARTY: gets the checkbox state of "Disconnection" */
function getCtxMaxDisconnectionTimeF() {
// Connection Time is 0 if disabled
if (isset($this->ctx['CtxMaxDisconnectionTime']) && ($this->ctx['CtxMaxDisconnectionTime'] != 0)) {
$result = true;
}
else {
$result = false;
}
return $result;
return isset($this->ctx['CtxMaxDisconnectionTime']) && ($this->ctx['CtxMaxDisconnectionTime'] != 0);
}
/** SMARTY: sets the checkbox "Disconnection" to unchecked */
@ -576,14 +504,7 @@ class sambaMungedDial {
/** SMARTY: gets the checkbox state of "Idle" */
function getCtxMaxIdleTimeF() {
// Connection Time is 0 if disabled
if (isset($this->ctx['CtxMaxIdleTime']) && ($this->ctx['CtxMaxIdleTime'] != 0)) {
$result = true;
}
else {
$result = false;
}
return $result;
return isset($this->ctx['CtxMaxIdleTime']) && ($this->ctx['CtxMaxIdleTime'] != 0);
}
/** SMARTY: sets the checkbox "Idle" to unchecked */

View file

@ -616,7 +616,7 @@ class shadowAccount extends baseModule implements passwordService, AccountStatus
*/
function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array("shadowAccount", $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = "shadowAccount";
@ -684,10 +684,10 @@ class shadowAccount extends baseModule implements passwordService, AccountStatus
// profile mappings in meta data
parent::load_profile($profile);
// add extension
if (isset($profile['shadowAccount_addExt'][0]) && ($profile['shadowAccount_addExt'][0] == "true")) {
if (!in_array('shadowAccount', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'shadowAccount';
}
if (isset($profile['shadowAccount_addExt'][0])
&& ($profile['shadowAccount_addExt'][0] == "true")
&& !in_array('shadowAccount', $this->attributes['objectClass'])) {
$this->attributes['objectClass'][] = 'shadowAccount';
}
// expiration date
if (!empty($profile['shadowAccount_shadowExpire_day'][0])) {
@ -992,7 +992,7 @@ class shadowAccount extends baseModule implements passwordService, AccountStatus
$attributes['shadowexpire'][0] = '1';
}
if (in_array(self::STATUS_PASSWORD_EXPIRED, $lockIds)) {
$inactive = !empty($attributes['shadowinactive'][0]) ? $attributes['shadowinactive'][0] : 0;
$inactive = empty($attributes['shadowinactive'][0]) ? 0 : $attributes['shadowinactive'][0];
$attributes['shadowlastchange'][0] = intval(time() / 3600 / 24) - $attributes['shadowmax'][0] - $inactive - 1;
}
}
@ -1016,7 +1016,7 @@ class shadowAccount extends baseModule implements passwordService, AccountStatus
* @inheritDoc
*/
public function getListFilterFunction(string $attributeName): ?callable {
if (($attributeName == 'shadowexpire') || ($attributeName == 'shadowlastchange')) {
if (($attributeName === 'shadowexpire') || ($attributeName === 'shadowlastchange')) {
return function(?array $values, ?string $filterValue): bool {
$regex = str_replace(['*'], ['.*'], $filterValue);
$regex = '/' . $regex . '/i';

View file

@ -44,7 +44,7 @@ class systemQuotas extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['user']);
return $this->get_scope() === 'user';
}
/**
@ -136,7 +136,7 @@ class systemQuotas extends baseModule {
if (isset($this->attributes['quota'][0])) {
natcasesort($this->attributes['quota']);
$this->attributes['quota'] = array_values($this->attributes['quota']);
for ($i = 0; $i < sizeof($this->attributes['quota']); $i++) {
for ($i = 0; $i < count($this->attributes['quota']); $i++) {
$parts = explode(',', $this->attributes['quota'][$i]);
$container->addElement(new htmlInputField('path_' . $i, $parts[0], 20));
$container->addElement($spacer);
@ -184,7 +184,7 @@ class systemQuotas extends baseModule {
$this->attributes['quota'] = [];
}
// check existing entries
for ($i = 0; $i < sizeof($this->attributes['quota']); $i++) {
for ($i = 0; $i < count($this->attributes['quota']); $i++) {
if (isset($_POST['del_' . $i])) {
unset($this->attributes['quota'][$i]);
$this->attributes['quota'] = array_values($this->attributes['quota']);
@ -331,8 +331,8 @@ class systemQuotas extends baseModule {
function check_profileOptions($options, $typeId) {
$messages = parent::check_profileOptions($options, $typeId);
$quotas = explode(';', $options['systemQuotas_quota'][0]);
for ($q = 0; $q < sizeof($quotas); $q++) {
if ($quotas[$q] == '') {
for ($q = 0; $q < count($quotas); $q++) {
if ($quotas[$q] === '') {
continue;
}
$parts = explode(',', $quotas[$q]);
@ -360,7 +360,7 @@ class systemQuotas extends baseModule {
*/
public function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array('systemQuotas', $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = 'systemQuotas';
@ -368,7 +368,7 @@ class systemQuotas extends baseModule {
// add quota
if (isset($rawAccounts[$i][$ids['systemQuotas_quota']]) && ($rawAccounts[$i][$ids['systemQuotas_quota']] != '')) {
$quotas = explode(';', $rawAccounts[$i][$ids['systemQuotas_quota']]);
for ($q = 0; $q < sizeof($quotas); $q++) {
for ($q = 0; $q < count($quotas); $q++) {
$parts = explode(',', $quotas[$q]);
$messages = array_merge($messages, $this->checkQuota($parts[0], $parts[1], $parts[2], $parts[3], $parts[4], $i));
$partialAccounts[$i]['quota'][] = $quotas[$q];
@ -393,7 +393,7 @@ class systemQuotas extends baseModule {
$pdfRow->cells[] = new PDFTableCell(_('Soft inode'), '18%', null, true);
$pdfRow->cells[] = new PDFTableCell(_('Hard inode'), '18%', null, true);
$pdfTable->rows[] = $pdfRow;
for ($i = 0; $i < sizeof($this->attributes['quota']); $i++) {
for ($i = 0; $i < count($this->attributes['quota']); $i++) {
$parts = explode(',', $this->attributes['quota'][$i]);
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell($parts[0], '28%');

View file

@ -88,7 +88,7 @@ class windowsGroup extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['group']);
return $this->get_scope() === 'group';
}
/**
@ -323,16 +323,16 @@ class windowsGroup extends baseModule {
$groupType = windowsGroup::TYPE_SECURITY;
$groupScope = windowsGroup::SCOPE_GLOBAL;
if (isset($this->attributes['groupType'][0])) {
if ($this->attributes['groupType'][0] & 2) {
if (($this->attributes['groupType'][0] & 2) !== 0) {
$groupScope = windowsGroup::SCOPE_GLOBAL;
}
elseif ($this->attributes['groupType'][0] & 4) {
elseif (($this->attributes['groupType'][0] & 4) !== 0) {
$groupScope = windowsGroup::SCOPE_DOMAIN_LOCAL;
}
elseif ($this->attributes['groupType'][0] & 8) {
elseif (($this->attributes['groupType'][0] & 8) !== 0) {
$groupScope = windowsGroup::SCOPE_UNIVERSAL;
}
if ($this->attributes['groupType'][0] & 0x80000000) {
if (($this->attributes['groupType'][0] & 0x80000000) !== 0) {
$groupType = windowsGroup::TYPE_SECURITY;
}
else {
@ -343,11 +343,11 @@ class windowsGroup extends baseModule {
// do not allow invalid conversions
if (isset($this->orig['groupType'][0])) {
$flippedScopes = array_flip($this->groupScopes);
if ($this->orig['groupType'][0] & 2) {
if (($this->orig['groupType'][0] & 2) !== 0) {
// no change from global to domain local
unset($scopeList[$flippedScopes[windowsGroup::SCOPE_DOMAIN_LOCAL]]);
}
elseif ($this->orig['groupType'][0] & 4) {
elseif (($this->orig['groupType'][0] & 4) !== 0) {
// no change from domain local to global
unset($scopeList[$flippedScopes[windowsGroup::SCOPE_GLOBAL]]);
}
@ -406,7 +406,7 @@ class windowsGroup extends baseModule {
$container->addField($memberButtons);
$memberList = [];
if (isset($this->attributes['member'])) {
for ($i = 0; $i < sizeof($this->attributes['member']); $i++) {
for ($i = 0; $i < count($this->attributes['member']); $i++) {
$memberList[] = $this->attributes['member'][$i];
}
usort($memberList, 'compareDN');
@ -414,7 +414,7 @@ class windowsGroup extends baseModule {
$members = new htmlTable();
$members->alignment = htmlElement::ALIGN_RIGHT;
$members->setCSSClasses(['fullwidth']);
for ($i = 0; $i < sizeof($memberList); $i++) {
for ($i = 0; $i < count($memberList); $i++) {
$member = new htmlOutputText(getAbstractDN($memberList[$i]));
$member->alignment = htmlElement::ALIGN_RIGHT;
$members->addElement($member, true);
@ -431,7 +431,7 @@ class windowsGroup extends baseModule {
$container->addField($memberOfGroup);
$memberList = [];
if (isset($this->attributes['memberOf'])) {
for ($i = 0; $i < sizeof($this->attributes['memberOf']); $i++) {
for ($i = 0; $i < count($this->attributes['memberOf']); $i++) {
$memberList[] = $this->attributes['memberOf'][$i];
}
usort($memberList, 'compareDN');
@ -439,7 +439,7 @@ class windowsGroup extends baseModule {
$memberOf = new htmlTable();
$memberOf->setCSSClasses(['fullwidth']);
$memberOf->alignment = htmlElement::ALIGN_RIGHT;
for ($i = 0; $i < sizeof($memberList); $i++) {
for ($i = 0; $i < count($memberList); $i++) {
$member = new htmlOutputText(getAbstractDN($memberList[$i]));
$member->alignment = htmlElement::ALIGN_RIGHT;
$memberOf->addElement($member, true);
@ -487,15 +487,13 @@ class windowsGroup extends baseModule {
}
// group type
if ($_POST['groupType'] == windowsGroup::TYPE_SECURITY) {
$this->attributes['groupType'][0] = $this->attributes['groupType'][0] - 2147483648;
$this->attributes['groupType'][0] -= 2147483648;
}
// notes
$this->attributes['info'][0] = $_POST['info'];
// managed by
if (!$this->isBooleanConfigOptionSet('windowsGroup_hidemanagedBy')) {
if (isset($_POST['form_subpage_' . static::class . '_attributes_removeManagedBy'])) {
unset($this->attributes['managedBy']);
}
if (!$this->isBooleanConfigOptionSet('windowsGroup_hidemanagedBy') && isset($_POST['form_subpage_' . static::class . '_attributes_removeManagedBy'])) {
unset($this->attributes['managedBy']);
}
// NIS name
if (!$this->isBooleanConfigOptionSet('windowsGroup_hidemsSFU30Name', true)) {
@ -534,7 +532,7 @@ class windowsGroup extends baseModule {
}
// sort by DN
usort($this->attributes['memberOf'], 'compareDN');
for ($i = 0; $i < sizeof($this->attributes['memberOf']); $i++) {
for ($i = 0; $i < count($this->attributes['memberOf']); $i++) {
if (in_array($this->attributes['memberOf'][$i], $groups)) {
$selectedGroups[getAbstractDN($this->attributes['memberOf'][$i])] = $this->attributes['memberOf'][$i];
}
@ -584,12 +582,12 @@ class windowsGroup extends baseModule {
$options = [];
$filter = get_ldap_filter('user');
$entries = searchLDAPByFilter($filter, ['dn'], ['user']);
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$entries[$i] = $entries[$i]['dn'];
}
// sort by DN
usort($entries, 'compareDN');
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$options[getAbstractDN($entries[$i])] = $entries[$i];
}
$selected = [];
@ -659,19 +657,19 @@ class windowsGroup extends baseModule {
$options = [];
$filter = get_ldap_filter($type->getId());
$entries = searchLDAP($type->getSuffix(), $filter, ['dn']);
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$entries[$i] = $entries[$i]['dn'];
}
// sort by DN
usort($entries, 'compareDN');
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
if (!isset($this->attributes['member']) || !in_array($entries[$i], $this->attributes['member'])) {
$options[getAbstractDN($entries[$i])] = $entries[$i];
}
}
$size = 20;
if (sizeof($options) < 20) {
$size = sizeof($options);
if (count($options) < 20) {
$size = count($options);
}
$membersSelect = new htmlSelect('members', $options, [], $size);
$membersSelect->setHasDescriptiveElements(true);
@ -695,14 +693,14 @@ class windowsGroup extends baseModule {
// sort by DN
usort($membersTemp, 'compareDN');
$members = [];
for ($i = 0; $i < sizeof($membersTemp); $i++) {
for ($i = 0; $i < count($membersTemp); $i++) {
$members[getAbstractDN($membersTemp[$i])] = $membersTemp[$i];
}
$size = 20;
if (isset($this->attributes['member']) && (sizeof($this->attributes['member']) < 20)) {
$size = sizeof($this->attributes['member']);
if (isset($this->attributes['member']) && (count($this->attributes['member']) < 20)) {
$size = count($this->attributes['member']);
}
if (sizeof($members) > 0) {
if ($members !== []) {
$membersSelect = new htmlSelect('members', $members, [], $size);
$membersSelect->setHasDescriptiveElements(true);
$membersSelect->setMultiSelect(true);
@ -747,7 +745,7 @@ class windowsGroup extends baseModule {
$return = [];
if (isset($_POST['form_subpage_' . static::class . '_user_remove']) && isset($_POST['members'])) {
$members = array_flip($this->attributes['member']);
for ($i = 0; $i < sizeof($_POST['members']); $i++) {
for ($i = 0; $i < count($_POST['members']); $i++) {
if (isset($members[$_POST['members'][$i]])) {
unset($members[$_POST['members'][$i]]);
}
@ -755,7 +753,7 @@ class windowsGroup extends baseModule {
$this->attributes['member'] = array_values(array_flip($members));
}
elseif (isset($_POST['form_subpage_' . static::class . '_user_addMembers']) && isset($_POST['members'])) {
for ($i = 0; $i < sizeof($_POST['members']); $i++) {
for ($i = 0; $i < count($_POST['members']); $i++) {
$this->attributes['member'][] = $_POST['members'][$i];
$this->attributes['member'] = array_unique($this->attributes['member']);
}
@ -802,7 +800,7 @@ class windowsGroup extends baseModule {
*/
public function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$errors = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array('group', $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = 'group';
@ -815,7 +813,7 @@ class windowsGroup extends baseModule {
}
else {
$errMsg = $this->messages['cn'][1];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$errors[] = $errMsg;
}
}
@ -853,7 +851,7 @@ class windowsGroup extends baseModule {
}
else {
$errMsg = $this->messages['groupScope'][0];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$errors[] = $errMsg;
}
}
@ -864,17 +862,17 @@ class windowsGroup extends baseModule {
if ($rawAccounts[$i][$ids['windowsGroup_type']] != "") {
if (in_array($rawAccounts[$i][$ids['windowsGroup_type']], $this->groupTypes)) {
if ($rawAccounts[$i][$ids['windowsGroup_type']] == windowsGroup::TYPE_SECURITY) {
$partialAccounts[$i]['groupType'] = $partialAccounts[$i]['groupType'] - 2147483648;
$partialAccounts[$i]['groupType'] -= 2147483648;
}
}
else {
$errMsg = $this->messages['groupType'][0];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$errors[] = $errMsg;
}
}
else {
$partialAccounts[$i]['groupType'] = $partialAccounts[$i]['groupType'] - 2147483648;
$partialAccounts[$i]['groupType'] -= 2147483648;
}
// NIS name
if (!$this->isBooleanConfigOptionSet('windowsGroup_hidemsSFU30Name', true)) {
@ -905,16 +903,16 @@ class windowsGroup extends baseModule {
$groupType = windowsGroup::TYPE_SECURITY;
$groupScope = windowsGroup::SCOPE_GLOBAL;
if (isset($this->attributes['groupType'][0])) {
if ($this->attributes['groupType'][0] & 2) {
if (($this->attributes['groupType'][0] & 2) !== 0) {
$groupScope = windowsGroup::SCOPE_GLOBAL;
}
elseif ($this->attributes['groupType'][0] & 4) {
elseif (($this->attributes['groupType'][0] & 4) !== 0) {
$groupScope = windowsGroup::SCOPE_DOMAIN_LOCAL;
}
elseif ($this->attributes['groupType'][0] & 8) {
elseif (($this->attributes['groupType'][0] & 8) !== 0) {
$groupScope = windowsGroup::SCOPE_UNIVERSAL;
}
if ($this->attributes['groupType'][0] & 0x80000000) {
if (($this->attributes['groupType'][0] & 0x80000000) !== 0) {
$groupType = windowsGroup::TYPE_SECURITY;
}
else {
@ -941,7 +939,7 @@ class windowsGroup extends baseModule {
}
usort($memberList, 'compareDN');
$pdfTable = new PDFTable(_('Members'));
for ($i = 0; $i < sizeof($memberList); $i++) {
for ($i = 0; $i < count($memberList); $i++) {
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell($memberList[$i]);
$pdfTable->rows[] = $pdfRow;
@ -956,7 +954,7 @@ class windowsGroup extends baseModule {
}
usort($memberOfList, 'compareDN');
$pdfTable = new PDFTable(_('Member of'));
for ($i = 0; $i < sizeof($memberOfList); $i++) {
for ($i = 0; $i < count($memberOfList); $i++) {
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell($memberOfList[$i]);
$pdfTable->rows[] = $pdfRow;
@ -978,7 +976,7 @@ class windowsGroup extends baseModule {
$return = [];
$types = ['group'];
$results = searchLDAPByFilter('(objectClass=group)', ['dn'], $types);
$count = sizeof($results);
$count = count($results);
for ($i = 0; $i < $count; $i++) {
if (isset($results[$i]['dn'])) {
$return[] = $results[$i]['dn'];
@ -1038,7 +1036,7 @@ class windowsGroup extends baseModule {
$toAdd = array_values(array_diff($this->attributes['memberOf'], $this->orig['memberOf']));
$toRem = array_values(array_diff($this->orig['memberOf'], $this->attributes['memberOf']));
// add groups
for ($i = 0; $i < sizeof($toAdd); $i++) {
for ($i = 0; $i < count($toAdd); $i++) {
if (in_array($toAdd[$i], $groups)) {
$success = @ldap_mod_add($_SESSION['ldap']->server(), $toAdd[$i], ['member' => [$this->getAccountContainer()->finalDN]]);
if (!$success) {
@ -1051,7 +1049,7 @@ class windowsGroup extends baseModule {
}
}
// remove groups
for ($i = 0; $i < sizeof($toRem); $i++) {
for ($i = 0; $i < count($toRem); $i++) {
if (in_array($toRem[$i], $groups)) {
$success = @ldap_mod_del($_SESSION['ldap']->server(), $toRem[$i], ['member' => [$this->getAccountContainer()->dn_orig]]);
if (!$success) {
@ -1148,7 +1146,7 @@ class windowsGroup extends baseModule {
if (!empty($values)) {
usort($values, 'compareDN');
}
$count = sizeof($values);
$count = count($values);
for ($i = 0; $i < $count; $i++) {
$replaced = false;
foreach ($typeManager->getConfiguredTypes() as $type) {

View file

@ -48,7 +48,7 @@ class windowsHost extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['host']);
return $this->get_scope() === 'host';
}
/**
@ -265,12 +265,12 @@ class windowsHost extends baseModule {
$options = [];
$filter = get_ldap_filter('user');
$entries = searchLDAPByFilter($filter, ['dn'], ['user']);
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$entries[$i] = $entries[$i]['dn'];
}
// sort by DN
usort($entries, 'compareDN');
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$options[getAbstractDN($entries[$i])] = $entries[$i];
}
$selected = [];
@ -322,7 +322,7 @@ class windowsHost extends baseModule {
*/
public function build_uploadAccounts($rawAccounts, $ids, &$partialAccounts, $selectedModules, &$type) {
$errors = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array('computer', $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = 'computer';
@ -335,7 +335,7 @@ class windowsHost extends baseModule {
}
else {
$errMsg = $this->messages['cn'][1];
array_push($errMsg, [$i]);
$errMsg[] = [$i];
$errors[] = $errMsg;
}
}

View file

@ -116,7 +116,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
* @return boolean true if module fits
*/
public function can_manage() {
return $this->get_scope() == 'user';
return $this->get_scope() === 'user';
}
/**
@ -1322,7 +1322,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
// get group memberships
$groupList = searchLDAPByAttribute('member', $this->getAccountContainer()->dn_orig, 'group', ['dn'], ['group']);
$this->groupList_orig = [];
for ($i = 0; $i < sizeof($groupList); $i++) {
for ($i = 0; $i < count($groupList); $i++) {
$this->groupList_orig[] = $groupList[$i]['dn'];
}
$this->groupList_orig = array_values(array_unique($this->groupList_orig));
@ -1624,12 +1624,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
for ($i = 90; $i > 67; $i--) {
$drives[] = chr($i) . ':';
}
if (!empty($this->attributes['homeDrive'][0])) {
$selected = [strtoupper($this->attributes['homeDrive'][0])];
}
else {
$selected = ['-'];
}
$selected = empty($this->attributes['homeDrive'][0]) ? ['-'] : [strtoupper($this->attributes['homeDrive'][0])];
$containerLeft->add(new htmlResponsiveSelect('homeDrive', $drives, $selected, _('Home drive'), 'homeDrive'));
}
// home directory
@ -1959,7 +1954,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
// profile path
if (!$this->isBooleanConfigOptionSet('windowsUser_hideprofilePath')) {
$this->attributes['profilePath'][0] = $_POST['profilePath'];
if (!($this->attributes['profilePath'][0] == '') && !get_preg($this->attributes['profilePath'][0], 'UNC')) {
if (($this->attributes['profilePath'][0] != '') && !get_preg($this->attributes['profilePath'][0], 'UNC')) {
$return[] = $this->messages['profilePath'][0];
}
}
@ -1972,12 +1967,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
}
// home drive
if (!$this->isBooleanConfigOptionSet('windowsUser_hidehomeDrive')) {
if ($_POST['homeDrive'] == "-") {
$this->attributes['homeDrive'][0] = '';
}
else {
$this->attributes['homeDrive'][0] = $_POST['homeDrive'];
}
$this->attributes['homeDrive'][0] = ($_POST['homeDrive'] === "-") ? '' : $_POST['homeDrive'];
}
// home directory
if (!$this->isBooleanConfigOptionSet('windowsUser_hidehomeDirectory')) {
@ -2089,7 +2079,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
$return = new htmlResponsiveRow();
$attr = 'accountexpires';
$datetime = new DateTime('now', getTimeZone());
if (!empty($this->attributes[$attr][0]) && !($this->attributes[$attr][0] == '0')) {
if (!empty($this->attributes[$attr][0]) && ($this->attributes[$attr][0] != '0')) {
$datetime = windowsUser::getFileTime($this->attributes[$attr][0]);
}
$dateInput = new htmlResponsiveInputField(_('Account expiration date'), $attr, $datetime->format('Y-m-d'), 'accountexpires');
@ -2131,7 +2121,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
// find button name
$buttonName = '';
$postKeys = array_keys($_POST);
for ($i = 0; $i < sizeof($postKeys); $i++) {
for ($i = 0; $i < count($postKeys); $i++) {
if (str_contains($postKeys[$i], 'form_subpage_windowsUser_attributes_')) {
$buttonName = $postKeys[$i];
}
@ -2215,7 +2205,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
if ($groupDisplayContainsDn) {
usort($this->groupList, compareDN(...));
}
for ($i = 0; $i < sizeof($this->groupList); $i++) {
for ($i = 0; $i < count($this->groupList); $i++) {
if (in_array($this->groupList[$i], $groups)) {
$groupDn = $this->groupList[$i];
$groupCn = extractRDNValue($groupDn);
@ -2559,12 +2549,12 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
$options = [];
$filter = get_ldap_filter('user');
$entries = searchLDAPByFilter('(|' . $filter . '(objectclass=organizationalRole))', ['dn'], ['user']);
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$entries[$i] = $entries[$i]['dn'];
}
// sort by DN
usort($entries, compareDN(...));
for ($i = 0; $i < sizeof($entries); $i++) {
for ($i = 0; $i < count($entries); $i++) {
$options[getAbstractDN($entries[$i])] = $entries[$i];
}
$selectedManager = [];
@ -2672,7 +2662,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
$temp = str_replace(' ', '', $this->attributes['userWorkstations'][0]);
$workstations = explode(',', $temp);
for ($i = 0; $i < count($workstations); $i++) {
if ($workstations[$i] == '') {
if ($workstations[$i] === '') {
unset($workstations[$i]);
}
}
@ -2697,7 +2687,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
$temp = str_replace(' ', '', $this->attributes['userWorkstations'][0]);
$workstations = explode(',', $temp);
for ($i = 0; $i < count($workstations); $i++) {
if ($workstations[$i] == '') {
if ($workstations[$i] === '') {
unset($workstations[$i]);
}
}
@ -2706,7 +2696,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
$workstations = array_delete($_POST['workstations_1'], $workstations);
// Recreate workstation string
unset($this->attributes['userWorkstations'][0]);
if (sizeof($workstations) > 0) {
if (count($workstations) > 0) {
$this->attributes['userWorkstations'][0] = $workstations[0];
for ($i = 1; $i < count($workstations); $i++) {
$this->attributes['userWorkstations'][0] = $this->attributes['userWorkstations'][0] . "," . $workstations[$i];
@ -2726,7 +2716,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
return $this->cachedHostList;
}
$this->cachedHostList = searchLDAPByAttribute('cn', '*', 'computer', ['cn'], ['host']);
for ($i = 0; $i < sizeof($this->cachedHostList); $i++) {
for ($i = 0; $i < count($this->cachedHostList); $i++) {
$this->cachedHostList[$i] = $this->cachedHostList[$i]['cn'][0];
}
return $this->cachedHostList;
@ -2748,7 +2738,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
$toAdd = array_values(array_diff($this->groupList, $this->groupList_orig));
$toRem = array_values(array_diff($this->groupList_orig, $this->groupList));
// add groups
for ($i = 0; $i < sizeof($toAdd); $i++) {
for ($i = 0; $i < count($toAdd); $i++) {
if (in_array($toAdd[$i], $groups)) {
$success = @ldap_mod_add($_SESSION['ldap']->server(), $toAdd[$i], ['member' => [$this->getAccountContainer()->finalDN]]);
if (!$success) {
@ -2761,7 +2751,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
}
}
// remove groups
for ($i = 0; $i < sizeof($toRem); $i++) {
for ($i = 0; $i < count($toRem); $i++) {
if (in_array($toRem[$i], $groups)) {
// membership is removed with potentially new DN as Windows updates group automatically on user move
$success = @ldap_mod_del($_SESSION['ldap']->server(), $toRem[$i], ['member' => [$this->getAccountContainer()->finalDN]]);
@ -2811,7 +2801,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
}
}
$booleanOptions = [_('yes') => true, _('no') => false];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!in_array('user', $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = 'user';
@ -2981,7 +2971,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
if (!$this->isBooleanConfigOptionSet('windowsUser_hideotherMailbox') && isset($ids['windowsUser_otherMailbox']) && ($rawAccounts[$i][$ids['windowsUser_otherMailbox']] != "")) {
$valueList = preg_split('/;[ ]*/', $rawAccounts[$i][$ids['windowsUser_otherMailbox']]);
$partialAccounts[$i]['otherMailbox'] = $valueList;
for ($x = 0; $x < sizeof($valueList); $x++) {
for ($x = 0; $x < count($valueList); $x++) {
if (!get_preg($valueList[$x], 'email')) {
$errMsg = $this->messages['otherMailbox'][1];
$errMsg[] = [$i];
@ -3122,7 +3112,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
$invalidGroups[] = $group;
}
}
if (sizeof($invalidGroups) > 0) {
if ($invalidGroups !== []) {
$errors[] = ['ERROR', sprintf(_('Account %s:'), $i) . ' windowsUser_groups',
_('LAM was unable to find a group with this name!') . '<br>' . htmlspecialchars(implode('; ', $invalidGroups))];
}
@ -3238,13 +3228,13 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
$temp['pwdChangeCount'] = 0;
$groupCol = $ids['windowsUser_groups'];
$passwordChangeRequiredCol = $ids['windowsUser_pwdMustChange'];
for ($i = 0; $i < sizeof($data); $i++) {
for ($i = 0; $i < count($data); $i++) {
if (in_array($i, $failed)) {
continue;
} // ignore failed accounts
if ($data[$i][$groupCol] != "") {
$groups = preg_split('/;[ ]*/', $data[$i][$groupCol]);
for ($g = 0; $g < sizeof($groups); $g++) {
for ($g = 0; $g < count($groups); $g++) {
if (in_array($groups[$g], $temp['groups'])) {
$temp['members'][$groups[$g]][] = $accounts[$i]['dn'];
}
@ -3257,8 +3247,8 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
$temp['pwdChange'][] = $accounts[$i]['dn'];
}
}
$temp['memberCount'] = sizeof($temp['members']);
$temp['pwdChangeCount'] = sizeof($temp['pwdChange']);
$temp['memberCount'] = count($temp['members']);
$temp['pwdChangeCount'] = count($temp['pwdChange']);
$temp['counter'] = $temp['memberCount'] + $temp['pwdChangeCount'];
return [
'status' => 'inProgress',
@ -3267,7 +3257,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
];
}
// add users to groups
elseif (sizeof($temp['members']) > 0) {
elseif (count($temp['members']) > 0) {
$keys = array_keys($temp['members']);
$group = $keys[0];
$member = array_pop($temp['members'][$group]);
@ -3281,10 +3271,10 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
[$group]
];
}
if (sizeof($temp['members'][$group]) == 0) {
if (count($temp['members'][$group]) == 0) {
unset($temp['members'][$group]);
}
$memberPercentage = (100 * ($temp['memberCount'] - sizeof($temp['members']))) / $temp['counter'];
$memberPercentage = (100 * ($temp['memberCount'] - count($temp['members']))) / $temp['counter'];
return [
'status' => 'inProgress',
'progress' => $memberPercentage,
@ -3292,7 +3282,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
];
}
// force password change
elseif (sizeof($temp['pwdChange']) > 0) {
elseif (count($temp['pwdChange']) > 0) {
$dn = array_pop($temp['pwdChange']);
$success = @ldap_mod_replace($_SESSION['ldap']->server(), $dn, ['pwdLastSet' => '0']);
$errors = [];
@ -3304,7 +3294,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
[$dn]
];
}
$pwdPercentage = (100 * ($temp['memberCount'] + ($temp['pwdChangeCount'] - sizeof($temp['pwdChange'])))) / $temp['counter'];
$pwdPercentage = (100 * ($temp['memberCount'] + ($temp['pwdChangeCount'] - count($temp['pwdChange'])))) / $temp['counter'];
return [
'status' => 'inProgress',
'progress' => $pwdPercentage,
@ -3401,10 +3391,10 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
}
$this->addPDFKeyValue($return, 'groups', _('Groups'), $groups);
// password
if (isset($this->clearTextPassword)) {
if ($this->clearTextPassword !== null) {
$this->addPDFKeyValue($return, 'password', _('Password'), $this->clearTextPassword);
}
else if (isset($this->attributes['INFO.userPasswordClearText'])) {
elseif (isset($this->attributes['INFO.userPasswordClearText'])) {
$this->addPDFKeyValue($return, 'password', _('Password'), $this->attributes['INFO.userPasswordClearText']);
}
// last password change
@ -3648,27 +3638,25 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
if ($_POST['windowsUser_unicodePwd'] != $_POST['windowsUser_unicodePwd2']) {
$return['messages'][] = $this->messages['unicodePwd'][0];
}
elseif (!get_preg($_POST['windowsUser_unicodePwd'], 'password')) {
$return['messages'][] = $this->messages['unicodePwd'][1];
}
else {
if (!get_preg($_POST['windowsUser_unicodePwd'], 'password')) {
$return['messages'][] = $this->messages['unicodePwd'][1];
$userName = empty($attributes['userPrincipalName'][0]) ? null : $attributes['userPrincipalName'][0];
$additionalAttrs = [];
if (!empty($attributes['sn'][0])) {
$additionalAttrs[] = $attributes['sn'][0];
}
if (!empty($attributes['givenName'][0])) {
$additionalAttrs[] = $attributes['givenName'][0];
}
$pwdPolicyResult = checkPasswordStrength($_POST['windowsUser_unicodePwd'], $userName, $additionalAttrs);
if ($pwdPolicyResult === true) {
$this->setSelfServicePassword($return);
$return['info']['userPasswordClearText'][0] = $_POST['windowsUser_unicodePwd'];
}
else {
$userName = empty($attributes['userPrincipalName'][0]) ? null : $attributes['userPrincipalName'][0];
$additionalAttrs = [];
if (!empty($attributes['sn'][0])) {
$additionalAttrs[] = $attributes['sn'][0];
}
if (!empty($attributes['givenName'][0])) {
$additionalAttrs[] = $attributes['givenName'][0];
}
$pwdPolicyResult = checkPasswordStrength($_POST['windowsUser_unicodePwd'], $userName, $additionalAttrs);
if ($pwdPolicyResult === true) {
$this->setSelfServicePassword($return);
$return['info']['userPasswordClearText'][0] = $_POST['windowsUser_unicodePwd'];
}
else {
$return['messages'][] = ['ERROR', $pwdPolicyResult];
}
$return['messages'][] = ['ERROR', $pwdPolicyResult];
}
}
}
@ -3904,14 +3892,12 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
$attrs = &$this->attributes;
}
foreach ($attrs as $key => $value) {
if (strtolower($key) == 'useraccountcontrol') {
if (strtolower($key) === 'useraccountcontrol') {
if ($deactivated) {
$attrs[$key][0] = intval($value[0]) | self::AC_ACCOUNT_DISABLED;
}
else {
if (intval($value[0]) & self::AC_ACCOUNT_DISABLED) {
$attrs[$key][0] = intval($value[0]) - self::AC_ACCOUNT_DISABLED;
}
elseif ((intval($value[0]) & self::AC_ACCOUNT_DISABLED) !== 0) {
$attrs[$key][0] = intval($value[0]) - self::AC_ACCOUNT_DISABLED;
}
}
}
@ -3938,14 +3924,12 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
*/
public static function setIsSmartCardRequired(&$attrs, $requireCard) {
foreach ($attrs as $key => $value) {
if (strtolower($key) == 'useraccountcontrol') {
if (strtolower($key) === 'useraccountcontrol') {
if ($requireCard) {
$attrs[$key][0] = intval($value[0]) | self::AC_SMARTCARD_REQUIRED;
}
else {
if (intval($value[0]) & self::AC_SMARTCARD_REQUIRED) {
$attrs[$key][0] = intval($value[0]) - self::AC_SMARTCARD_REQUIRED;
}
elseif ((intval($value[0]) & self::AC_SMARTCARD_REQUIRED) !== 0) {
$attrs[$key][0] = intval($value[0]) - self::AC_SMARTCARD_REQUIRED;
}
}
}
@ -3972,14 +3956,12 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
*/
public static function setIsNeverExpiring(&$attrs, $neverExpires) {
foreach ($attrs as $key => $value) {
if (strtolower($key) == 'useraccountcontrol') {
if (strtolower($key) === 'useraccountcontrol') {
if ($neverExpires) {
$attrs[$key][0] = (string) (intval($value[0]) | self::AC_PWD_NEVER_EXPIRES);
}
else {
if (intval($value[0]) & self::AC_PWD_NEVER_EXPIRES) {
$attrs[$key][0] = (string) (intval($value[0]) - self::AC_PWD_NEVER_EXPIRES);
}
elseif ((intval($value[0]) & self::AC_PWD_NEVER_EXPIRES) !== 0) {
$attrs[$key][0] = (string) (intval($value[0]) - self::AC_PWD_NEVER_EXPIRES);
}
}
}
@ -3997,7 +3979,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
$return = [];
$types = ['group'];
$results = searchLDAPByFilter('(objectClass=group)', ['dn'], $types);
$count = sizeof($results);
$count = count($results);
for ($i = 0; $i < $count; $i++) {
if (isset($results[$i]['dn'])) {
$return[] = $results[$i]['dn'];
@ -4349,7 +4331,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
$titles = [];
$employeeTypes = [];
$businessCategories = [];
if (sizeof($attrs) > 0) {
if ($attrs !== []) {
$result = searchLDAPByFilter('(objectClass=user)', $attrs, [$this->get_scope()]);
foreach ($result as $attributes) {
if (isset($attributes['department'])) {
@ -4445,7 +4427,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
}
elseif (!empty($this->attributes['userPrincipalName'][0])) {
$userParts = explode('@', $this->attributes['userPrincipalName'][0]);
if ((sizeof($userParts) === 2) && !empty($userParts[0])) {
if ((count($userParts) === 2) && !empty($userParts[0])) {
$replacements['user'] = $userParts[0];
}
}
@ -4683,7 +4665,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr
return function(array $entry, string $attribute): ?htmlElement {
$group = new htmlGroup();
if (isset($entry[$attribute][0]) && ($entry[$attribute][0] != '')) {
for ($i = 0; $i < sizeof($entry[$attribute]); $i++) {
for ($i = 0; $i < count($entry[$attribute]); $i++) {
if ($i > 0) {
$group->addElement(new htmlOutputText(", "));
}
@ -4940,8 +4922,7 @@ if (interface_exists('\LAM\JOB\Job', false)) {
$errors = [];
// from address
if (empty($options[$prefix . '_mailFrom' . $jobID][0])
|| !(get_preg($options[$prefix . '_mailFrom' . $jobID][0], 'email')
|| get_preg($options[$prefix . '_mailFrom' . $jobID][0], 'emailWithName'))) {
|| (!get_preg($options[$prefix . '_mailFrom' . $jobID][0], 'email') && !get_preg($options[$prefix . '_mailFrom' . $jobID][0], 'emailWithName'))) {
$errors[] = ['ERROR', _('Please enter a valid email address!'), _('From address')];
}
// reply-to
@ -5032,7 +5013,7 @@ if (interface_exists('\LAM\JOB\Job', false)) {
return;
}
$userResults = $this->findUsers($jobID, $options);
$this->jobResultLog->logDebug("Found " . sizeof($userResults) . " users to send an email.");
$this->jobResultLog->logDebug("Found " . count($userResults) . " users to send an email.");
$isHTML = (!empty($options[$this->getConfigPrefix() . '_mailIsHTML' . $jobID][0]) && ($options[$this->getConfigPrefix() . '_mailIsHTML' . $jobID][0] == 'true'));
foreach ($userResults as $user) {
if (empty($user[strtolower(self::MANAGED_GROUPS)])) {
@ -5082,12 +5063,12 @@ if (interface_exists('\LAM\JOB\Job', false)) {
* @return int interval
*/
private function getMonthInterval($options, $jobId): int {
return match($options[$this->getConfigPrefix() . '_period' . $jobId][0]) {
self::PERIOD_HALF_YEARLY => 6,
self::PERIOD_QUARTERLY => 3,
self::PERIOD_MONTHLY => 1,
default => 12,
};
return match ($options[$this->getConfigPrefix() . '_period' . $jobId][0]) {
self::PERIOD_HALF_YEARLY => 6,
self::PERIOD_QUARTERLY => 3,
self::PERIOD_MONTHLY => 1,
default => 12,
};
}
/**

View file

@ -58,7 +58,7 @@ class yubiKeyUser extends baseModule {
* @return boolean true if module fits
*/
public function can_manage() {
return in_array($this->get_scope(), ['user']);
return $this->get_scope() === 'user';
}
/**
@ -235,7 +235,7 @@ class yubiKeyUser extends baseModule {
$objectClass = $this->getObjectClassName();
$attributeName = $this->getAttributeName();
$messages = [];
for ($i = 0; $i < sizeof($rawAccounts); $i++) {
for ($i = 0; $i < count($rawAccounts); $i++) {
// add object class
if (!empty($objectClass) && !in_array($objectClass, $partialAccounts[$i]['objectClass'])) {
$partialAccounts[$i]['objectClass'][] = $objectClass;
@ -256,7 +256,7 @@ class yubiKeyUser extends baseModule {
$attributeName = $this->getAttributeName();
if (!empty($this->attributes[$attributeName])) {
$pdfTable = new PDFTable(_('YubiKey ids'));
for ($i = 0; $i < sizeof($this->attributes[$attributeName]); $i++) {
for ($i = 0; $i < count($this->attributes[$attributeName]); $i++) {
$pdfRow = new PDFTableRow();
$pdfRow->cells[] = new PDFTableCell($this->attributes[$attributeName][$i]);
$pdfTable->rows[] = $pdfRow;
@ -315,8 +315,8 @@ class yubiKeyUser extends baseModule {
private function getSelfServiceKeys() {
$keys = $_SESSION[self::SESS_KEY_LIST];
$content = new htmlResponsiveRow();
if (sizeof($keys) > 0) {
for ($i = 0; $i < sizeof($keys); $i++) {
if (count($keys) > 0) {
for ($i = 0; $i < count($keys); $i++) {
$group = new htmlGroup();
$keyInput = new htmlInputField('yubiKeyId_' . $i, $keys[$i]);
$keyInput->setFieldMaxLength(12);
@ -325,7 +325,7 @@ class yubiKeyUser extends baseModule {
$group->addElement($keyInput);
$delLink = new htmlLink('', '#', '../../graphics/del.svg');
$delLink->setTitle(_('Delete'));
$delLink->setOnClick('yubiKeyIdDeleteKey(' . $i . ', ' . sizeof($keys) . ');return false;');
$delLink->setOnClick('yubiKeyIdDeleteKey(' . $i . ', ' . count($keys) . ');return false;');
$delLink->setCSSClasses(['icon']);
$group->addElement($delLink);
$content->add($group, 12, 12, 12, 'nowrap');
@ -334,7 +334,7 @@ class yubiKeyUser extends baseModule {
$addGroup = new htmlGroup();
$addLink = new htmlLink(_('Add'), '#', '../../graphics/add.svg', true);
$addLink->setTitle(_('Add'));
$addLink->setOnClick('yubiKeyIdAddKey(' . sizeof($keys) . ');return false;');
$addLink->setOnClick('yubiKeyIdAddKey(' . count($keys) . ');return false;');
$addLink->setCSSClasses(['icon']);
$addGroup->addElement($addLink);
$addGroup->addElement(new htmlSpacer('0.5rem', null));
@ -348,7 +348,7 @@ class yubiKeyUser extends baseModule {
*
* @return htmlJavaScript JS block
*/
private static function getSelfServiceKeysJSBlock() {
private function getSelfServiceKeysJSBlock() {
$content = '
function yubiKeyIdDeleteKey(id, count) {
var actionJSON = {
@ -449,9 +449,9 @@ class yubiKeyUser extends baseModule {
$newKeys[] = $_POST['yubiKeyId_' . $counter];
$counter++;
}
$count = sizeof($newKeys);
$count = count($newKeys);
for ($i = 0; $i < $count; $i++) {
if (trim($newKeys[$i]) == '') {
if (trim($newKeys[$i]) === '') {
unset($newKeys[$i]);
}
elseif (!get_preg($newKeys[$i], 'ascii')) {
@ -464,11 +464,11 @@ class yubiKeyUser extends baseModule {
$oldKeys = $attributes[$attributeName];
}
$update = false;
if (sizeof($newKeys) != sizeof($oldKeys)) {
if (count($newKeys) !== count($oldKeys)) {
$update = true;
}
else {
for ($i = 0; $i < sizeof($newKeys); $i++) {
for ($i = 0; $i < count($newKeys); $i++) {
if (!in_array($newKeys[$i], $oldKeys)) {
$update = true;
break;
@ -476,10 +476,10 @@ class yubiKeyUser extends baseModule {
}
}
if ($update) {
if (sizeof($oldKeys) == 0) {
if (count($oldKeys) == 0) {
$return['add'][$attributeName] = $newKeys;
}
elseif (sizeof($newKeys) == 0) {
elseif (count($newKeys) == 0) {
$return['del'][$attributeName] = $newKeys;
}
else {

View file

@ -203,7 +203,7 @@ function replaceWildcards(string $value, array $entry): string {
// §attr|;§ -> "val1;val2"
$matches = [];
if (preg_match_all('/§([a-z0-9-_]+)\\|([^§]+)§/i', $replacement, $matches) > 0) {
for ($i = 0; $i < sizeof($matches[1]); $i++) {
for ($i = 0; $i < count($matches[1]); $i++) {
$attributeName = strtolower($matches[1][$i]);
$separator = $matches[2][$i];
$match = $matches[0][$i];

View file

@ -48,7 +48,7 @@ define('LAMPDF_FONT_SIZE', 7);
define('LAMPDF_FONT_SIZE_BIG', 10);
/** access to PDF configuration files */
include_once('pdfstruct.inc');
include_once(__DIR__ . '/pdfstruct.inc');
/**
* This function creates the PDF output of one or more accounts.
@ -152,10 +152,10 @@ function createPdf($structure, $accounts, $pdfKeys, $account_type, $font, $retur
if ($valueEntry instanceof PDFLabelValue) {
printLabelValue($pdf, $valueEntry, $font);
}
else if ($valueEntry instanceof PDFTable) {
elseif ($valueEntry instanceof PDFTable) {
printTable($pdf, $valueEntry, $font);
}
else if ($valueEntry instanceof PDFImage) {
elseif ($valueEntry instanceof PDFImage) {
printImage($pdf, $valueEntry, $font);
}
}

View file

@ -96,7 +96,7 @@ class PdfStructurePersistenceManager {
* @throws LAMException error deleting template
*/
public function deletePdfStructureTemplate(string $scope, string $name): void {
if (!$this->isValidPdfStructureName($name) || !TypeManager::isValidTypeId($scope) || ($name == 'default')) {
if (!$this->isValidPdfStructureName($name) || !TypeManager::isValidTypeId($scope) || ($name === 'default')) {
logNewMessage(LOG_NOTICE, "Invalid account profile name: $name:$scope");
throw new LAMException(_("Unable to delete profile!"));
}
@ -649,7 +649,7 @@ class PdfStructurePersistenceStrategyFiles implements PdfStructurePersistenceStr
$entry = $templateDir->read();
while ($entry) {
$parts = explode('.', $entry);
if ((strlen($entry) > 3) && (sizeof($parts) == 3)) {
if ((strlen($entry) > 3) && (count($parts) == 3)) {
$name = $parts[0];
$scope = $parts[1];
$allTemplates[$scope][] = $name;
@ -698,7 +698,7 @@ class PdfStructurePersistenceStrategyFiles implements PdfStructurePersistenceStr
logNewMessage(LOG_ERR, 'Unable to write ' . $fileName);
throw new LAMException(_('Unable to save PDF structure.'));
}
fputs($file, $xml);
fwrite($file, $xml);
fclose($file);
}
@ -774,7 +774,7 @@ class PdfStructurePersistenceStrategyFiles implements PdfStructurePersistenceStr
logNewMessage(LOG_ERR, 'Unable to write ' . $fileName);
throw new LAMException(_('Unable to upload logo file.'));
}
fputs($file, $data);
fwrite($file, $data);
fclose($file);
}
@ -803,7 +803,7 @@ class PdfStructurePersistenceStrategyFiles implements PdfStructurePersistenceStr
throw new LAMException(_('Unable to read logos.'));
}
while ($file = readdir($dirHandle)) {
if (!is_dir($file) && $file != '.' && $file != '..' && preg_match('/\\.(jpg|png)$/i', $file)) {
if (!is_dir($file) && $file !== '.' && $file !== '..' && preg_match('/\\.(jpg|png)$/i', $file)) {
$return[] = $file;
}
}
@ -846,7 +846,7 @@ class PdfStructurePersistenceStrategyFiles implements PdfStructurePersistenceStr
logNewMessage(LOG_ERR, 'Unable to write ' . $fileName);
throw new LAMException(_('Unable to upload logo file.'));
}
fputs($file, $data);
fwrite($file, $data);
fclose($file);
}
@ -861,12 +861,12 @@ class PdfStructurePersistenceStrategyFiles implements PdfStructurePersistenceStr
while ($file = readdir($dirHandle)) {
$struct_file = explode('.', $file);
if (!is_dir($path . $file)
&& ($file != '.')
&& ($file != '..')
&& (sizeof($struct_file) === 3)
&& ($file !== '.')
&& ($file !== '..')
&& (count($struct_file) === 3)
&& ($struct_file[1] === $typeId)
&& ($struct_file[2] === 'xml')) {
array_push($return, $struct_file[0]);
$return[] = $struct_file[0];
}
}
}
@ -920,7 +920,7 @@ class PdfStructurePersistenceStrategyFiles implements PdfStructurePersistenceStr
logNewMessage(LOG_ERR, 'Unable to write ' . $fileName);
throw new LAMException(_('Unable to save PDF structure.'));
}
fputs($file, $xml);
fwrite($file, $xml);
fclose($file);
}

View file

@ -269,7 +269,7 @@ class ConfigDataExporter {
if (!isLAMProVersion()) {
return $data;
}
include_once 'database.inc';
include_once __DIR__ . '/database.inc';
foreach ($serverProfiles as $serverProfileName => $serverProfile) {
try {
$cronDatabase = new CronDatabase($serverProfile);
@ -696,7 +696,7 @@ class ConfigDataImporter {
return;
}
$failedProfiles = [];
include_once 'database.inc';
include_once __DIR__ . '/database.inc';
$serverProfilePersistenceManager = new ServerProfilePersistenceManager();
foreach ($step->getSubSteps() as $profileStep) {
if (!$profileStep->isActive()) {
@ -708,7 +708,7 @@ class ConfigDataImporter {
$cronDatabase = new CronDatabase($serverProfile);
$cronDatabase->connect();
if (isset($data['jobRuns'])) {
logNewMessage(LOG_DEBUG, 'Import ' . sizeof($data['jobRuns']) . ' cron job runs for ' . $serverProfileName);
logNewMessage(LOG_DEBUG, 'Import ' . count($data['jobRuns']) . ' cron job runs for ' . $serverProfileName);
$cronDatabase->clearJobRuns();
foreach ($data['jobRuns'] as $jobRun) {
$cronDatabase->importJobRun($jobRun['runId'], $jobRun['name'], $jobRun['jobId'], $jobRun['time'], $jobRun['isOk'], $jobRun['message']);
@ -721,7 +721,7 @@ class ConfigDataImporter {
continue;
}
$job = $jobs[$jobId];
logNewMessage(LOG_DEBUG, 'Import ' . sizeof($jobData) . ' cron data entries for ' . $job->getName() . ' - ' . $jobId);
logNewMessage(LOG_DEBUG, 'Import ' . count($jobData) . ' cron data entries for ' . $job->getName() . ' - ' . $jobId);
$job->import($cronDatabase->getPdo(), $jobData, $jobId);
}
}

View file

@ -83,7 +83,7 @@ class AccountProfilePersistenceManager {
* @throws LAMException error deleting template
*/
public function deleteAccountProfileTemplate(string $scope, string $name): void {
if (!$this->isValidAccountProfileName($name) || !TypeManager::isValidTypeId($scope) || ($name == 'default')) {
if (!$this->isValidAccountProfileName($name) || !TypeManager::isValidTypeId($scope) || ($name === 'default')) {
logNewMessage(LOG_NOTICE, "Invalid account profile name: $name:$scope");
throw new LAMException(_("Unable to delete profile!"));
}
@ -376,7 +376,7 @@ class AccountProfilePersistenceStrategyFiles implements AccountProfilePersistenc
$entry = $templateDir->read();
while ($entry) {
$parts = explode('.', $entry);
if ((strlen($entry) > 3) && (sizeof($parts) === 2)) {
if ((strlen($entry) > 3) && (count($parts) === 2)) {
$name = $parts[0];
$scope = $parts[1];
$templates[$scope][] = $name;
@ -439,19 +439,19 @@ class AccountProfilePersistenceStrategyFiles implements AccountProfilePersistenc
if ($file) {
while (!feof($file)) {
$line = fgets($file, 1024);
if (($line === false) || ($line == '') || ($line == "\n") || ($line[0] == "#")) {
if (($line === false) || ($line === '') || ($line === "\n") || ($line[0] === "#")) {
continue; // ignore comments
}
// search keywords
$parts = explode(": ", $line);
if (sizeof($parts) == 2) {
if (count($parts) == 2) {
$option = $parts[0];
if ($option === 'profname') {
continue;
}
$value = $parts[1];
// remove line ends
$value = chop($value);
$value = rtrim($value);
$settings[$option] = explode("+::+", $value);
}
}
@ -486,14 +486,9 @@ class AccountProfilePersistenceStrategyFiles implements AccountProfilePersistenc
}
// write attributes
$keys = array_keys($data);
for ($i = 0; $i < sizeof($keys); $i++) {
if (isset($data[$keys[$i]])) {
$line = $keys[$i] . ": " . implode("+::+", $data[$keys[$i]]) . "\n";
}
else {
$line = $keys[$i] . ": \n";
}
fputs($file, $line);
for ($i = 0; $i < count($keys); $i++) {
$line = isset($data[$keys[$i]]) ? $keys[$i] . ": " . implode("+::+", $data[$keys[$i]]) . "\n" : $keys[$i] . ": \n";
fwrite($file, $line);
}
// close file
fclose($file);
@ -558,7 +553,7 @@ class AccountProfilePersistenceStrategyFiles implements AccountProfilePersistenc
// check if filename ends with .<typeId>
if (strrpos($entry, '.')) {
$pos = strrpos($entry, '.');
if (substr($entry, $pos + 1) == $typeId) {
if (substr($entry, $pos + 1) === $typeId) {
$name = substr($entry, 0, $pos);
$ret[] = $name;
}

View file

@ -83,7 +83,7 @@ class Remote {
}
$this->serverConfig = $server;
$serverNameParts = explode(",", $this->serverConfig->getServer());
if (sizeof($serverNameParts) > 1) {
if (count($serverNameParts) > 1) {
$handle = @new SSH2($serverNameParts[0], $serverNameParts[1]);
}
else {
@ -131,27 +131,17 @@ class Remote {
}
$keyPath = $this->serverConfig->getSshKey();
$keyPassword = $this->serverConfig->getSshKeyPassword();
if (!empty($keyPath)) {
$password = $this->loadKey($keyPath, $keyPassword);
}
else {
$password = $_SESSION['ldap']->getPassword();
}
$password = empty($keyPath) ? $_SESSION['ldap']->getPassword() : $this->loadKey($keyPath, $keyPassword);
try {
$login = @$handle->login($username, $password);
if (!$login) {
$errors = $handle->getErrors();
if (!empty($errors)) {
$errors = implode(' ', $errors);
}
else {
$errors = null;
}
$errors = empty($errors) ? null : implode(' ', $errors);
throw new LAMException(_("Unable to login to lamdaemon server."), $errors);
}
}
catch (Exception $e) {
throw new LAMException(_("Unable to login to lamdaemon server."), $e->getMessage());
throw new LAMException(_("Unable to login to lamdaemon server."), $e->getMessage(), $e);
}
}
@ -179,7 +169,7 @@ class Remote {
}
catch (NoKeyLoadedException $e) {
logNewMessage(LOG_ERR, sprintf('Unable to load key %s: %s', $keyPath, $e->getMessage()));
throw new LAMException(sprintf(_("Unable to load key %s."), htmlspecialchars($keyPath)));
throw new LAMException(sprintf(_("Unable to load key %s."), htmlspecialchars($keyPath)), null, $e);
}
}

View file

@ -1,4 +1,5 @@
<?php
namespace LAM\SCHEMA;
/*
@ -125,7 +126,7 @@ class ObjectClass extends SchemaItem {
case '(':
break;
case 'NAME':
if ($strings[$i + 1] != "(") {
if ($strings[$i + 1] !== "(") {
do {
$i++;
if (($this->name === null) || (strlen($this->name) == 0)) {
@ -173,7 +174,7 @@ class ObjectClass extends SchemaItem {
$this->is_obsolete = TRUE;
break;
case 'SUP':
if ($strings[$i + 1] != "(") {
if ($strings[$i + 1] !== "(") {
$i++;
$this->sup_classes[] = preg_replace("/'/", "", $strings[$i]);
}
@ -181,7 +182,7 @@ class ObjectClass extends SchemaItem {
$i++;
do {
$i++;
if ($strings[$i] != "$") {
if ($strings[$i] !== "$") {
$this->sup_classes[] = preg_replace("/'/", "", $strings[$i]);
}
}
@ -204,14 +205,14 @@ class ObjectClass extends SchemaItem {
$this->must_attrs[] = $attr;
do {
$i++;
if ($strings[$i] != "$") {
if ($strings[$i] !== "$") {
$attr = new ObjectClassAttribute($strings[$i], $this->name);
$this->must_attrs[] = $attr;
}
}
while (!preg_match('/\)+\)?/', $strings[$i + 1]));
}
elseif ($strings[$i + 1] != "(") {
elseif ($strings[$i + 1] !== "(") {
$i++;
$attr = new ObjectClassAttribute($strings[$i], $this->name);
$this->must_attrs[] = $attr;
@ -220,7 +221,7 @@ class ObjectClass extends SchemaItem {
$i++;
do {
$i++;
if ($strings[$i] != "$") {
if ($strings[$i] !== "$") {
$attr = new ObjectClassAttribute($strings[$i], $this->name);
$this->must_attrs[] = $attr;
}
@ -236,14 +237,14 @@ class ObjectClass extends SchemaItem {
$this->may_attrs[] = $attr;
do {
$i++;
if ($strings[$i] != "$") {
if ($strings[$i] !== "$") {
$attr = new ObjectClassAttribute($strings[$i], $this->name);
$this->may_attrs[] = $attr;
}
}
while (!preg_match('/\)+\)?/', $strings[$i + 1]));
}
elseif ($strings[$i + 1] != "(") {
elseif ($strings[$i + 1] !== "(") {
$i++;
$attr = new ObjectClassAttribute($strings[$i], $this->name);
$this->may_attrs[] = $attr;
@ -252,7 +253,7 @@ class ObjectClass extends SchemaItem {
$i++;
do {
$i++;
if ($strings[$i] != "$") {
if ($strings[$i] !== "$") {
$attr = new ObjectClassAttribute($strings[$i], $this->name);
$this->may_attrs[] = $attr;
}
@ -593,7 +594,7 @@ class AttributeType extends SchemaItem {
case '(':
break;
case 'NAME':
if ($strings[$i + 1] != "(") {
if ($strings[$i + 1] !== "(") {
do {
$i++;
if (($this->name === null) || (strlen($this->name) == 0)) {
@ -620,7 +621,7 @@ class AttributeType extends SchemaItem {
}
while (!preg_match("/\'$/", $strings[$i]));
// add alias names for this attribute
while ($strings[++$i] != ")") {
while ($strings[++$i] !== ")") {
$alias = $strings[$i];
$alias = preg_replace("/^\'/", "", $alias);
$alias = preg_replace("/\'$/", "", $alias);
@ -632,7 +633,7 @@ class AttributeType extends SchemaItem {
do {
$i++;
if (strlen($this->description) == 0) {
$this->description = $this->description . $strings[$i];
$this->description .= $strings[$i];
}
else {
$this->description = $this->description . " " . $strings[$i];
@ -664,18 +665,13 @@ class AttributeType extends SchemaItem {
$this->syntax = $strings[$i];
$this->syntax_oid = preg_replace("/{\d+}$/", "", $this->syntax);
// does this SYNTAX string specify a max length (ie, 1.2.3.4{16})
if (preg_match("/{(\d+)}$/", $this->syntax, $this->max_length)) {
$this->max_length = $this->max_length[1];
}
else {
$this->max_length = null;
}
if ($i < count($strings) - 1 && $strings[$i + 1] == "{") {
$this->max_length = preg_match("/{(\d+)}$/", $this->syntax, $this->max_length) ? $this->max_length[1] : null;
if ($i < count($strings) - 1 && $strings[$i + 1] === "{") {
do {
$i++;
$this->name .= " " . $strings[$i];
}
while ($strings[$i] != "}");
while ($strings[$i] !== "}");
}
break;
case 'SINGLE-VALUE':
@ -1021,7 +1017,7 @@ class Syntax extends SchemaItem {
do {
$i++;
if (strlen($this->description) == 0) {
$this->description = $this->description . $strings[$i];
$this->description .= $strings[$i];
}
else {
$this->description = $this->description . " " . $strings[$i];
@ -1077,7 +1073,7 @@ class MatchingRule extends SchemaItem {
case '(':
break;
case 'NAME':
if ($strings[$i + 1] != "(") {
if ($strings[$i + 1] !== "(") {
do {
$i++;
if (strlen($this->name) == 0) {
@ -1113,7 +1109,7 @@ class MatchingRule extends SchemaItem {
do {
$i++;
if (strlen($this->description) == 0) {
$this->description = $this->description . $strings[$i];
$this->description .= $strings[$i];
}
else {
$this->description = $this->description . " " . $strings[$i];
@ -1211,10 +1207,10 @@ class MatchingRuleUse extends SchemaItem {
case '(':
break;
case 'NAME':
if ($strings[$i + 1] != "(") {
if ($strings[$i + 1] !== "(") {
do {
$i++;
if (!isset($this->name) || strlen($this->name) == 0) {
if ($this->name === null || strlen($this->name) == 0) {
$this->name = $strings[$i];
}
else {
@ -1244,7 +1240,7 @@ class MatchingRuleUse extends SchemaItem {
$this->name = preg_replace("/\'$/", "", $this->name);
break;
case 'APPLIES':
if ($strings[$i + 1] != "(") {
if ($strings[$i + 1] !== "(") {
// has a single attribute name
$i++;
$this->used_by_attrs = [$strings[$i]];
@ -1253,7 +1249,7 @@ class MatchingRuleUse extends SchemaItem {
else {
// has multiple attribute names
$i++;
while ($strings[$i] != ")") {
while ($strings[$i] !== ")") {
$i++;
$new_attr = $strings[$i];
$new_attr = preg_replace("/^\'/", "", $new_attr);
@ -1429,19 +1425,13 @@ function _get_raw_schema($schema_to_fetch, $dn = '') {
LDAP_DEREF_ALWAYS);
// Were we not able to fetch the schema from the $schema_dn?
if ($schema_search !== false) {
$schema_entries = @ldap_get_entries($ds, $schema_search);
}
else {
$schema_entries = [];
}
$schema_entries = $schema_search !== false ? @ldap_get_entries($ds, $schema_search) : [];
if ($schema_search === false ||
0 == @ldap_count_entries($ds, $schema_search) ||
!isset($schema_entries[0][$schema_to_fetch])) {
if ($debug) {
echo "Did not find the schema with (objectClass=*). Attempting with (objetClass=subschema)\n";
}
// Try again with a different filter (some servers require (objectClass=subschema) like M-Vault)
$schema_search = @ldap_read($ds, $schema_dn, '(objectClass=subschema)',
[$schema_to_fetch], 0, 0, 0,
@ -1449,7 +1439,6 @@ function _get_raw_schema($schema_to_fetch, $dn = '') {
if ($schema_search !== false) {
$schema_entries = @ldap_get_entries($ds, $schema_search);
}
// Still didn't get it?
if ($schema_search === false ||
0 == @ldap_count_entries($ds, $schema_search) ||
@ -1461,16 +1450,12 @@ function _get_raw_schema($schema_to_fetch, $dn = '') {
unset($schema_dn);
$schema_search = null;
}
else {
if ($debug) {
echo "Found the schema at DN: $schema_dn (with objectClass=subschema).\n";
}
elseif ($debug) {
echo "Found the schema at DN: $schema_dn (with objectClass=subschema).\n";
}
}
else {
if ($debug) {
echo "Found the schema at DN: $schema_dn (with objectClass=*).\n";
}
elseif ($debug) {
echo "Found the schema at DN: $schema_dn (with objectClass=*).\n";
}
}
@ -1644,7 +1629,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);
@ -1686,7 +1671,7 @@ function get_schema_objectclasses($dn = null, $use_cache = true): array {
function get_schema_objectclass($oclass_name, $dn = null, $use_cache = true) {
$oclass_name = strtolower($oclass_name);
$oclasses = get_schema_objectclasses($dn, $use_cache);
if (!$oclasses) {
if ($oclasses === []) {
return false;
}
return $oclasses[$oclass_name] ?? false;
@ -1816,7 +1801,7 @@ function add_aliases_to_attrs(&$attrs) {
// go back and add data from aliased attributeTypes
foreach ($attrs as $attr) {
$aliases = $attr->getAliases();
if (is_array($aliases) && count($aliases) > 0) {
if (is_array($aliases) && ($aliases !== [])) {
// foreach of the attribute's aliases, create a new entry in the attrs array
// with its name set to the alias name, and all other data copied
foreach ($aliases as $alias_attr_name) {
@ -2049,7 +2034,7 @@ function get_schema_syntaxes($dn = null, $use_cache = true) {
foreach ($raw_syntaxes as $syntax_string) {
$syntax = new Syntax($syntax_string);
$key = strtolower(trim($syntax->getOID()));
if (!$key) {
if ($key === '') {
continue;
}
$syntaxes[$key] = $syntax;
@ -2079,7 +2064,7 @@ function get_schema_syntaxes($dn = null, $use_cache = true) {
*/
function cached_schema_available($schema_type) {
// Check config to make sure session-based caching is enabled.
if (!SCHEMA_SESSION_CACHE_ENABLED) {
if (SCHEMA_SESSION_CACHE_ENABLED === 0) {
return false;
}
@ -2113,7 +2098,7 @@ function cached_schema_available($schema_type) {
*/
function get_cached_schema($schema_type) {
// Check config to make sure session-based caching is enabled.
if (!SCHEMA_SESSION_CACHE_ENABLED) {
if (SCHEMA_SESSION_CACHE_ENABLED === 0) {
return false;
}
@ -2145,7 +2130,7 @@ function get_cached_schema($schema_type) {
*/
function set_cached_schema($schema_type, $schema_items) {
// Check config to make sure session-based caching is enabled.
if (!SCHEMA_SESSION_CACHE_ENABLED) {
if (SCHEMA_SESSION_CACHE_ENABLED === 0) {
return false;
}
@ -2165,7 +2150,7 @@ function set_cached_schema($schema_type, $schema_items) {
* fetch it from the server.
*/
function set_schema_cache_unavailable() {
if (!SCHEMA_SESSION_CACHE_ENABLED) {
if (SCHEMA_SESSION_CACHE_ENABLED === 0) {
return false;
}
$_SESSION['schema']['unavailable'] = true;

View file

@ -28,11 +28,11 @@
*/
/** configuration options */
include_once('config.inc');
include_once(__DIR__ . '/config.inc');
/** ldap connection */
include_once('ldap.inc');
include_once(__DIR__ . '/ldap.inc');
/** common functions */
include_once('account.inc');
include_once(__DIR__ . '/account.inc');
// check client IP address
checkClientIP();
@ -167,7 +167,7 @@ function checkClientIP() {
}
$allowedHosts = explode(",", $allowedHosts);
$grantAccess = false;
for ($i = 0; $i < sizeof($allowedHosts); $i++) {
for ($i = 0; $i < count($allowedHosts); $i++) {
$host = $allowedHosts[$i];
$ipRegex = '/^[0-9a-z\\.:\\*]+$/i';
if (!preg_match($ipRegex, $host)) {
@ -222,7 +222,7 @@ function logoffAndBackToLoginPage(): void {
$page = 'selfServiceLogin.php';
$pageSuffix = '?expired=yes&scope=' . $scope . '&name=' . $name;
}
for ($i = 0; $i < sizeof($paths); $i++) {
for ($i = 0; $i < count($paths); $i++) {
if (file_exists($paths[$i] . $page)) {
$page = $paths[$i] . $page;
break;
@ -349,10 +349,7 @@ function checkIfPasswordChangeIsAllowed() {
if (!isset($_SESSION['config'])) {
return false;
}
if ($_SESSION['config']->getAccessLevel() >= LAMConfig::ACCESS_PASSWORD_CHANGE) {
return true;
}
return false;
return $_SESSION['config']->getAccessLevel() >= LAMConfig::ACCESS_PASSWORD_CHANGE;
}
/**
@ -432,7 +429,7 @@ function checkPasswordStrength($password, $userNames, $otherUserAttrs) {
if (preg_match("/[A-Z]/", $password[$i])) {
$upper++;
}
if (preg_match("/[0-9]/", $password[$i])) {
if (preg_match("/\\d/", $password[$i])) {
$numeric++;
}
if (preg_match("/[^a-z0-9]/i", $password[$i])) {
@ -561,7 +558,7 @@ function checkPwdWithExternalPasswordService($cfg, $password) {
curl_setopt($curl, CURLOPT_URL, $url);
$results = curl_exec($curl);
$code = curl_errno($curl);
if ($code) {
if ($code !== 0) {
logNewMessage(LOG_ERR, 'Error calling the external password service at ' . $url
. '. ' . curl_error($curl));
return true;

View file

@ -35,11 +35,11 @@ use function LAM\PERSISTENCE\dbTableExists;
*/
/** modules */
include_once "modules.inc";
include_once __DIR__ . "/modules.inc";
/** account types */
include_once "types.inc";
include_once __DIR__ . "/types.inc";
/** 2-factor */
include_once '2factor.inc';
include_once __DIR__ . '/2factor.inc';
/**
* Returns if this is a LAM Pro installation.
@ -60,7 +60,7 @@ function isLAMProVersion() {
function getSelfServiceSearchAttributes($scope) {
$return = [];
$modules = getAvailableModules($scope);
for ($i = 0; $i < sizeof($modules); $i++) {
for ($i = 0; $i < count($modules); $i++) {
$m = moduleCache::getModule($modules[$i], $scope);
$attributes = $m->getSelfServiceSearchAttributes();
$return = array_merge($return, $attributes);
@ -78,10 +78,10 @@ function getSelfServiceSearchAttributes($scope) {
function getSelfServiceFieldSettings($scope) {
$return = [];
$modules = getAvailableModules($scope);
for ($i = 0; $i < sizeof($modules); $i++) {
for ($i = 0; $i < count($modules); $i++) {
$m = moduleCache::getModule($modules[$i], $scope);
$settings = $m->getSelfServiceFields();
if (sizeof($settings) > 0) {
if (count($settings) > 0) {
$return[$modules[$i]] = $settings;
}
}
@ -107,14 +107,14 @@ function getSelfServiceOptions($scope, $fields, $attributes, $passwordChangeOnly
}
$m = moduleCache::getModule($module, $scope);
$modReadOnlyFields = [];
for ($r = 0; $r < sizeof($readOnlyFields); $r++) {
for ($r = 0; $r < count($readOnlyFields); $r++) {
$parts = explode('_', $readOnlyFields[$r]);
if ($parts[0] == $module) {
$modReadOnlyFields[] = $parts[1];
}
}
$code = $m->getSelfServiceOptions($fields[$module], $attributes, $passwordChangeOnly, $modReadOnlyFields);
if (sizeof($code) > 0) {
if (count($code) > 0) {
$return[$module] = $code;
}
}
@ -134,32 +134,32 @@ function getSelfServiceOptions($scope, $fields, $attributes, $passwordChangeOnly
function checkSelfServiceOptions($scope, $fields, $attributes, $passwordChangeOnly, $readOnlyFields) {
$return = ['messages' => [], 'add' => [], 'del' => [], 'mod' => [], 'info' => []];
$modules = getAvailableModules($scope);
for ($i = 0; $i < sizeof($modules); $i++) {
for ($i = 0; $i < count($modules); $i++) {
if (!isset($fields[$modules[$i]])) {
continue;
}
$m = moduleCache::getModule($modules[$i], $scope);
$modReadOnlyFields = [];
for ($r = 0; $r < sizeof($readOnlyFields); $r++) {
for ($r = 0; $r < count($readOnlyFields); $r++) {
$parts = explode('_', $readOnlyFields[$r]);
if ($parts[0] == $modules[$i]) {
$modReadOnlyFields[] = $parts[1];
}
}
$result = $m->checkSelfServiceOptions($fields[$modules[$i]], $attributes, $passwordChangeOnly, $modReadOnlyFields);
if (sizeof($result['messages']) > 0) {
if (count($result['messages']) > 0) {
$return['messages'] = array_merge($result['messages'], $return['messages']);
}
if (sizeof($result['add']) > 0) {
if (count($result['add']) > 0) {
$return['add'] = array_merge($result['add'], $return['add']);
}
if (sizeof($result['del']) > 0) {
if (count($result['del']) > 0) {
$return['del'] = array_merge($result['del'], $return['del']);
}
if (sizeof($result['mod']) > 0) {
if (count($result['mod']) > 0) {
$return['mod'] = array_merge($result['mod'], $return['mod']);
}
if (sizeof($result['info']) > 0) {
if (count($result['info']) > 0) {
$return['info'] = array_merge($result['info'], $return['info']);
}
}
@ -176,7 +176,7 @@ function checkSelfServiceOptions($scope, $fields, $attributes, $passwordChangeOn
function getSelfServiceSettings($scope, $profile) {
$return = [];
$modules = getAvailableModules($scope);
for ($i = 0; $i < sizeof($modules); $i++) {
for ($i = 0; $i < count($modules); $i++) {
$m = moduleCache::getModule($modules[$i], $scope);
$return[$modules[$i]] = $m->getSelfServiceSettings($profile);
}
@ -194,7 +194,7 @@ function getSelfServiceSettings($scope, $profile) {
function checkSelfServiceSettings($scope, &$options, &$profile) {
$return = [];
$modules = getAvailableModules($scope);
for ($i = 0; $i < sizeof($modules); $i++) {
for ($i = 0; $i < count($modules); $i++) {
$m = moduleCache::getModule($modules[$i], $scope);
$errors = $m->checkSelfServiceSettings($options, $profile);
$return = array_merge($return, $errors);
@ -266,7 +266,7 @@ class SelfServicePersistence {
}
catch (PDOException $e) {
logNewMessage(LOG_ERR, _('Unable to connect to configuration database.') . ' ' . $e->getMessage());
throw new LAMException(_('Unable to connect to configuration database.'));
throw new LAMException(_('Unable to connect to configuration database.'), null, $e);
}
}
else {
@ -282,7 +282,7 @@ class SelfServicePersistence {
public function getProfiles(): array {
$profiles = $this->strategy->getProfiles();
ksort($profiles);
foreach ($profiles as $key => $value) {
foreach (array_keys($profiles) as $key) {
sort($profiles[$key]);
}
return $profiles;
@ -472,7 +472,7 @@ class SelfServicePersistenceStrategyFileSystem implements SelfServicePersistence
}
$profile = new selfServiceProfile();
$file = __DIR__ . "/../config/selfService/" . $name . "." . $scope;
if (is_file($file) === True) {
if (is_file($file)) {
$file = @fopen($file, "r");
if ($file) {
$data = fread($file, 10000000);
@ -506,7 +506,7 @@ class SelfServicePersistenceStrategyFileSystem implements SelfServicePersistence
$file = @fopen($path, "w");
if ($file) {
// write settings to file
fputs($file, json_encode($profile->export()));
fwrite($file, json_encode($profile->export()));
// close file
fclose($file);
@chmod($path, 0600);
@ -664,25 +664,25 @@ class SelfServicePersistenceStrategyPdo implements SelfServicePersistenceStrateg
class selfServiceProfile {
/** server address */
public $serverURL;
public $serverURL = "localhost";
/** use TLS */
public $useTLS;
public $useTLS = false;
/** LDAP suffix */
public $LDAPSuffix;
public $LDAPSuffix = "dc=my-domain,dc=com";
/** LDAP user DN*/
public $LDAPUser;
public $LDAPUser = "";
/** LDAP password */
public $LDAPPassword;
public $LDAPPassword = "";
/** use bind user also for read/modify operations */
public $useForAllOperations;
public $useForAllOperations = false;
/** LDAP search attribute */
public $searchAttribute;
public $searchAttribute = "uid";
/**
* @var string|null login handler ID
@ -690,13 +690,13 @@ class selfServiceProfile {
public ?string $loginHandler = SelfServiceUserPasswordLoginHandler::ID;
/** header for self service pages */
public $pageHeader;
public $pageHeader = '<p><a href="https://www.ldap-account-manager.org/" target="new_window"><img alt="help" class="align-middle" src="../../graphics/logo24.png" style="height:24px; width:24px" /> LDAP Account Manager </a></p><p>&nbsp;</p>';
/** base color */
public $baseColor = '#fffde2';
/** list of additional CSS links (separated by \n) */
public $additionalCSS;
public $additionalCSS = '';
/** describing text for user login */
public $loginCaption;
@ -705,13 +705,13 @@ class selfServiceProfile {
public $loginFooter;
/** label for password input */
public $passwordLabel;
public $passwordLabel = '';
/** describing text for search attribute */
public $loginAttributeText;
/** additional LDAP filter for accounts */
public $additionalLDAPFilter;
public $additionalLDAPFilter = '';
/** describing text for self service main page */
public $mainPageText;
@ -731,13 +731,13 @@ class selfServiceProfile {
/**
* List of fields that are set in read-only mode.
*/
public $readOnlyFields;
public $readOnlyFields = [];
/** List of override values for field labels: array(<field ID> => label) */
public $relabelFields;
public $relabelFields = [];
/** configuration settings of modules */
public $moduleSettings;
public $moduleSettings = [];
/** language for self service */
public $language = 'en_GB.utf8';
@ -814,22 +814,8 @@ class selfServiceProfile {
* Constructor
*/
public function __construct() {
// set default values
$this->serverURL = "localhost";
$this->useTLS = false;
$this->LDAPSuffix = "dc=my-domain,dc=com";
$this->LDAPUser = "";
$this->LDAPPassword = "";
$this->useForAllOperations = false;
$this->searchAttribute = "uid";
$this->additionalLDAPFilter = '';
$this->loginHandler = '';
$this->pageHeader = '<p><a href="https://www.ldap-account-manager.org/" target="new_window"><img alt="help" class="align-middle" src="../../graphics/logo24.png" style="height:24px; width:24px" /> LDAP Account Manager </a></p><p>&nbsp;</p>';
$this->additionalCSS = '';
$this->baseColor = '#fffde2';
$this->loginCaption = '<b>' . _("Welcome to LAM self service. Please enter your user name and password.") . '</b>';
$this->loginAttributeText = _('User name');
$this->passwordLabel = '';
$this->mainPageText = "<h1>LAM self service</h1>\n" . _("Here you can change your personal settings.");
$this->inputFields = [
['name' => _('Personal data'),
@ -839,28 +825,6 @@ class selfServiceProfile {
['name' => _('Password'),
'fields' => ['posixAccount_password']]
];
$this->readOnlyFields = [];
$this->relabelFields = [];
$this->moduleSettings = [];
$this->language = 'en_GB.utf8';
$this->enforceLanguage = true;
$this->followReferrals = 0;
$this->timeZone = 'Europe/London';
$this->twoFactorAuthentication = TwoFactorProviderService::TWO_FACTOR_NONE;
$this->twoFactorAuthenticationURL = 'https://localhost';
$this->twoFactorAuthenticationInsecure = false;
$this->twoFactorAuthenticationLabel = null;
$this->twoFactorAuthenticationOptional = false;
$this->twoFactorAuthenticationCaption = '';
$this->twoFactorAuthenticationClientId = '';
$this->twoFactorAuthenticationSecretKey = '';
$this->twoFactorAuthenticationAttribute = 'uid';
$this->twoFactorAuthenticationDomain = '';
$this->captchaProvider = '-';
$this->reCaptchaSiteKey = '';
$this->reCaptchaSecretKey = '';
$this->captchaOnLogin = false;
$this->baseUrl = '';
}
/**
@ -1078,7 +1042,7 @@ class SelfServiceUserPasswordLoginHandler implements SelfServiceLoginHandler {
*/
function addLoginFields(htmlResponsiveRow $content): void {
// user name
$userNameVal = !empty($_POST['username']) ? $_POST['username'] : '';
$userNameVal = empty($_POST['username']) ? '' : $_POST['username'];
$userField = new htmlResponsiveInputField($this->profile->loginAttributeText, 'username', $userNameVal);
$userField->setCSSClasses(['lam-initial-focus']);
$content->add($userField);
@ -1087,7 +1051,7 @@ class SelfServiceUserPasswordLoginHandler implements SelfServiceLoginHandler {
if (!empty($this->profile->passwordLabel)) {
$passwordText = $this->profile->passwordLabel;
}
$passwordVal = !empty($_POST['password']) ? $_POST['password'] : '';
$passwordVal = empty($_POST['password']) ? '' : $_POST['password'];
$passwordField = new htmlResponsiveInputField($passwordText, 'password', $passwordVal);
$passwordField->setIsPassword(true);
$content->add($passwordField);
@ -1162,7 +1126,7 @@ class SelfServiceHttpAuthLoginHandler implements SelfServiceLoginHandler {
// user name
$userLabel = new htmlLabel('username', $this->profile->loginAttributeText);
$content->addLabel($userLabel);
$userName = !empty($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '-';
$userName = empty($_SERVER['PHP_AUTH_USER']) ? '-' : $_SERVER['PHP_AUTH_USER'];
$userField = new htmlOutputText($userName);
$content->addField($userField);
// password field
@ -1315,7 +1279,7 @@ class SelfService2FaLoginHandler implements SelfServiceLoginHandler {
}
$info = $entries;
cleanLDAPResult($info);
if (sizeof($info) === 1) {
if (count($info) === 1) {
$userDN = $info[0]['dn'];
$_SESSION['selfService_clientDN'] = lamEncrypt($userDN, 'SelfService');
return;

View file

@ -67,7 +67,7 @@ function StatusMessage($MessageTyp, $MessageHeadline, $MessageText = '', $Messag
}
$format = "<div " . $class . ">\n<table>\n<tr>\n<td>" . $MessageHeadline . $MessageText . "</td>\n</tr>\n</table>\n</div>\n";
if (is_array($MessageVariables)) {
if (sizeof($MessageVariables) > 0) {
if ($MessageVariables !== []) {
array_unshift($MessageVariables, $format);
$output = call_user_func_array('sprintf', $MessageVariables);
}

View file

@ -39,7 +39,7 @@ function getTools(): array {
$entry = $toolsDir->read();
// include all files in the tools directory
while ($entry) {
if ((substr($entry, strlen($entry) - 4, 4) == '.inc') && is_file($toolsDirName . '/' . $entry)) {
if ((substr($entry, strlen($entry) - 4, 4) === '.inc') && is_file($toolsDirName . '/' . $entry)) {
include_once($toolsDirName . '/' . $entry);
}
$entry = $toolsDir->read();

View file

@ -95,7 +95,7 @@ class toolFileUpload extends LAMTool {
public function isVisible(): bool {
$typeManager = new TypeManager();
$types = $typeManager->getConfiguredTypes();
return (sizeof($types) > 0);
return (count($types) > 0);
}
}

View file

@ -95,7 +95,7 @@ class toolOUEditor extends LAMTool {
public function isVisible(): bool {
$typeManager = new TypeManager();
$types = $typeManager->getConfiguredTypes();
return (sizeof($types) > 0);
return (count($types) > 0);
}
}

View file

@ -95,7 +95,7 @@ class toolPDFEditor extends LAMTool {
public function isVisible(): bool {
$typeManager = new TypeManager();
$types = $typeManager->getConfiguredTypes();
return (sizeof($types) > 0);
return (count($types) > 0);
}
}

View file

@ -95,7 +95,7 @@ class toolProfileEditor extends LAMTool {
public function isVisible(): bool {
$typeManager = new TypeManager();
$types = $typeManager->getConfiguredTypes();
return (sizeof($types) > 0);
return (count($types) > 0);
}
}

View file

@ -96,7 +96,7 @@ class toolTests extends LAMTool {
public function isVisible(): bool {
$typeManager = new TypeManager();
$types = $typeManager->getConfiguredTypes();
return (sizeof($types) > 0);
return (count($types) > 0);
}
}

View file

@ -107,7 +107,7 @@ class TreeViewTool extends LAMTool {
public function getConfigOptions(array $settings): ?htmlElement {
$row = new htmlResponsiveRow();
$row->add(new htmlOutputText(_('Tree view')), 12);
$suffix = !empty($settings[self::TREE_SUFFIX_CONFIG]) ? $settings[self::TREE_SUFFIX_CONFIG] : '';
$suffix = empty($settings[self::TREE_SUFFIX_CONFIG]) ? '' : $settings[self::TREE_SUFFIX_CONFIG];
$row->add(new htmlResponsiveInputField(_('Tree suffix'), self::TREE_SUFFIX_CONFIG, $suffix, '203'), 12);
$row->addVerticalSpacer('1rem');
return $row;

View file

@ -60,9 +60,9 @@ use function LAM\SCHEMA\get_schema_objectclasses;
* @author Roland Gruber
*/
include_once 'account.inc';
include_once 'tools.inc';
include_once 'tools/treeview.inc';
include_once __DIR__ . '/account.inc';
include_once __DIR__ . '/tools.inc';
include_once __DIR__ . '/tools/treeview.inc';
/**
* Tree view functions.
@ -583,7 +583,7 @@ class TreeView {
* @return bool is multi-value
*/
private function isMultiValueAttribute(?array $values, ?AttributeType $schemaAttribute): bool {
return (sizeof($values) > 1) || (($schemaAttribute !== null) && ($schemaAttribute->getIsSingleValue() !== true));
return (count($values) > 1) || (($schemaAttribute !== null) && ($schemaAttribute->getIsSingleValue() !== true));
}
/**
@ -671,7 +671,7 @@ class TreeView {
if (empty($values)) {
return false;
}
$regex = '/^\\{[0-9]+\\}/';
$regex = '/^\{\d+\}/';
foreach ($values as $value) {
if (!preg_match($regex, $value)) {
return false;
@ -763,10 +763,7 @@ class TreeView {
if (stripos($attributeName, 'jpegphoto') === 0) {
return true;
}
if (($schemaAttribute !== null) && ($schemaAttribute->getType() === 'JPEG')) {
return true;
}
return false;
return ($schemaAttribute !== null) && ($schemaAttribute->getType() === 'JPEG');
}
/**
@ -872,10 +869,9 @@ class TreeView {
if (in_array_ignore_case($schemaAttribute->getName(), $requiredAttributes)) {
return true;
}
if (!empty($schemaObjectClass->getSupClasses())) {
if ($this->isAttributeRequired($schemaObjectClasses, $schemaAttribute, $schemaObjectClass->getSupClasses())) {
return true;
}
if (!empty($schemaObjectClass->getSupClasses())
&& $this->isAttributeRequired($schemaObjectClasses, $schemaAttribute, $schemaObjectClass->getSupClasses())) {
return true;
}
}
return false;
@ -953,7 +949,7 @@ class TreeView {
if (!isset($ldapChanges[$attrName]) && !empty($attributes[$attrName])) {
$ldapChanges[$attrName] = $attributes[$attrName];
}
$oldValues = !empty($attributes[$attrName]) ? $attributes[$attrName] : [];
$oldValues = empty($attributes[$attrName]) ? [] : $attributes[$attrName];
if ($this->isMultiValueAttribute($oldValues, $schemaAttribute)) {
$ldapChanges[$attrName][] = base64_decode($change['upload']);
}
@ -1057,12 +1053,7 @@ class TreeView {
$binaryValues = [];
foreach ($encoded as $value) {
$decoded = base64_decode($value, true);
if ($decoded !== false) {
$binaryValues[] = $decoded;
}
else {
$binaryValues[] = $value;
}
$binaryValues[] = ($decoded !== false) ? $decoded : $value;
}
return $binaryValues;
}
@ -1076,14 +1067,9 @@ class TreeView {
*/
private function applyPasswordHash(array $values, array $hash): array {
$result = [];
for ($i = 0; $i < sizeof($values); $i++) {
for ($i = 0; $i < count($values); $i++) {
$oldType = getHashType($values[$i]);
if (($oldType === 'PLAIN') && ($hash[$i] !== 'PLAIN')) {
$result[] = pwd_hash($values[$i], true, $hash[$i]);
}
else {
$result[] = $values[$i];
}
$result[] = (($oldType === 'PLAIN') && ($hash[$i] !== 'PLAIN')) ? pwd_hash($values[$i], true, $hash[$i]) : $values[$i];
}
return $result;
}
@ -1172,12 +1158,7 @@ class TreeView {
* @return string JSON data
*/
private function createNewNodeCheckObjectClassesStep(string $dn, ?string $errorMessage = null, ?string $rdnAttribute = null, ?array $attributes = null): string {
if ($attributes === null) {
$objectClasses = explode(',', $_POST['objectClasses']);
}
else {
$objectClasses = $attributes['objectClass'];
}
$objectClasses = ($attributes === null) ? explode(',', $_POST['objectClasses']) : $attributes['objectClass'];
$structuralObjectClassesCount = 0;
$schemaObjectClasses = $this->getSchemaObjectClasses();
foreach ($objectClasses as $objectClass) {
@ -1634,7 +1615,7 @@ class TreeView {
throw new LAMException(_('Entry cannot be inserted into itself.'));
}
$entryAndChildren = ldapListDN($dn);
$childrenCount = sizeof($entryAndChildren);
$childrenCount = count($entryAndChildren);
logNewMessage(LOG_DEBUG, 'Paste operation for entry with ' . $childrenCount . ' child entries.');
if (($childrenCount === 0) && ($action === 'CUT')) {
// do LDAP move for entries without children and CUT operation

View file

@ -256,21 +256,21 @@ class ConfiguredType {
$units = ldap_get_entries($connection, $sr);
cleanLDAPResult($units);
// extract Dns
$count = sizeof($units);
$count = count($units);
for ($i = 0; $i < $count; $i++) {
if (in_array('container', $units[$i]['objectclass'])) {
// Active Directory fix, hide system containers
if (preg_match('/.*cn=system,dc=.+/i', $units[$i]['dn']) || preg_match('/.*CN=program data,dc=.+/i', $units[$i]['dn'])) {
continue;
}
// Active Directory fix, hide system containers
if (in_array('container', $units[$i]['objectclass'])
&& (preg_match('/.*cn=system,dc=.+/i', $units[$i]['dn'])
|| preg_match('/.*CN=program data,dc=.+/i', $units[$i]['dn']))) {
continue;
}
$ret[] = $units[$i]['dn'];
}
}
// add root suffix if needed
$found = false;
for ($i = 0; $i < sizeof($ret); $i++) { // search suffix case-insensitive
if (strtolower($this->getSuffix()) == strtolower($ret[$i])) {
for ($i = 0; $i < count($ret); $i++) { // search suffix case-insensitive
if (strtolower($this->getSuffix()) === strtolower($ret[$i])) {
$found = true;
break;
}

View file

@ -134,7 +134,7 @@ class dhcp extends baseType {
if (isset($attributes['dhcpComments'][0])) {
$subtitle .= htmlspecialchars($attributes['dhcpComments'][0]);
}
if ($subtitle == '') {
if ($subtitle === '') {
return null;
}
return $subtitle;
@ -178,7 +178,7 @@ class lamDHCPList extends lamList {
return true;
}
$entries = searchLDAP($data['dn'], 'objectClass=dhcpHost', ['dhcpstatements', 'dhcphwaddress', 'cn']);
if (sizeof($entries) > 0) {
if (count($entries) > 0) {
foreach ($entries as $entry) {
foreach ($entry as $attrValues) {
if (!is_array($attrValues)) {
@ -191,10 +191,8 @@ class lamDHCPList extends lamList {
}
if (!empty($entry['dhcpstatements'])) {
$ip = fixed_ip::extractIP($entry['dhcpstatements']);
if (!empty($ip)) {
if (preg_match($regex, $ip)) {
return true;
}
if (!empty($ip) && preg_match($regex, $ip)) {
return true;
}
}
}

View file

@ -259,7 +259,7 @@ class lamGroupList extends lamList {
parent::listGetParams();
// generate list primary group members
// after parent::listGetParams is $this->refresh set to correct value
if ($this->include_primary && !$this->refresh && ($this->refresh_primary || (sizeof($this->primary_hash) == 0))) {
if ($this->include_primary && !$this->refresh && ($this->refresh_primary || (count($this->primary_hash) == 0))) {
$this->groupRefreshPrimary();
}
}
@ -278,13 +278,13 @@ class lamGroupList extends lamList {
if (isset($entry['gidnumber']) && is_array($entry['gidnumber'])) {
$gid = $entry['gidnumber'][0];
}
$use_primary = (($gid >= 0) && (sizeof($this->primary_hash) > 0) &&
isset($this->primary_hash[$gid]) && is_array($this->primary_hash[$gid]) &&
(sizeof($this->primary_hash[$gid]) > 0));
$use_primary = (($gid >= 0) && (count($this->primary_hash) > 0)
&& isset($this->primary_hash[$gid]) && is_array($this->primary_hash[$gid])
&& ($this->primary_hash[$gid] !== []));
}
if (!$use_primary) {
if (!isset($entry[$attribute]) || !is_array($entry[$attribute]) || (sizeof($entry[$attribute]) < 1)) {
return;
if (!isset($entry[$attribute]) || !is_array($entry[$attribute]) || (count($entry[$attribute]) < 1)) {
return null;
}
// sort array
sort($entry[$attribute]);
@ -296,17 +296,12 @@ class lamGroupList extends lamList {
// merge primary members into secondary ones
$primaryvals = array_flip(array_values($primary_hash));
// test if group has some secondary members
if (isset($entry[$attribute])) {
$attr = array_merge($primary_hash, $entry[$attribute]);
}
else {
$attr = $primary_hash;
}
$attr = isset($entry[$attribute]) ? array_merge($primary_hash, $entry[$attribute]) : $primary_hash;
// sort array
sort($attr);
// make a link for each member of the group
for ($d = 0; $d < sizeof($attr); $d++) {
for ($d = 0; $d < count($attr); $d++) {
$user = $attr[$d]; // user name
if (isAccountTypeHidden('user')) {
$linklist[$d] = $user;
@ -321,7 +316,7 @@ class lamGroupList extends lamList {
}
else {
// make a link for each member of the group
for ($d = 0; $d < sizeof($entry[$attribute]); $d++) {
for ($d = 0; $d < count($entry[$attribute]); $d++) {
$user = $entry[$attribute][$d]; // user name
if (!isAccountTypeHidden('user')) {
$linklist[$d] = "<a href=\"userlink.php?user='" . $user . "' \">" . $user . "</a>";
@ -355,7 +350,7 @@ class lamGroupList extends lamList {
function groupRefreshPrimary() {
$this->refresh_primary = false;
// return unless some entries
if (sizeof($this->ldapEntries) <= 0) {
if (count($this->ldapEntries) <= 0) {
return;
}
@ -363,14 +358,14 @@ class lamGroupList extends lamList {
// configure search filter
$module_filter = get_ldap_filter($scope); // basic filter is provided by modules
$attrs = ["uid"];
for ($i = 0; $i < sizeof($this->ldapEntries); $i++) {
for ($i = 0; $i < count($this->ldapEntries); $i++) {
if (empty($this->ldapEntries[$i]['gidnumber'][0])) {
continue;
}
$gid = $this->ldapEntries[$i]['gidnumber'][0];
$filter = "(&(&" . $module_filter . ")(gidNumber=" . $gid . "))";
$entries = searchLDAPByFilter($filter, $attrs, [$scope]);
for ($j = 0; $j < sizeof($entries); $j++) {
for ($j = 0; $j < count($entries); $j++) {
$this->primary_hash[$gid][$j] = $entries[$j]['uid'][0];
}
}

View file

@ -132,7 +132,7 @@ class netgroup extends baseType {
if (isset($attributes['description'][0])) {
$subtitle .= htmlspecialchars($attributes['description'][0]);
}
if ($subtitle == '') {
if ($subtitle === '') {
return null;
}
return $subtitle;

View file

@ -132,7 +132,7 @@ class smbDomain extends baseType {
if (isset($attributes['sambaSID'][0])) {
$subtitle .= htmlspecialchars($attributes['sambaSID'][0]);
}
if ($subtitle == '') {
if ($subtitle === '') {
return null;
}
return $subtitle;

View file

@ -191,7 +191,7 @@ class user extends baseType {
if (isset($personalAttributes['mobile'][0]) && !empty($personalAttributes['mobile'][0])) {
$subtitle .= _('Mobile number') . ' ' . htmlspecialchars($personalAttributes['mobile'][0]);
}
if ($subtitle == '') {
if ($subtitle === '') {
return null;
}
return $subtitle;
@ -238,7 +238,7 @@ class lamUserList extends lamList {
protected function listGetParams() {
parent::listGetParams();
// generate hash table for group translation
if ($this->trans_primary == "on" && !$this->refresh && (sizeof($this->trans_primary_hash) == 0)) {
if ($this->trans_primary == "on" && !$this->refresh && (count($this->trans_primary_hash) == 0)) {
$this->refreshPrimaryGroupTranslation();
}
}
@ -261,7 +261,7 @@ class lamUserList extends lamList {
$this->trans_primary_hash = [];
$attrs = ["cn", "gidNumber"];
$entries = searchLDAPByAttribute(null, null, 'posixGroup', $attrs, ['group']);
$entryCount = sizeof($entries);
$entryCount = count($entries);
for ($i = 0; $i < $entryCount; $i++) {
$this->trans_primary_hash[$entries[$i]['gidnumber'][0]] = $entries[$i]['cn'][0];
}
@ -273,7 +273,7 @@ class lamUserList extends lamList {
*/
protected function getTableCellContent(&$entry, &$attribute) {
// check if there is something to display at all
if (!isset($entry[$attribute]) || !is_array($entry[$attribute]) || (sizeof($entry[$attribute]) < 1)) {
if (!isset($entry[$attribute]) || !is_array($entry[$attribute]) || (count($entry[$attribute]) < 1)) {
return parent::getTableCellContent($entry, $attribute);
}
// translate GID to group name
@ -321,10 +321,7 @@ class lamUserList extends lamList {
* @return boolean filtering possible
*/
protected function canBeFiltered($attr) {
if (strtolower($attr) == 'jpegphoto') {
return false;
}
return true;
return strtolower($attr) !== 'jpegphoto';
}
/**

View file

@ -35,9 +35,9 @@ use accountContainer;
*/
/** LDAP handle */
include_once('ldap.inc');
include_once(__DIR__ . '/ldap.inc');
/** PDF */
include_once('pdf.inc');
include_once(__DIR__ . '/pdf.inc');
/**
* Creates LDAP accounts for file upload.
@ -55,7 +55,7 @@ class Uploader {
private const TIME_LIMIT = 10;
public static function cleanSession() {
foreach ($_SESSION as $key => &$value) {
foreach (array_keys($_SESSION) as $key) {
if (str_starts_with($key, 'mass_')) {
unset($_SESSION[$key]);
}
@ -92,7 +92,7 @@ class Uploader {
if (!isset($_SESSION['mass_counter'])) {
return $this->startUpload();
}
elseif ($_SESSION['mass_counter'] < sizeof($this->accounts)) {
elseif ($_SESSION['mass_counter'] < count($this->accounts)) {
return $this->continueUpload();
}
elseif (!isset($_SESSION['mass_postActions']['finished'])) {
@ -110,12 +110,12 @@ class Uploader {
* @return String JSON of upload status
*/
private function continueUpload() {
while (($_SESSION['mass_counter'] < sizeof($this->accounts)) && ($this->endTime > time())) {
while (($_SESSION['mass_counter'] < count($this->accounts)) && ($this->endTime > time())) {
$this->uploadEntry($_SESSION['mass_counter']);
$_SESSION['mass_counter']++;
}
$accountsProgress = round(($_SESSION['mass_counter'] * 100) / sizeof($this->accounts));
$accountsFinished = ($_SESSION['mass_counter'] == sizeof($this->accounts));
$accountsProgress = round(($_SESSION['mass_counter'] * 100) / count($this->accounts));
$accountsFinished = ($_SESSION['mass_counter'] == count($this->accounts));
return $this->buildUploadStatus($accountsProgress, $accountsFinished);
}
@ -142,7 +142,7 @@ class Uploader {
$preAttributes['dn'] = &$dn;
$preMessages = doUploadPreActions($this->type, $_SESSION['mass_selectedModules'], $preAttributes);
$preActionOk = true;
for ($i = 0; $i < sizeof($preMessages); $i++) {
for ($i = 0; $i < count($preMessages); $i++) {
if (($preMessages[$i][0] == 'ERROR') || ($preMessages[$i][0] == 'WARN')) {
$preActionOk = false;
$_SESSION['mass_errors'][] = $preMessages[$i];
@ -278,7 +278,7 @@ class Uploader {
$_SESSION['mass_postActions']['finished'] = true;
}
if (isset($return['errors'])) {
for ($i = 0; $i < sizeof($return['errors']); $i++) {
for ($i = 0; $i < count($return['errors']); $i++) {
$_SESSION['mass_errors'][] = $return['errors'][$i];
}
}
@ -298,7 +298,7 @@ class Uploader {
$tempFilesManager = new LamTemporaryFilesManager();
if ($_SESSION['mass_pdf']['counter'] == 0) {
$pdfZipResult = @$pdfZip->open($tempFilesManager->getFileSystemPath($file), ZipArchive::OVERWRITE);
if (!$pdfZipResult === true) {
if (!$pdfZipResult) {
$_SESSION['mass_errors'][] = ['ERROR', _('Unable to create ZIP file for PDF export.')];
$_SESSION['mass_pdf']['finished'] = true;
}
@ -319,7 +319,7 @@ class Uploader {
// load account
$_SESSION['mass_pdfAccount'] = new accountContainer($this->type, 'mass_pdfAccount');
$pdfErrors = $_SESSION['mass_pdfAccount']->load_account($dn, $infoAttributes);
if (sizeof($pdfErrors) > 0) {
if (count($pdfErrors) > 0) {
$_SESSION['mass_errors'] = array_merge($_SESSION['mass_errors'], $pdfErrors);
$_SESSION['mass_pdf']['finished'] = true;
break;
@ -329,12 +329,12 @@ class Uploader {
$fileName = $dn . '.pdf';
$pdfZip->addFromString($fileName, $pdfContent);
$_SESSION['mass_pdf']['counter']++;
if ($_SESSION['mass_pdf']['counter'] >= sizeof($this->accounts)) {
if ($_SESSION['mass_pdf']['counter'] >= count($this->accounts)) {
$_SESSION['mass_pdf']['finished'] = true;
}
}
@$pdfZip->close();
$progress = round(($_SESSION['mass_pdf']['counter'] * 100) / sizeof($this->accounts));
$progress = round(($_SESSION['mass_pdf']['counter'] * 100) / count($this->accounts));
return $this->buildUploadStatus(100, true, '', 100, true, $progress);
}

View file

@ -333,7 +333,7 @@ class WebauthnManager {
return new PublicKeyCredentialSourceRepositorySQLite();
}
catch (PDOException $e) {
throw new LAMException(_('Unable to connect to database.'), $e->getMessage());
throw new LAMException(_('Unable to connect to database.'), $e->getMessage(), $e);
}
}
@ -596,7 +596,7 @@ abstract class PublicKeyCredentialSourceRepositoryBase implements PublicKeyCrede
$results = $statement->fetchAll();
$devices = [];
foreach ($results as $result) {
$name = !empty($result['name']) ? $result['name'] : '';
$name = empty($result['name']) ? '' : $result['name'];
$devices[] = [
'dn' => $result['userDN'],
'credentialId' => $result['credentialId'],
@ -623,7 +623,7 @@ abstract class PublicKeyCredentialSourceRepositoryBase implements PublicKeyCrede
$results = $statement->fetchAll();
$devices = [];
foreach ($results as $result) {
$name = !empty($result['name']) ? $result['name'] : '';
$name = empty($result['name']) ? '' : $result['name'];
$devices[] = [
'dn' => $result['userDN'],
'credentialId' => $result['credentialId'],

View file

@ -76,7 +76,7 @@ foreach ($_SESSION as $key => $value) {
if (str_starts_with($key, $sessionAccountPrefix)) {
$cleanupCandidates[] = $key;
}
$candidateCount = sizeof($cleanupCandidates);
$candidateCount = count($cleanupCandidates);
if ($candidateCount > 100) {
$numToDelete = $candidateCount - 100;
natsort($cleanupCandidates);
@ -105,7 +105,7 @@ if (!empty($_GET['DN'])) {
}
$_SESSION[$sessionKey] = new accountContainer($type, $sessionKey);
$result = $_SESSION[$sessionKey]->load_account($dn);
if (sizeof($result) > 0) {
if (count($result) > 0) {
include __DIR__ . '/../../lib/adminHeader.inc';
foreach ($result as $message) {
call_user_func_array(StatusMessage(...), $message);

View file

@ -47,9 +47,9 @@ use ZipArchive;
/** Access to persistence functions */
include_once('../../lib/persistence.inc');
include_once(__DIR__ . '/../../lib/persistence.inc');
/** account modules */
include_once('../../lib/modules.inc');
include_once(__DIR__ . '/../../lib/modules.inc');
// start session
if (isFileBasedSession()) {
@ -271,7 +271,7 @@ printHeaderContents(_("Import and export configuration"), '../..');
$tmpFile = __DIR__ . '/../../tmp/internal/import_' . generateRandomText() . '.tmp';
$file = @fopen($tmpFile, "w");
if ($file) {
fputs($file, $data);
fwrite($file, $data);
fclose($file);
chmod($tmpFile, 0600);
}

View file

@ -1,5 +1,6 @@
<?php
namespace LAM\CONFIG;
use \htmlStatusMessage;
use \htmlResponsiveRow;
use \LAMCfgMain;
@ -35,17 +36,17 @@ use ServerProfilePersistenceManager;
/**
* Login page to change the preferences.
*
* @package configuration
* @author Roland Gruber
*/
* Login page to change the preferences.
*
* @package configuration
* @author Roland Gruber
*/
/** Access to config functions */
include_once('../../lib/config.inc');
include_once(__DIR__ . '/../../lib/config.inc');
/** Used to print status messages */
include_once('../../lib/status.inc');
include_once(__DIR__ . '/../../lib/status.inc');
// start session
if (isFileBasedSession()) {
@ -64,8 +65,10 @@ if (isset($_SESSION['conf_message'])) {
// remove settings from session
$sessionKeys = array_keys($_SESSION);
for ($i = 0; $i < sizeof($sessionKeys); $i++) {
if (str_starts_with($sessionKeys[$i], "conf_")) unset($_SESSION[$sessionKeys[$i]]);
for ($i = 0; $i < count($sessionKeys); $i++) {
if (str_starts_with($sessionKeys[$i], "conf_")) {
unset($_SESSION[$sessionKeys[$i]]);
}
}
echo $_SESSION['header'];
@ -80,101 +83,102 @@ catch (LAMException $e) {
}
printHeaderContents(_("Login"), '../..');
if (sizeof($files) < 1) {
if (count($files) < 1) {
$message = new htmlStatusMessage('INFO', _("No server profiles found. Please create one."));
}
?>
</head>
<body>
<?php
printJsIncludes('../..');
?>
<div id="lam-topnav" class="lam-header">
<div class="lam-header-left lam-menu-stay">
<a href="https://www.ldap-account-manager.org/" target="new_window">
<img class="align-middle" width="24" height="24" alt="help" src="../../graphics/logo24.png">
<span class="hide-on-mobile">
</head>
<body>
<?php
printJsIncludes('../..');
?>
<div id="lam-topnav" class="lam-header">
<div class="lam-header-left lam-menu-stay">
<a href="https://www.ldap-account-manager.org/" target="new_window">
<img class="align-middle" width="24" height="24" alt="help" src="../../graphics/logo24.png">
<span class="hide-on-mobile">
<?php
echo getLAMVersionText();
?>
echo getLAMVersionText();
?>
</span>
</a>
</div>
<?php
if (is_dir(__DIR__ . '/../../docs/manual')) {
?>
<a class="lam-header-right lam-menu-icon hide-on-tablet" href="javascript:void(0);" class="icon" onclick="window.lam.topmenu.toggle();">
<img class="align-middle" width="16" height="16" alt="menu" src="../../graphics/menu.svg">
<span class="padding0">&nbsp;</span>
</a>
<a class="lam-header-right lam-menu-entry" target="_blank" href="../../docs/manual/index.html">
<span class="padding0"><?php echo _("Help") ?></span>
</a>
<?php
}
?>
</div>
<br><br>
<!-- form to change existing profiles -->
<form action="confmain.php" method="post" autocomplete="off">
<?php
$row = new htmlResponsiveRow();
// message
if ($message !== null) {
$row->add($message, 12);
$row->addVerticalSpacer('2rem');
}
$box = new htmlResponsiveRow();
if (sizeof($files) > 0) {
$box->add(new htmlOutputText(_("Please enter your password to change the server preferences:")), 12);
$box->addVerticalSpacer('1.5rem');
$conf = new LAMCfgMain();
$selectedProfile = [];
$profilesExisting = false;
$profiles = $files;
if (!empty($_COOKIE["lam_default_profile"]) && in_array($_COOKIE["lam_default_profile"], $files)) {
$selectedProfile[] = $_COOKIE["lam_default_profile"];
}
else {
$selectedProfile[] = $conf->default;
}
$box->add(new htmlResponsiveSelect('filename', $profiles, $selectedProfile, _('Profile name')), 12);
$passwordInput = new htmlResponsiveInputField(_('Password'), 'passwd', '', '200');
$passwordInput->setIsPassword(true);
$passwordInput->setCSSClasses(['lam-initial-focus']);
$box->add($passwordInput, 12);
$box->addVerticalSpacer('1rem');
$button = new htmlButton('submit', _("Ok"));
$button->setCSSClasses(['lam-primary']);
$box->addLabel($button);
$box->add(new htmlOutputText(''), 0, 6);
$box->addVerticalSpacer('1.5rem');
$box->add(new htmlHorizontalLine(), 12);
$box->addVerticalSpacer('1.5rem');
}
$manageLink = new htmlLink(_("Manage server profiles"), 'profmanage.php');
$box->add($manageLink, 12, 12, 12, 'text-center');
$boxDiv = new htmlDiv(null, $box);
$boxDiv->setCSSClasses(['roundedShadowBox', 'limitWidth', 'text-center']);
$row->add($boxDiv, 12);
// back link
$row->addVerticalSpacer('2rem');
$backLink = new htmlLink(_("Back to login"), '../login.php');
$row->add($backLink, 12, 12, 12, 'text-left');
parseHtml(null, new htmlDiv(null, $row, ['centeredTable']), [], false, 'user');
</a>
</div>
<?php
if (is_dir(__DIR__ . '/../../docs/manual')) {
?>
</form>
<a class="lam-header-right lam-menu-icon hide-on-tablet" href="javascript:void(0);" class="icon"
onclick="window.lam.topmenu.toggle();">
<img class="align-middle" width="16" height="16" alt="menu" src="../../graphics/menu.svg">
<span class="padding0">&nbsp;</span>
</a>
<a class="lam-header-right lam-menu-entry" target="_blank" href="../../docs/manual/index.html">
<span class="padding0"><?php echo _("Help") ?></span>
</a>
<?php
}
?>
</div>
<br><br>
<!-- form to change existing profiles -->
<form action="confmain.php" method="post" autocomplete="off">
<p><br><br></p>
<?php
$row = new htmlResponsiveRow();
// message
if ($message !== null) {
$row->add($message, 12);
$row->addVerticalSpacer('2rem');
}
$box = new htmlResponsiveRow();
if (count($files) > 0) {
$box->add(new htmlOutputText(_("Please enter your password to change the server preferences:")), 12);
$box->addVerticalSpacer('1.5rem');
$conf = new LAMCfgMain();
$selectedProfile = [];
$profilesExisting = false;
$profiles = $files;
if (!empty($_COOKIE["lam_default_profile"]) && in_array($_COOKIE["lam_default_profile"], $files)) {
$selectedProfile[] = $_COOKIE["lam_default_profile"];
}
else {
$selectedProfile[] = $conf->default;
}
$box->add(new htmlResponsiveSelect('filename', $profiles, $selectedProfile, _('Profile name')), 12);
$passwordInput = new htmlResponsiveInputField(_('Password'), 'passwd', '', '200');
$passwordInput->setIsPassword(true);
$passwordInput->setCSSClasses(['lam-initial-focus']);
$box->add($passwordInput, 12);
$box->addVerticalSpacer('1rem');
$button = new htmlButton('submit', _("Ok"));
$button->setCSSClasses(['lam-primary']);
$box->addLabel($button);
$box->add(new htmlOutputText(''), 0, 6);
$box->addVerticalSpacer('1.5rem');
$box->add(new htmlHorizontalLine(), 12);
$box->addVerticalSpacer('1.5rem');
}
$manageLink = new htmlLink(_("Manage server profiles"), 'profmanage.php');
$box->add($manageLink, 12, 12, 12, 'text-center');
$boxDiv = new htmlDiv(null, $box);
$boxDiv->setCSSClasses(['roundedShadowBox', 'limitWidth', 'text-center']);
$row->add($boxDiv, 12);
// back link
$row->addVerticalSpacer('2rem');
$backLink = new htmlLink(_("Back to login"), '../login.php');
$row->add($backLink, 12, 12, 12, 'text-left');
parseHtml(null, new htmlDiv(null, $row, ['centeredTable']), [], false, 'user');
?>
</form>
<p><br><br></p>
</body>
</body>
</html>

View file

@ -1,5 +1,7 @@
<?php
namespace LAM\CONFIG;
use \LAM\LIB\TWO_FACTOR\TwoFactorProviderService;
use \LAMConfig;
use \htmlTable;
@ -45,12 +47,12 @@ use ServerProfilePersistenceManager;
/**
* Main page of configuration
*
* @package configuration
* @author Roland Gruber
* @author Thomas Manninger
*/
* Main page of configuration
*
* @package configuration
* @author Roland Gruber
* @author Thomas Manninger
*/
/** Access to config functions */
@ -92,7 +94,8 @@ $serverProfilePersistenceManager = new ServerProfilePersistenceManager();
if (!isset($_SESSION['conf_config']) && isset($_POST['filename'])) {
try {
$_SESSION['conf_config'] = $serverProfilePersistenceManager->loadProfile($_POST['filename']);
} catch (LAMException $e) {
}
catch (LAMException $e) {
$_SESSION['conf_message'] = new htmlStatusMessage('ERROR', $e->getTitle());
metaRefresh('conflogin.php');
exit;
@ -102,9 +105,10 @@ $conf = &$_SESSION['conf_config'];
// check if password is valid
// if not: load login page
if ((!isset($_SESSION['conf_isAuthenticated']) || !($_SESSION['conf_isAuthenticated'] === $conf->getName())) && !$conf->check_Passwd($passwd)) {
if ((!isset($_SESSION['conf_isAuthenticated']) || ($_SESSION['conf_isAuthenticated'] !== $conf->getName()))
&& !$conf->check_Passwd($passwd)) {
$sessionKeys = array_keys($_SESSION);
for ($i = 0; $i < sizeof($sessionKeys); $i++) {
for ($i = 0; $i < count($sessionKeys); $i++) {
if (str_starts_with($sessionKeys[$i], "conf_")) {
unset($_SESSION[$sessionKeys[$i]]);
}
@ -133,29 +137,29 @@ if (isset($_POST['saveSettings']) || isset($_POST['editmodules'])
|| isset($_POST['edittypes']) || isset($_POST['generalSettingsButton'])
|| isset($_POST['moduleSettings']) || isset($_POST['jobs'])) {
$errorsToDisplay = checkInput();
if (sizeof($errorsToDisplay) == 0) {
if (count($errorsToDisplay) == 0) {
// go to final page
if (isset($_POST['saveSettings'])) {
metaRefresh("confsave.php");
exit;
}
// go to modules page
elseif (isset($_POST['editmodules'])) {
elseif (isset($_POST['editmodules'])) {
metaRefresh("confmodules.php");
exit;
}
// go to types page
elseif (isset($_POST['edittypes'])) {
elseif (isset($_POST['edittypes'])) {
metaRefresh("conftypes.php");
exit;
}
// go to module settings page
elseif (isset($_POST['moduleSettings'])) {
elseif (isset($_POST['moduleSettings'])) {
metaRefresh("moduleSettings.php");
exit;
}
// go to jobs page
elseif (isset($_POST['jobs'])) {
elseif (isset($_POST['jobs'])) {
metaRefresh("jobs.php");
exit;
}
@ -177,8 +181,8 @@ if (!$serverProfilePersistenceManager->isWritable($_SESSION['conf_config']->getN
}
// display error messages
if (sizeof($errorsToDisplay) > 0) {
for ($i = 0; $i < sizeof($errorsToDisplay); $i++) {
if ($errorsToDisplay !== []) {
for ($i = 0; $i < count($errorsToDisplay); $i++) {
call_user_func_array(StatusMessage(...), $errorsToDisplay[$i]);
}
echo "<br>";
@ -190,10 +194,10 @@ echo "<form enctype=\"multipart/form-data\" action=\"confmain.php\" method=\"pos
printConfigurationPageTabs(ConfigurationPageTab::GENERAL);
?>
<input type="text" name="hiddenPreventAutocomplete" autocomplete="false" class="hidden" value="">
<input type="password" name="hiddenPreventAutocompletePwd1" autocomplete="false" class="hidden" value="123">
<input type="password" name="hiddenPreventAutocompletePwd2" autocomplete="false" class="hidden" value="321">
<?php
<input type="text" name="hiddenPreventAutocomplete" autocomplete="false" class="hidden" value="">
<input type="password" name="hiddenPreventAutocompletePwd1" autocomplete="false" class="hidden" value="123">
<input type="password" name="hiddenPreventAutocompletePwd2" autocomplete="false" class="hidden" value="321">
<?php
$row = new htmlResponsiveRow();
@ -210,14 +214,14 @@ $tlsSelect->setHasDescriptiveElements(true);
$row->add($tlsSelect, 12);
// LDAP search limit
$searchLimitOptions = [
'-' => 0,
100 => 100,
500 => 500,
1000 => 1000,
5000 => 5000,
10000 => 10000,
50000 => 50000,
100000 => 100000
'-' => 0,
100 => 100,
500 => 500,
1000 => 1000,
5000 => 5000,
10000 => 10000,
50000 => 50000,
100000 => 100000
];
$limitSelect = new htmlResponsiveSelect('searchLimit', $searchLimitOptions, [$conf->get_searchLimit()], _("LDAP search limit"), '222');
$limitSelect->setHasDescriptiveElements(true);
@ -229,10 +233,10 @@ $row->add($urlInput, 12);
// access level is only visible in Pro version
if (isLAMProVersion()) {
$accessOptions = [
_('Write access') => LAMConfig::ACCESS_ALL,
_('Change passwords') => LAMConfig::ACCESS_PASSWORD_CHANGE,
_('Read-only') => LAMConfig::ACCESS_READ_ONLY
];
_('Write access') => LAMConfig::ACCESS_ALL,
_('Change passwords') => LAMConfig::ACCESS_PASSWORD_CHANGE,
_('Read-only') => LAMConfig::ACCESS_READ_ONLY
];
$accessSelect = new htmlResponsiveSelect('accessLevel', $accessOptions, [$conf->getAccessLevel()], _("Access level"), '215');
$accessSelect->setHasDescriptiveElements(true);
$row->add($accessSelect, 12);
@ -241,18 +245,18 @@ if (isLAMProVersion()) {
$row->addVerticalSpacer('1rem');
// login method
$loginOptions = [
_('Fixed list') => LAMConfig::LOGIN_LIST,
_('LDAP search') => LAMConfig::LOGIN_SEARCH
_('Fixed list') => LAMConfig::LOGIN_LIST,
_('LDAP search') => LAMConfig::LOGIN_SEARCH
];
$loginSelect = new htmlResponsiveSelect('loginMethod', $loginOptions, [$conf->getLoginMethod()], _("Login method"), '220');
$loginSelect->setHasDescriptiveElements(true);
$loginSelect->setTableRowsToHide([
LAMConfig::LOGIN_LIST => ['loginSearchSuffix', 'loginSearchFilter', 'loginSearchDN', 'loginSearchPassword', 'httpAuthentication'],
LAMConfig::LOGIN_SEARCH => ['admins']
LAMConfig::LOGIN_LIST => ['loginSearchSuffix', 'loginSearchFilter', 'loginSearchDN', 'loginSearchPassword', 'httpAuthentication'],
LAMConfig::LOGIN_SEARCH => ['admins']
]);
$loginSelect->setTableRowsToShow([
LAMConfig::LOGIN_LIST => ['admins'],
LAMConfig::LOGIN_SEARCH => ['loginSearchSuffix', 'loginSearchFilter', 'loginSearchDN', 'loginSearchPassword', 'httpAuthentication']
LAMConfig::LOGIN_LIST => ['admins'],
LAMConfig::LOGIN_SEARCH => ['loginSearchSuffix', 'loginSearchFilter', 'loginSearchDN', 'loginSearchPassword', 'httpAuthentication']
]);
$row->add($loginSelect);
// admin list
@ -284,13 +288,13 @@ $advancedOptionsContent = new htmlResponsiveRow();
$advancedOptionsContent->add(new htmlResponsiveInputField(_('Display name'), 'serverDisplayName', $conf->getServerDisplayName(), '268'), 12);
// referrals
$followReferrals = ($conf->getFollowReferrals() === 'true');
$advancedOptionsContent->add(new htmlResponsiveInputCheckbox('followReferrals', $followReferrals , _('Follow referrals'), '205'), 12);
$advancedOptionsContent->add(new htmlResponsiveInputCheckbox('followReferrals', $followReferrals, _('Follow referrals'), '205'), 12);
// paged results
$pagedResults = ($conf->getPagedResults() === 'true');
$advancedOptionsContent->add(new htmlResponsiveInputCheckbox('pagedResults', $pagedResults , _('Paged results'), '266'), 12);
$advancedOptionsContent->add(new htmlResponsiveInputCheckbox('pagedResults', $pagedResults, _('Paged results'), '266'), 12);
// referential integrity overlay
$referentialIntegrity = ($conf->isReferentialIntegrityOverlayActive());
$advancedOptionsContent->add(new htmlResponsiveInputCheckbox('referentialIntegrityOverlay', $referentialIntegrity , _('Referential integrity overlay'), '269'), 12);
$advancedOptionsContent->add(new htmlResponsiveInputCheckbox('referentialIntegrityOverlay', $referentialIntegrity, _('Referential integrity overlay'), '269'), 12);
// hide password prompt for expired passwords
$hidePasswordPromptForExpiredPasswords = ($conf->isHidePasswordPromptForExpiredPasswords());
$advancedOptionsContent->add(new htmlResponsiveInputCheckbox('hidePasswordPromptForExpiredPasswords', $hidePasswordPromptForExpiredPasswords, _('Hide password prompt for expired password'), '291'), 12);
@ -308,7 +312,7 @@ $row->add(new htmlSubTitle(_("Language settings"), '../../graphics/language.svg'
$possibleLanguages = getLanguages();
$defaultLanguage = ['en_GB.utf8'];
if (!empty($possibleLanguages)) {
$languages = [];
$languages = [];
foreach ($possibleLanguages as $lang) {
$languages[$lang->description] = $lang->code;
if (str_starts_with($conf->get_defaultLanguage(), $lang->code)) {
@ -339,7 +343,7 @@ $row->add(new htmlResponsiveSelect('timeZone', $timezones, [$conf->getTimeZone()
$row->addVerticalSpacer('2rem');
// tool settings
$row->add(new htmlSubTitle(_("Tool settings"), '../../graphics/configure.svg',null, true), 12);
$row->add(new htmlSubTitle(_("Tool settings"), '../../graphics/configure.svg', null, true), 12);
$toolSettings = $conf->getToolSettings();
$tools = getTools();
$row->add(new htmlOutputText(_('Hidden tools')), 12);
@ -389,25 +393,25 @@ if (isLAMProVersion()) {
if ($conf->getPwdResetAllowSpecificPassword() == 'false') {
$pwdResetAllowSpecific = false;
}
$row->add(new htmlResponsiveInputCheckbox('pwdResetAllowSpecificPassword', $pwdResetAllowSpecific , _('Allow setting specific passwords'), '280'), 12);
$row->add(new htmlResponsiveInputCheckbox('pwdResetAllowSpecificPassword', $pwdResetAllowSpecific, _('Allow setting specific passwords'), '280'), 12);
$pwdResetAllowScreenPassword = true;
if ($conf->getPwdResetAllowScreenPassword() == 'false') {
$pwdResetAllowScreenPassword = false;
}
$row->add(new htmlResponsiveInputCheckbox('pwdResetAllowScreenPassword', $pwdResetAllowScreenPassword , _('Allow to display password on screen'), '281'), 12);
$row->add(new htmlResponsiveInputCheckbox('pwdResetAllowScreenPassword', $pwdResetAllowScreenPassword, _('Allow to display password on screen'), '281'), 12);
$pwdResetForcePasswordChange = true;
if ($conf->getPwdResetForcePasswordChange() == 'false') {
$pwdResetForcePasswordChange = false;
}
$row->add(new htmlResponsiveInputCheckbox('pwdResetForcePasswordChange', $pwdResetForcePasswordChange , _('Force password change by default'), '283'), 12);
$row->add(new htmlResponsiveInputCheckbox('pwdResetForcePasswordChange', $pwdResetForcePasswordChange, _('Force password change by default'), '283'), 12);
$pwdResetDefaultPasswordOutputOptions = [
_('Display on screen') => LAMConfig::PWDRESET_DEFAULT_SCREEN,
_('Send via mail') => LAMConfig::PWDRESET_DEFAULT_MAIL,
_('Both') => LAMConfig::PWDRESET_DEFAULT_BOTH
];
_('Display on screen') => LAMConfig::PWDRESET_DEFAULT_SCREEN,
_('Send via mail') => LAMConfig::PWDRESET_DEFAULT_MAIL,
_('Both') => LAMConfig::PWDRESET_DEFAULT_BOTH
];
$pwdResetDefaultPasswordOutputSelect = new htmlResponsiveSelect('pwdResetDefaultPasswordOutput', $pwdResetDefaultPasswordOutputOptions, [$conf->getPwdResetDefaultPasswordOutput()], _("Default password output"), '282');
$pwdResetDefaultPasswordOutputSelect->setHasDescriptiveElements(true);
$row->add($pwdResetDefaultPasswordOutputSelect, 12);
@ -430,13 +434,13 @@ if (isLAMProVersion()) {
if ($conf->getLamProMailIsHTML() == 'true') {
$pwdMailIsHTML = true;
}
$row->add(new htmlResponsiveInputCheckbox('pwdResetMail_isHTML',$pwdMailIsHTML , _('HTML format'), '553'), 12);
$row->add(new htmlResponsiveInputCheckbox('pwdResetMail_isHTML', $pwdMailIsHTML, _('HTML format'), '553'), 12);
$pwdMailAllowAlternate = true;
if ($conf->getLamProMailAllowAlternateAddress() == 'false') {
$pwdMailAllowAlternate = false;
}
$row->add(new htmlResponsiveInputCheckbox('pwdResetMail_allowAlternate',$pwdMailAllowAlternate , _('Allow alternate address'), '555'), 12);
$row->add(new htmlResponsiveInputCheckbox('pwdResetMail_allowAlternate', $pwdMailAllowAlternate, _('Allow alternate address'), '555'), 12);
$pwdMailBody = new htmlResponsiveInputTextarea('pwdResetMail_body', $conf->getLamProMailText(), 50, 4, _('Text'), '552');
$row->add($pwdMailBody, 12);
@ -469,17 +473,17 @@ $rightsTable->addElement(new htmlOutputText(_("Read")));
$rightsTable->addElement(new htmlOutputText(_("Write")));
$rightsTable->addElement(new htmlOutputText(_("Execute")), true);
$rightsTable->addElement(new htmlOutputText(_("Owner")));
$rightsTable->addElement(new htmlInputCheckbox('chmod_owr', checkChmod("read","owner", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_oww', checkChmod("write","owner", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_owe', checkChmod("execute","owner", $chmod)), true);
$rightsTable->addElement(new htmlInputCheckbox('chmod_owr', checkChmod("read", "owner", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_oww', checkChmod("write", "owner", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_owe', checkChmod("execute", "owner", $chmod)), true);
$rightsTable->addElement(new htmlOutputText(_("Group")));
$rightsTable->addElement(new htmlInputCheckbox('chmod_grr', checkChmod("read","group", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_grw', checkChmod("write","group", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_gre', checkChmod("execute","group", $chmod)), true);
$rightsTable->addElement(new htmlInputCheckbox('chmod_grr', checkChmod("read", "group", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_grw', checkChmod("write", "group", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_gre', checkChmod("execute", "group", $chmod)), true);
$rightsTable->addElement(new htmlOutputText(_("Other")));
$rightsTable->addElement(new htmlInputCheckbox('chmod_otr', checkChmod("read","other", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_otw', checkChmod("write","other", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_ote', checkChmod("execute","other", $chmod)), true);
$rightsTable->addElement(new htmlInputCheckbox('chmod_otr', checkChmod("read", "other", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_otw', checkChmod("write", "other", $chmod)));
$rightsTable->addElement(new htmlInputCheckbox('chmod_ote', checkChmod("execute", "other", $chmod)), true);
$row->addField($rightsTable);
$row->addVerticalSpacer('2rem');
@ -502,45 +506,45 @@ $row->add(new htmlResponsiveSelect('pwdPolicyMinSymbolic', $optionsPwdLength, [$
if (extension_loaded('curl')) {
$row->add(new htmlSubTitle(_("2-factor authentication"), '../../graphics/locked.svg'), 12);
$twoFactorOptions = [
_('None') => TwoFactorProviderService::TWO_FACTOR_NONE,
'privacyIDEA' => TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA,
'YubiKey' => TwoFactorProviderService::TWO_FACTOR_YUBICO,
'Duo' => TwoFactorProviderService::TWO_FACTOR_DUO,
'Okta' => TwoFactorProviderService::TWO_FACTOR_OKTA,
'OpenId' => TwoFactorProviderService::TWO_FACTOR_OPENID,
'WebAuthn' => TwoFactorProviderService::TWO_FACTOR_WEBAUTHN
];
_('None') => TwoFactorProviderService::TWO_FACTOR_NONE,
'privacyIDEA' => TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA,
'YubiKey' => TwoFactorProviderService::TWO_FACTOR_YUBICO,
'Duo' => TwoFactorProviderService::TWO_FACTOR_DUO,
'Okta' => TwoFactorProviderService::TWO_FACTOR_OKTA,
'OpenId' => TwoFactorProviderService::TWO_FACTOR_OPENID,
'WebAuthn' => TwoFactorProviderService::TWO_FACTOR_WEBAUTHN
];
$twoFactorSelect = new htmlResponsiveSelect('twoFactor', $twoFactorOptions, [$conf->getTwoFactorAuthentication()], _('Provider'), '514');
$twoFactorSelect->setHasDescriptiveElements(true);
$twoFactorSelect->setTableRowsToHide([
TwoFactorProviderService::TWO_FACTOR_NONE => ['twoFactorURL', 'twoFactorURLs', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorOptional', 'twoFactorCaption', 'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorAttribute',
'twoFactorDomain', 'twoFactorAllowToRememberDeviceOptions'],
TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA => ['twoFactorURLs', 'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorDomain'],
TwoFactorProviderService::TWO_FACTOR_YUBICO => ['twoFactorURL', 'twoFactorAttribute', 'twoFactorDomain'],
TwoFactorProviderService::TWO_FACTOR_DUO => ['twoFactorURLs', 'twoFactorOptional', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorDomain', 'twoFactorAllowToRememberDeviceOptions'],
TwoFactorProviderService::TWO_FACTOR_OKTA => ['twoFactorURLs', 'twoFactorOptional', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorDomain', 'twoFactorAllowToRememberDeviceOptions'],
TwoFactorProviderService::TWO_FACTOR_OPENID => ['twoFactorURLs', 'twoFactorOptional', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorDomain', 'twoFactorAllowToRememberDeviceOptions'],
TwoFactorProviderService::TWO_FACTOR_WEBAUTHN => ['twoFactorURL', 'twoFactorURLs', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorCaption', 'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorAttribute']
]);
TwoFactorProviderService::TWO_FACTOR_NONE => ['twoFactorURL', 'twoFactorURLs', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorOptional', 'twoFactorCaption', 'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorAttribute',
'twoFactorDomain', 'twoFactorAllowToRememberDeviceOptions'],
TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA => ['twoFactorURLs', 'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorDomain'],
TwoFactorProviderService::TWO_FACTOR_YUBICO => ['twoFactorURL', 'twoFactorAttribute', 'twoFactorDomain'],
TwoFactorProviderService::TWO_FACTOR_DUO => ['twoFactorURLs', 'twoFactorOptional', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorDomain', 'twoFactorAllowToRememberDeviceOptions'],
TwoFactorProviderService::TWO_FACTOR_OKTA => ['twoFactorURLs', 'twoFactorOptional', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorDomain', 'twoFactorAllowToRememberDeviceOptions'],
TwoFactorProviderService::TWO_FACTOR_OPENID => ['twoFactorURLs', 'twoFactorOptional', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorDomain', 'twoFactorAllowToRememberDeviceOptions'],
TwoFactorProviderService::TWO_FACTOR_WEBAUTHN => ['twoFactorURL', 'twoFactorURLs', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorCaption', 'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorAttribute']
]);
$twoFactorSelect->setTableRowsToShow([
TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA => ['twoFactorURL', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorOptional', 'twoFactorCaption', 'twoFactorAttribute', 'twoFactorAllowToRememberDeviceOptions'],
TwoFactorProviderService::TWO_FACTOR_YUBICO => ['twoFactorURLs', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorOptional', 'twoFactorCaption', 'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorAllowToRememberDeviceOptions'],
TwoFactorProviderService::TWO_FACTOR_DUO => ['twoFactorURL', 'twoFactorLabel', 'twoFactorCaption',
'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorAttribute'],
TwoFactorProviderService::TWO_FACTOR_OKTA => ['twoFactorURL', 'twoFactorCaption', 'twoFactorClientId',
'twoFactorSecretKey', 'twoFactorAttribute'],
TwoFactorProviderService::TWO_FACTOR_OPENID => ['twoFactorURL', 'twoFactorCaption', 'twoFactorClientId',
'twoFactorSecretKey', 'twoFactorAttribute'],
TwoFactorProviderService::TWO_FACTOR_WEBAUTHN => ['twoFactorDomain', 'twoFactorOptional',
'twoFactorAllowToRememberDeviceOptions']
]);
TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA => ['twoFactorURL', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorOptional', 'twoFactorCaption', 'twoFactorAttribute', 'twoFactorAllowToRememberDeviceOptions'],
TwoFactorProviderService::TWO_FACTOR_YUBICO => ['twoFactorURLs', 'twoFactorInsecure', 'twoFactorLabel',
'twoFactorOptional', 'twoFactorCaption', 'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorAllowToRememberDeviceOptions'],
TwoFactorProviderService::TWO_FACTOR_DUO => ['twoFactorURL', 'twoFactorLabel', 'twoFactorCaption',
'twoFactorClientId', 'twoFactorSecretKey', 'twoFactorAttribute'],
TwoFactorProviderService::TWO_FACTOR_OKTA => ['twoFactorURL', 'twoFactorCaption', 'twoFactorClientId',
'twoFactorSecretKey', 'twoFactorAttribute'],
TwoFactorProviderService::TWO_FACTOR_OPENID => ['twoFactorURL', 'twoFactorCaption', 'twoFactorClientId',
'twoFactorSecretKey', 'twoFactorAttribute'],
TwoFactorProviderService::TWO_FACTOR_WEBAUTHN => ['twoFactorDomain', 'twoFactorOptional',
'twoFactorAllowToRememberDeviceOptions']
]);
$row->add($twoFactorSelect);
$twoFactorAttribute = new htmlResponsiveInputField(_("User name attribute"), 'twoFactorAttribute', $conf->getTwoFactorAuthenticationAttribute(), '528');
$row->add($twoFactorAttribute);
@ -608,11 +612,11 @@ $buttonContainer->addElement(new htmlSpacer(null, '10px'), true);
parseHtml(null, $buttonContainer, [], false, 'user');
?>
</form>
<script type="text/javascript" src="../lib/extra/jodit/jodit.js"></script>
</body>
</html>
<?php
</form>
<script type="text/javascript" src="../lib/extra/jodit/jodit.js"></script>
</body>
</html>
<?php
/**
* Checks user input and saves the entered settings.
@ -650,12 +654,12 @@ function checkInput(): array {
else {
$conf->setReferentialIntegrityOverlay('false');
}
if (isset($_POST['hidePasswordPromptForExpiredPasswords']) && ($_POST['hidePasswordPromptForExpiredPasswords'] == 'on')) {
$conf->setHidePasswordPromptForExpiredPasswords('true');
}
else {
$conf->setHidePasswordPromptForExpiredPasswords('false');
}
if (isset($_POST['hidePasswordPromptForExpiredPasswords']) && ($_POST['hidePasswordPromptForExpiredPasswords'] == 'on')) {
$conf->setHidePasswordPromptForExpiredPasswords('true');
}
else {
$conf->setHidePasswordPromptForExpiredPasswords('false');
}
$conf->set_searchLimit($_POST['searchLimit']);
$conf->setHideDnPart($_POST['hideDnPart']);
if (isLAMProVersion()) {
@ -684,7 +688,7 @@ function checkInput(): array {
}
if (!empty($_POST['pwdResetMail_subject']) && empty($_POST['pwdResetMail_from'])) {
$errors[] = ["ERROR", _("From address for password mails is invalid."), htmlspecialchars($_POST['pwdResetMail_from'])];
}
}
if (!$conf->setLamProMailReplyTo($_POST['pwdResetMail_replyTo'])) {
$errors[] = ["ERROR", _("Reply-to address for password mails is invalid."), htmlspecialchars($_POST['pwdResetMail_replyTo'])];
}
@ -706,9 +710,9 @@ function checkInput(): array {
$adminText = $_POST['admins'];
$adminText = explode("\n", $adminText);
$adminTextNew = [];
for ($i = 0; $i < sizeof($adminText); $i++) {
if (trim($adminText[$i]) == "") {
continue;
for ($i = 0; $i < count($adminText); $i++) {
if (trim($adminText[$i]) === "") {
continue;
}
$adminTextNew[] = trim($adminText[$i]);
}
@ -717,10 +721,10 @@ function checkInput(): array {
$conf->setLoginSearchSuffix($_POST['loginSearchSuffix']);
$conf->setLoginSearchPassword($_POST['loginSearchPassword']);
$conf->setLoginSearchDN($_POST['loginSearchDN']);
if ($_POST['loginMethod'] == LAMConfig::LOGIN_SEARCH) { // check only if search method
if (!$conf->setLoginSearchDN($_POST['loginSearchDN'])) {
$errors[] = ["ERROR", _("Please enter a valid bind user.")];
}
// check only if search method
if (($_POST['loginMethod'] == LAMConfig::LOGIN_SEARCH)
&& !$conf->setLoginSearchDN($_POST['loginSearchDN'])) {
$errors[] = ["ERROR", _("Please enter a valid bind user.")];
}
if (isset($_POST['httpAuthentication']) && ($_POST['httpAuthentication'] == 'on')) {
$conf->setHttpAuthentication('true');
@ -779,7 +783,7 @@ function checkInput(): array {
$conf->setScriptSSHKey($_POST['scriptkey']);
$conf->setScriptSSHKeyPassword($_POST['scriptkeypassword']);
if (!empty($_POST['scriptkey'])) {
include_once '../../lib/remote.inc';
include_once __DIR__ . '/../../lib/remote.inc';
$remote = new \LAM\REMOTE\Remote();
try {
$remote->loadKey($conf->getScriptSSHKey(), $conf->getScriptSSHKeyPassword());
@ -792,30 +796,25 @@ function checkInput(): array {
$tools = getTools();
$toolSettings = extractConfigOptionsFromPOST($_SESSION['confmain_toolTypes']);
foreach ($toolSettings as $key => $value) {
$toolSettings[$key] = implode(LAMConfig::LINE_SEPARATOR, $value);
}
$toolSettings[$key] = implode(LAMConfig::LINE_SEPARATOR, $value);
}
foreach ($tools as $tool) {
$toolClass = $tool::class;
if ($toolClass === false) {
continue;
}
$toolName = substr($toolClass, strrpos($toolClass, '\\') + 1);
$toolClass = $tool::class;
if ($toolClass === false) {
continue;
}
$toolName = substr($toolClass, strrpos($toolClass, '\\') + 1);
$toolConfigID = 'tool_hide_' . $toolName;
if ((isset($_POST[$toolConfigID])) && ($_POST[$toolConfigID] == 'on')) {
$toolSettings[$toolConfigID] = 'true';
}
else {
$toolSettings[$toolConfigID] = 'false';
}
$toolSettings[$toolConfigID] = (isset($_POST[$toolConfigID])) && ($_POST[$toolConfigID] == 'on') ? 'true' : 'false';
$toolErrors = $tool->checkConfigurationOptions($toolSettings);
if (!empty($toolErrors)) {
$errors = array_merge($errors, $toolErrors);
}
$errors = array_merge($errors, $toolErrors);
}
}
$conf->setToolSettings($toolSettings);
// password policy override
$conf->setPwdPolicyMinLength($_POST['pwdPolicyMinLength']);
$conf->setPwdPolicyMinLength($_POST['pwdPolicyMinLength']);
$conf->setPwdPolicyMinLowercase($_POST['pwdPolicyMinLowercase']);
$conf->setPwdPolicyMinUppercase($_POST['pwdPolicyMinUppercase']);
$conf->setPwdPolicyMinNumeric($_POST['pwdPolicyMinNumeric']);

View file

@ -1,5 +1,7 @@
<?php
namespace LAM\CONFIG;
use htmlInputField;
use htmlJavaScript;
use \htmlTable;
@ -15,6 +17,7 @@ use \htmlSubTitle;
use \htmlDiv;
use \htmlResponsiveRow;
use \htmlGroup;
/*
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2004 - 2024 Roland Gruber
@ -36,20 +39,20 @@ use \htmlGroup;
*/
/**
* confmodules lets the user select the account modules
*
* @package configuration
* @author Roland Gruber
*/
/**
* confmodules lets the user select the account modules
*
* @package configuration
* @author Roland Gruber
*/
/** Access to config functions */
include_once('../../lib/config.inc');
include_once(__DIR__ . '/../../lib/config.inc');
/** Access to module lists */
include_once('../../lib/modules.inc');
include_once(__DIR__ . '/../../lib/modules.inc');
/** common functions */
include_once '../../lib/configPages.inc';
include_once __DIR__ . '/../../lib/configPages.inc';
// start session
if (isFileBasedSession()) {
@ -64,7 +67,7 @@ setlanguage();
// if not: load login page
if (!isset($_SESSION['conf_config'])) {
/** go back to login if password is invalid */
require('conflogin.php');
require(__DIR__ . '/conflogin.php');
exit;
}
@ -79,35 +82,34 @@ $conf = &$_SESSION['conf_config'];
$errorsToDisplay = checkInput();
// check if button was pressed and if we have to save the settings or go to another tab
if (isset($_POST['saveSettings']) || isset($_POST['editmodules'])
|| isset($_POST['edittypes']) || isset($_POST['generalSettingsButton'])
|| isset($_POST['moduleSettings']) || isset($_POST['jobs'])) {
if (sizeof($errorsToDisplay) == 0) {
// go to final page
if (isset($_POST['saveSettings'])) {
metaRefresh("confsave.php");
exit;
}
// go to types page
elseif (isset($_POST['edittypes'])) {
metaRefresh("conftypes.php");
exit;
}
// go to general page
elseif (isset($_POST['generalSettingsButton'])) {
metaRefresh("confmain.php");
exit;
}
// go to module settings page
elseif (isset($_POST['moduleSettings'])) {
metaRefresh("moduleSettings.php");
exit;
}
// go to jobs page
elseif (isset($_POST['jobs'])) {
metaRefresh("jobs.php");
exit;
}
if ((isset($_POST['saveSettings']) || isset($_POST['editmodules'])
|| isset($_POST['edittypes']) || isset($_POST['generalSettingsButton'])
|| isset($_POST['moduleSettings']) || isset($_POST['jobs']))
&& ($errorsToDisplay === [])) {
// go to final page
if (isset($_POST['saveSettings'])) {
metaRefresh("confsave.php");
exit;
}
// go to types page
elseif (isset($_POST['edittypes'])) {
metaRefresh("conftypes.php");
exit;
}
// go to general page
elseif (isset($_POST['generalSettingsButton'])) {
metaRefresh("confmain.php");
exit;
}
// go to module settings page
elseif (isset($_POST['moduleSettings'])) {
metaRefresh("moduleSettings.php");
exit;
}
// go to jobs page
elseif (isset($_POST['jobs'])) {
metaRefresh("jobs.php");
exit;
}
}
@ -119,7 +121,7 @@ printJsIncludes('../..');
printConfigurationPageHeaderBar($conf);
// print error messages
for ($i = 0; $i < sizeof($errorsToDisplay); $i++) {
for ($i = 0; $i < count($errorsToDisplay); $i++) {
call_user_func_array(StatusMessage(...), $errorsToDisplay[$i]);
}
@ -157,7 +159,7 @@ $buttonContainer->addElement(new htmlSpacer(null, '10px'), true);
if (empty($errorsToDisplay) && isset($_POST['scrollPositionTop']) && isset($_POST['scrollPositionLeft'])) {
// scroll to last position
$buttonContainer->addElement(new htmlJavaScript('window.lam.utility.restoreScrollPosition(' . $_POST['scrollPositionTop'] .', ' . $_POST['scrollPositionLeft'] . ')'));
$buttonContainer->addElement(new htmlJavaScript('window.lam.utility.restoreScrollPosition(' . $_POST['scrollPositionTop'] . ', ' . $_POST['scrollPositionLeft'] . ')'));
}
parseHtml(null, $buttonContainer, [], false, 'user');
@ -168,56 +170,56 @@ echo "</html>\n";
/**
* Displays the module selection boxes and checks if dependencies are fulfilled.
*
* @param \LAM\TYPES\ConfiguredType $type account type
* @param htmlResponsiveRow $container meta HTML container
*/
* Displays the module selection boxes and checks if dependencies are fulfilled.
*
* @param \LAM\TYPES\ConfiguredType $type account type
* @param htmlResponsiveRow $container meta HTML container
*/
function config_showAccountModules($type, &$container): void {
// account modules
$available = getAvailableModules($type->getScope(), true);
$selected = $type->getModules();
$sortedAvailable = [];
for ($i = 0; $i < sizeof($available); $i++) {
for ($i = 0; $i < count($available); $i++) {
$sortedAvailable[$available[$i]] = getModuleAlias($available[$i], $type->getScope());
}
natcasesort($sortedAvailable);
// build options for selected and available modules
$selOptions = [];
for ($i = 0; $i < sizeof($selected); $i++) {
for ($i = 0; $i < count($selected); $i++) {
if (in_array($selected[$i], $available)) { // selected modules must be available
if (is_base_module($selected[$i], $type->getScope())) { // mark base modules
$selOptions[getModuleAlias($selected[$i], $type->getScope()) . " (" . $selected[$i] . ")*"] = $selected[$i];
$selOptions[getModuleAlias($selected[$i], $type->getScope()) . " (" . $selected[$i] . ")*"] = $selected[$i];
}
else {
$selOptions[getModuleAlias($selected[$i], $type->getScope()) . " (" . $selected[$i] . ")"] = $selected[$i];
$selOptions[getModuleAlias($selected[$i], $type->getScope()) . " (" . $selected[$i] . ")"] = $selected[$i];
}
}
}
$availOptions = [];
foreach ($sortedAvailable as $key => $value) {
if (! in_array($key, $selected)) { // display non-selected modules
if (!in_array($key, $selected)) { // display non-selected modules
if (is_base_module($key, $type->getScope())) { // mark base modules
$availOptions[$value . " (" . $key . ")*"] = $key;
$availOptions[$value . " (" . $key . ")*"] = $key;
}
else {
$availOptions[$value . " (" . $key . ")"] = $key;
$availOptions[$value . " (" . $key . ")"] = $key;
}
}
}
// add account module selection
$container->add(new htmlSubTitle($type->getAlias(), '../../graphics/' . $type->getIcon()), 12);
if (sizeof($selOptions) > 0) {
if ($selOptions !== []) {
$container->add(new htmlOutputText(_("Selected modules")), 12, 6);
}
if (sizeof($availOptions) > 0) {
if ($availOptions !== []) {
$container->add(new htmlOutputText(_("Available modules")), 0, 6);
}
$container->addVerticalSpacer('1rem');
// selected modules
if (sizeof($selOptions) > 0) {
if ($selOptions !== []) {
$listElements = [];
foreach ($selOptions as $key => $value) {
$el = new htmlTable('100%');
@ -241,7 +243,7 @@ function config_showAccountModules($type, &$container): void {
$container->add(new htmlOutputText(''), 12, 6);
}
// available modules
if (sizeof($availOptions) > 0) {
if ($availOptions !== []) {
$container->add(new htmlSpacer(null, '2rem'), 12, 0, 0, 'hide-on-tablet');
$container->add(new htmlOutputText(_("Available modules")), 12, 0, 0, 'hide-on-tablet');
$container->add(new htmlSpacer(null, '1rem'), 12, 0, 0, 'hide-on-tablet');
@ -261,7 +263,7 @@ function config_showAccountModules($type, &$container): void {
$availDiv->alignment = htmlElement::ALIGN_TOP;
$availDiv->setCSSClasses(['confModList']);
$availRow->add($availDiv);
if (sizeof($availOptions) >= 10) {
if (count($availOptions) >= 10) {
$availRow->addVerticalSpacer('1rem');
$filterGroup = new htmlGroup();
$filterGroup->addElement(new htmlOutputText(_('Filter')));
@ -274,7 +276,7 @@ function config_showAccountModules($type, &$container): void {
$container->add($availRow, 12, 6);
}
$positions = [];
for ($i = 0; $i < sizeof($selOptions); $i++) {
for ($i = 0; $i < count($selOptions); $i++) {
$positions[] = $i;
}
$container->add(new htmlHiddenInput('positions_' . $type->getId(), implode(',', $positions)), 12);
@ -304,7 +306,7 @@ function checkInput(): array {
$selected_temp = explode(',', $selected_temp);
$selected = [];
// only use available modules as selected
for ($i = 0; $i < sizeof($selected_temp); $i++) {
for ($i = 0; $i < count($selected_temp); $i++) {
if (in_array($selected_temp[$i], $available)) {
$selected[] = $selected_temp[$i];
}
@ -321,7 +323,7 @@ function checkInput(): array {
}
// remove modules from selection
$new_selected = [];
for ($i = 0; $i < sizeof($selected); $i++) {
for ($i = 0; $i < count($selected); $i++) {
if (!isset($_POST['del_' . $typeId . '_' . $selected[$i]])) {
$new_selected[] = $selected[$i];
}
@ -339,7 +341,7 @@ function checkInput(): array {
// check dependencies
$depends = check_module_depends($selected, getModulesDependencies($scope));
if ($depends !== false) {
for ($i = 0; $i < sizeof($depends); $i++) {
for ($i = 0; $i < count($depends); $i++) {
$errors[] = ['ERROR', $type->getAlias(), _("Unsolved dependency:") . ' ' .
$depends[$i][0] . " (" . $depends[$i][1] . ")"];
}
@ -347,14 +349,14 @@ function checkInput(): array {
// check conflicts
$conflicts = check_module_conflicts($selected, getModulesDependencies($scope));
if ($conflicts !== false) {
for ($i = 0; $i < sizeof($conflicts); $i++) {
for ($i = 0; $i < count($conflicts); $i++) {
$errors[] = ['ERROR', $type->getAlias(), _("Conflicting module:") . ' ' .
$conflicts[$i][0] . " (" . $conflicts[$i][1] . ")"];
}
}
// check for base module
$baseCount = 0;
for ($i = 0; $i < sizeof($selected); $i++) {
for ($i = 0; $i < count($selected); $i++) {
if (is_base_module($selected[$i], $scope)) {
$baseCount++;
}

View file

@ -55,7 +55,7 @@ setlanguage();
if (!isset($_SESSION['conf_isAuthenticated']) || ($_SESSION['conf_config']->getName() !== $_SESSION['conf_isAuthenticated'])) {
$_SESSION['conf_message'] = new htmlStatusMessage('ERROR', _("No password was entered!"));
/** go back to login if password is empty */
require('conflogin.php');
require(__DIR__ . '/conflogin.php');
exit;
}
@ -82,7 +82,7 @@ catch (LAMException $e) {
finally {
// remove settings from session
$sessionKeys = array_keys($_SESSION);
for ($i = 0; $i < sizeof($sessionKeys); $i++) {
for ($i = 0; $i < count($sessionKeys); $i++) {
if (str_starts_with($sessionKeys[$i], "conf_")) {
unset($_SESSION[$sessionKeys[$i]]);
}

View file

@ -1,5 +1,7 @@
<?php
namespace LAM\CONFIG;
use \htmlTable;
use \htmlSubTitle;
use \htmlImage;
@ -12,6 +14,7 @@ use \htmlResponsiveInputCheckbox;
use \LAMConfig;
use \htmlResponsiveRow;
use \htmlResponsiveInputField;
/*
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
Copyright (C) 2004 - 2023 Roland Gruber
@ -34,19 +37,19 @@ use \htmlResponsiveInputField;
/**
* Here the user can select the account types.
*
* @package configuration
* @author Roland Gruber
*/
* Here the user can select the account types.
*
* @package configuration
* @author Roland Gruber
*/
/** Access to config functions */
include_once '../../lib/config.inc';
include_once __DIR__ . '/../../lib/config.inc';
/** Access to account types */
include_once '../../lib/types.inc';
include_once __DIR__ . '/../../lib/types.inc';
/** common functions */
include_once '../../lib/configPages.inc';
include_once __DIR__ . '/../../lib/configPages.inc';
// start session
if (isFileBasedSession()) {
@ -60,7 +63,7 @@ setlanguage();
// if not: load login page
if (!isset($_SESSION['conf_config'])) {
/** go back to login if password is invalid */
require('conflogin.php');
require(__DIR__ . '/conflogin.php');
exit;
}
@ -75,45 +78,44 @@ $conf = &$_SESSION['conf_config'];
$errorsToDisplay = checkInput();
// check if button was pressed and if we have to save the settings or go to another tab
if (isset($_POST['saveSettings']) || isset($_POST['editmodules'])
|| isset($_POST['edittypes']) || isset($_POST['generalSettingsButton'])
|| isset($_POST['moduleSettings']) || isset($_POST['jobs'])) {
if (sizeof($errorsToDisplay) == 0) {
// check if all types have modules
$activeTypes = $conf->get_ActiveTypes();
for ($i = 0; $i < sizeof($activeTypes); $i++) {
$selectedModules = $conf->get_AccountModules($activeTypes[$i]);
if (sizeof($selectedModules) == 0) {
// go to module selection
metaRefresh("confmodules.php");
exit;
}
}
// go to final page
if (isset($_POST['saveSettings'])) {
metaRefresh("confsave.php");
exit;
}
// go to modules page
elseif (isset($_POST['editmodules'])) {
if ((isset($_POST['saveSettings']) || isset($_POST['editmodules'])
|| isset($_POST['edittypes']) || isset($_POST['generalSettingsButton'])
|| isset($_POST['moduleSettings']) || isset($_POST['jobs']))
&& (count($errorsToDisplay) == 0)) {
// check if all types have modules
$activeTypes = $conf->get_ActiveTypes();
for ($i = 0; $i < count($activeTypes); $i++) {
$selectedModules = $conf->get_AccountModules($activeTypes[$i]);
if (count($selectedModules) == 0) {
// go to module selection
metaRefresh("confmodules.php");
exit;
}
// go to general page
elseif (isset($_POST['generalSettingsButton'])) {
metaRefresh("confmain.php");
exit;
}
// go to module settings page
elseif (isset($_POST['moduleSettings'])) {
metaRefresh("moduleSettings.php");
exit;
}
// go to jobs page
elseif (isset($_POST['jobs'])) {
metaRefresh("jobs.php");
exit;
}
}
// go to final page
if (isset($_POST['saveSettings'])) {
metaRefresh("confsave.php");
exit;
}
// go to modules page
elseif (isset($_POST['editmodules'])) {
metaRefresh("confmodules.php");
exit;
}
// go to general page
elseif (isset($_POST['generalSettingsButton'])) {
metaRefresh("confmain.php");
exit;
}
// go to module settings page
elseif (isset($_POST['moduleSettings'])) {
metaRefresh("moduleSettings.php");
exit;
}
// go to jobs page
elseif (isset($_POST['jobs'])) {
metaRefresh("jobs.php");
exit;
}
}
@ -143,7 +145,7 @@ printJsIncludes('../..');
printConfigurationPageHeaderBar($conf);
// print error messages
for ($i = 0; $i < sizeof($errorsToDisplay); $i++) {
for ($i = 0; $i < count($errorsToDisplay); $i++) {
call_user_func_array(StatusMessage(...), $errorsToDisplay[$i]);
}
@ -154,7 +156,7 @@ printConfigurationPageTabs(ConfigurationPageTab::TYPES);
$row = new htmlResponsiveRow();
// show available types
if (sizeof($availableScopes) > 0) {
if ($availableScopes !== []) {
$row->add(new htmlSubTitle(_("Available account types")), 12);
foreach ($availableScopes as $availableScope) {
$availableLabelGroup = new htmlGroup();
@ -179,7 +181,7 @@ $container = new htmlResponsiveRow();
$_SESSION['conftypes_optionTypes'] = [];
// show active types
if (sizeof($activeTypes) > 0) {
if (count($activeTypes) > 0) {
$container->add(new htmlSubTitle(_("Active account types")), 12);
$index = 0;
foreach ($activeTypes as $activeType) {
@ -196,19 +198,19 @@ if (sizeof($activeTypes) > 0) {
$buttons = new htmlGroup();
// move buttons
if ($index > 0) {
$upButton = new htmlButton('moveup_'. $activeType->getId(), 'up.svg', true);
$upButton = new htmlButton('moveup_' . $activeType->getId(), 'up.svg', true);
$upButton->setTitle(_("Up"));
$upButton->setCSSClasses(['size16']);
$buttons->addElement($upButton);
}
if ($index < (sizeof($activeTypes) - 1)) {
$upButton = new htmlButton('movedown_'. $activeType->getId(), 'down.svg', true);
if ($index < (count($activeTypes) - 1)) {
$upButton = new htmlButton('movedown_' . $activeType->getId(), 'down.svg', true);
$upButton->setTitle(_("Down"));
$upButton->setCSSClasses(['size16']);
$buttons->addElement($upButton);
}
// delete button
$delButton = new htmlButton('rem_'. $activeType->getId(), 'del.svg', true);
$delButton = new htmlButton('rem_' . $activeType->getId(), 'del.svg', true);
$delButton->setTitle(_("Remove this account type"));
$delButton->setCSSClasses(['size16']);
$buttons->addElement($delButton);
@ -340,7 +342,7 @@ function checkInput(): array {
$typeSettings = $conf->get_typeSettings();
$accountTypes = $conf->get_ActiveTypes();
$postKeys = array_keys($_POST);
for ($i = 0; $i < sizeof($postKeys); $i++) {
for ($i = 0; $i < count($postKeys); $i++) {
$key = $postKeys[$i];
// check if remove button was pressed
if (str_starts_with($key, "rem_")) {
@ -350,7 +352,7 @@ function checkInput(): array {
$accountTypes = array_flip($accountTypes);
$accountTypes = array_values($accountTypes);
}
// check if up button was pressed
// check if up button was pressed
elseif (str_starts_with($key, "moveup_")) {
$type = substr($key, 7);
$pos = array_search($type, $accountTypes);
@ -383,7 +385,7 @@ function checkInput(): array {
}
}
// set filter
elseif (substr($key, 0, strlen('filter_')) == "filter_") {
elseif (substr($key, 0, strlen('filter_')) === "filter_") {
$typeSettings[$key] = $_POST[$key];
}
// set custom label

View file

@ -33,7 +33,7 @@ use htmlResponsiveRow;
/** Access to config functions */
include_once('../../lib/config.inc');
include_once(__DIR__ . '/../../lib/config.inc');
// start session
if (isFileBasedSession()) {

View file

@ -22,17 +22,17 @@
/**
* Login page to change the main preferences.
*
* @package configuration
* @author Roland Gruber
*/
* Login page to change the main preferences.
*
* @package configuration
* @author Roland Gruber
*/
/** Access to config functions */
include_once('../../lib/config.inc');
include_once(__DIR__ . '/../../lib/config.inc');
/** Used to print status messages */
include_once('../../lib/status.inc');
include_once(__DIR__ . '/../../lib/status.inc');
if (isLAMProVersion()) {
include_once(__DIR__ . "/../../lib/env.inc");
}
@ -47,7 +47,9 @@ session_regenerate_id(true);
setlanguage();
// remove settings from session
if (isset($_SESSION["mainconf_password"])) unset($_SESSION["mainconf_password"]);
if (isset($_SESSION["mainconf_password"])) {
unset($_SESSION["mainconf_password"]);
}
if (isset($_SESSION['cfgMain'])) {
unset($_SESSION['cfgMain']);
}
@ -69,109 +71,117 @@ if (isset($_SESSION['header'])) {
}
printHeaderContents(_("Login"), '../..');
?>
</head>
<body>
<?php
// include all JavaScript files
printJsIncludes('../..');
?>
<div id="lam-topnav" class="lam-header">
<div class="lam-header-left lam-menu-stay">
<a href="https://www.ldap-account-manager.org/" target="new_window">
<img class="align-middle" width="24" height="24" alt="help" src="../../graphics/logo24.png">
<span class="hide-on-mobile">
</head>
<body>
<?php
// include all JavaScript files
printJsIncludes('../..');
?>
<div id="lam-topnav" class="lam-header">
<div class="lam-header-left lam-menu-stay">
<a href="https://www.ldap-account-manager.org/" target="new_window">
<img class="align-middle" width="24" height="24" alt="help" src="../../graphics/logo24.png">
<span class="hide-on-mobile">
<?php
echo getLAMVersionText();
?>
echo getLAMVersionText();
?>
</span>
</a>
</div>
<?php
if (is_dir(__DIR__ . '/../../docs/manual')) {
?>
<a class="lam-header-right lam-menu-icon hide-on-tablet" href="javascript:void(0);" class="icon" onclick="window.lam.topmenu.toggle();">
<img class="align-middle" width="16" height="16" alt="menu" src="../../graphics/menu.svg">
<span class="padding0">&nbsp;</span>
</a>
<a class="lam-header-right lam-menu-entry" target="_blank" href="../../docs/manual/index.html">
<span class="padding0"><?php echo _("Help") ?></span>
</a>
<?php
}
?>
</div>
<br>
<?php
// check if config file is writable
if (!$cfgMain->isWritable()) {
StatusMessage('WARN', _('The config file is not writable.'), _('Your changes cannot be saved until you make the file writable for the webserver user.'));
}
if (!empty($_GET['invalidLicense']) && ($_GET['invalidLicense'] == '1')) {
StatusMessage('WARN', _('Invalid licence'), _('Please setup your licence data.'));
}
if (!empty($_GET['invalidLicense']) && ($_GET['invalidLicense'] == '2')) {
StatusMessage('WARN', _('Expired licence'), _('Please setup your licence data.'));
}
</a>
</div>
<?php
if (is_dir(__DIR__ . '/../../docs/manual')) {
?>
<br>
<!-- form to change main options -->
<form action="mainlogin.php" method="post" autocomplete="off">
<table align="center">
<tr><td>
<table align="center" border="0" rules="none" bgcolor="white" class="roundedShadowBox" style="padding: 20px;">
<tr><td>
<a class="lam-header-right lam-menu-icon hide-on-tablet" href="javascript:void(0);" class="icon"
onclick="window.lam.topmenu.toggle();">
<img class="align-middle" width="16" height="16" alt="menu" src="../../graphics/menu.svg">
<span class="padding0">&nbsp;</span>
</a>
<a class="lam-header-right lam-menu-entry" target="_blank" href="../../docs/manual/index.html">
<span class="padding0"><?php echo _("Help") ?></span>
</a>
<?php
$spacer = new htmlSpacer('20px', '20px');
$group = new htmlGroup();
$row = new htmlResponsiveRow();
$row->add(new htmlOutputText(_("Please enter the master password to change the general preferences:")), 12);
$group->addElement($row);
// print message if login was incorrect or no config profiles are present
if (isset($message)) {
$messageField = new htmlStatusMessage('ERROR', $message);
$row = new htmlResponsiveRow();
$row->add($messageField, 12);
$group->addElement($spacer);
$group->addElement($row);
}
$group->addElement($spacer);
// password input
$label = new htmlOutputText(_('Master password'));
$passwordGroup = new htmlGroup();
$passwordField = new htmlInputField('passwd');
$passwordField->setFieldSize(15);
$passwordField->setIsPassword(true);
$passwordField->setCSSClasses(['lam-initial-focus']);
$passwordGroup->addElement($passwordField);
$passwordGroup->addElement(new htmlHelpLink('236'));
$passwordDiv = new htmlDiv(null, $passwordGroup);
$passwordDiv->setCSSClasses(['nowrap']);
$row = new htmlResponsiveRow($label, $passwordDiv);
$group->addElement($row);
// button
$group->addElement($spacer);
$okButton = new htmlButton('submit', _("Ok"));
$okButton->setCSSClasses(['lam-primary']);
$row = new htmlResponsiveRow();
$row->add($okButton, 12);
$row->setCSSClasses(['']);
$group->addElement($row);
}
?>
</div>
<br>
<?php
// check if config file is writable
if (!$cfgMain->isWritable()) {
StatusMessage('WARN', _('The config file is not writable.'), _('Your changes cannot be saved until you make the file writable for the webserver user.'));
}
if (!empty($_GET['invalidLicense']) && ($_GET['invalidLicense'] == '1')) {
StatusMessage('WARN', _('Invalid licence'), _('Please setup your licence data.'));
}
if (!empty($_GET['invalidLicense']) && ($_GET['invalidLicense'] == '2')) {
StatusMessage('WARN', _('Expired licence'), _('Please setup your licence data.'));
}
?>
<br>
<!-- form to change main options -->
<form action="mainlogin.php" method="post" autocomplete="off">
<table align="center">
<tr>
<td>
<table align="center" border="0" rules="none" bgcolor="white" class="roundedShadowBox"
style="padding: 20px;">
<tr>
<td>
<?php
$spacer = new htmlSpacer('20px', '20px');
$group = new htmlGroup();
$row = new htmlResponsiveRow();
$row->add(new htmlOutputText(_("Please enter the master password to change the general preferences:")), 12);
$group->addElement($row);
// print message if login was incorrect or no config profiles are present
if (isset($message)) {
$messageField = new htmlStatusMessage('ERROR', $message);
$row = new htmlResponsiveRow();
$row->add($messageField, 12);
$group->addElement($spacer);
$group->addElement($row);
}
$group->addElement($spacer);
// password input
$label = new htmlOutputText(_('Master password'));
$passwordGroup = new htmlGroup();
$passwordField = new htmlInputField('passwd');
$passwordField->setFieldSize(15);
$passwordField->setIsPassword(true);
$passwordField->setCSSClasses(['lam-initial-focus']);
$passwordGroup->addElement($passwordField);
$passwordGroup->addElement(new htmlHelpLink('236'));
$passwordDiv = new htmlDiv(null, $passwordGroup);
$passwordDiv->setCSSClasses(['nowrap']);
$row = new htmlResponsiveRow($label, $passwordDiv);
$group->addElement($row);
// button
$group->addElement($spacer);
$okButton = new htmlButton('submit', _("Ok"));
$okButton->setCSSClasses(['lam-primary']);
$row = new htmlResponsiveRow();
$row->add($okButton, 12);
$row->setCSSClasses(['']);
$group->addElement($row);
$div = new htmlDiv(null, $group);
$div->setCSSClasses(['centeredTable']);
$div = new htmlDiv(null, $group);
$div->setCSSClasses(['centeredTable']);
parseHtml(null, $div, [], false, 'user');
?>
</td></tr>
</table>
</td></tr>
<tr><td align="left">
<br><a href="../login.php"><?php echo _("Back to login"); ?></a>
</td></tr>
</table>
</form>
parseHtml(null, $div, [], false, 'user');
?>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="left">
<br><a href="../login.php"><?php echo _("Back to login"); ?></a>
</td>
</tr>
</table>
</form>
<p><br><br></p>
<p><br><br></p>
</body>
</body>
</html>

View file

@ -61,11 +61,11 @@ use PDO;
/** Access to config functions */
include_once('../../lib/config.inc');
include_once(__DIR__ . '/../../lib/config.inc');
/** Used to print status messages */
include_once('../../lib/status.inc');
include_once(__DIR__ . '/../../lib/status.inc');
/** LAM Pro */
include_once('../../lib/selfService.inc');
include_once(__DIR__ . '/../../lib/selfService.inc');
// start session
if (isFileBasedSession()) {
@ -83,7 +83,7 @@ $cfg = &$_SESSION['cfgMain'];
// check if user is logged in
if (!isset($_SESSION["mainconf_password"]) || (!$cfg->checkPassword($_SESSION["mainconf_password"]))) {
require('mainlogin.php');
require(__DIR__ . '/mainlogin.php');
exit();
}
@ -199,10 +199,10 @@ if (isset($_POST['submitFormData'])) {
if (isset($_POST['allowedHosts'])) {
$allowedHosts = $_POST['allowedHosts'];
$allowedHostsList = explode("\n", $allowedHosts);
for ($i = 0; $i < sizeof($allowedHostsList); $i++) {
for ($i = 0; $i < count($allowedHostsList); $i++) {
$allowedHostsList[$i] = trim($allowedHostsList[$i]);
// ignore empty lines
if ($allowedHostsList[$i] == "") {
if ($allowedHostsList[$i] === "") {
unset($allowedHostsList[$i]);
continue;
}
@ -222,10 +222,10 @@ if (isset($_POST['submitFormData'])) {
if (isset($_POST['allowedHostsSelfService'])) {
$allowedHostsSelfService = $_POST['allowedHostsSelfService'];
$allowedHostsSelfServiceList = explode("\r\n", $allowedHostsSelfService);
for ($i = 0; $i < sizeof($allowedHostsSelfServiceList); $i++) {
for ($i = 0; $i < count($allowedHostsSelfServiceList); $i++) {
$allowedHostsSelfServiceList[$i] = trim($allowedHostsSelfServiceList[$i]);
// ignore empty lines
if ($allowedHostsSelfServiceList[$i] == "") {
if ($allowedHostsSelfServiceList[$i] === "") {
unset($allowedHostsSelfServiceList[$i]);
continue;
}
@ -252,7 +252,7 @@ if (isset($_POST['submitFormData'])) {
} elseif ($_POST['logDestination'] == "remote") {
$cfg->logDestination = "REMOTE:" . $_POST['logRemote'];
$remoteParts = explode(':', $_POST['logRemote']);
if ((sizeof($remoteParts) !== 2) || !get_preg($remoteParts[0], 'DNSname') || !get_preg($remoteParts[1], 'digit')) {
if ((count($remoteParts) !== 2) || !get_preg($remoteParts[0], 'DNSname') || !get_preg($remoteParts[1], 'digit')) {
$errors[] = _("Please enter a valid remote server in format \"server:port\".");
}
} else {
@ -325,7 +325,7 @@ if (isset($_POST['submitFormData'])) {
}
if (isset($_POST['sslCaCertImport'])) {
$matches = [];
if (preg_match('/^ldaps:\\/\\/([a-zA-Z0-9_\\.-]+)(:([0-9]+))?$/', $_POST['serverurl'], $matches)) {
if (preg_match('/^ldaps:\/\/([a-zA-Z0-9_.-]+)(:(\d+))?$/', $_POST['serverurl'], $matches)) {
$port = '636';
if (isset($matches[3]) && !empty($matches[3])) {
$port = $matches[3];
@ -342,7 +342,7 @@ if (isset($_POST['submitFormData'])) {
$errors[] = _('Invalid server name. Please enter "server" or "server:port".');
}
}
foreach ($_POST as $key => $value) {
foreach (array_keys($_POST) as $key) {
if (str_starts_with($key, 'deleteCert_')) {
$index = substr($key, strlen('deleteCert_'));
$cfg->deleteSSLCaCert($index);
@ -529,7 +529,7 @@ if (isset($_POST['submitFormData'])) {
$sslUploadBtn->setTitle(_('Upload CA certificate in DER/PEM format.'));
$row->addField($sslUploadBtn);
if (function_exists('stream_socket_client') && function_exists('stream_context_get_params')) {
$sslImportServerUrl = !empty($_POST['serverurl']) ? $_POST['serverurl'] : 'ldaps://';
$sslImportServerUrl = empty($_POST['serverurl']) ? 'ldaps://' : $_POST['serverurl'];
$serverUrlUpload = new htmlInputField('serverurl', $sslImportServerUrl);
$row->addLabel($serverUrlUpload);
$sslImportBtn = new htmlButton('sslCaCertImport', _('Import from server'));
@ -538,10 +538,10 @@ if (isset($_POST['submitFormData'])) {
}
$sslCerts = $cfg->getSSLCaCertificates();
if (sizeof($sslCerts) > 0) {
if (count($sslCerts) > 0) {
$certsTitles = [_('Common name'), _('Valid to'), _('Serial number'), _('Delete')];
$certsData = [];
for ($i = 0; $i < sizeof($sslCerts); $i++) {
for ($i = 0; $i < count($sslCerts); $i++) {
$serial = $sslCerts[$i]['serialNumber'] ?? '';
$validTo = $sslCerts[$i]['validTo_time_t'] ?? '';
if (get_preg($validTo, 'digit')) {

View file

@ -1,5 +1,7 @@
<?php
namespace LAM\CONFIG;
use htmlJavaScript;
use \moduleCache;
use \htmlSpacer;
@ -7,6 +9,7 @@ use \htmlTable;
use \htmlButton;
use \htmlResponsiveRow;
use \htmlSubTitle;
/*
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
@ -30,19 +33,19 @@ use \htmlSubTitle;
/**
* Here the user can edit the module settings.
*
* @package configuration
* @author Roland Gruber
*/
* Here the user can edit the module settings.
*
* @package configuration
* @author Roland Gruber
*/
/** Access to config functions */
include_once('../../lib/config.inc');
include_once(__DIR__ . '/../../lib/config.inc');
/** Access to account types */
include_once('../../lib/types.inc');
include_once(__DIR__ . '/../../lib/types.inc');
/** common functions */
include_once '../../lib/configPages.inc';
include_once __DIR__ . '/../../lib/configPages.inc';
// start session
if (isFileBasedSession()) {
@ -56,7 +59,7 @@ setlanguage();
// if not: load login page
if (!isset($_SESSION['conf_config'])) {
/** go back to login if password is invalid */
require('conflogin.php');
require(__DIR__ . '/conflogin.php');
exit;
}
@ -71,35 +74,34 @@ $conf = &$_SESSION['conf_config'];
$errorsToDisplay = checkInput();
// check if button was pressed and if we have to save the settings or go to another tab
if (isset($_POST['saveSettings']) || isset($_POST['editmodules'])
|| isset($_POST['edittypes']) || isset($_POST['generalSettingsButton'])
|| isset($_POST['moduleSettings']) || isset($_POST['jobs'])) {
if (sizeof($errorsToDisplay) == 0) {
// go to final page
if (isset($_POST['saveSettings'])) {
metaRefresh("confsave.php");
exit;
}
// go to types page
elseif (isset($_POST['edittypes'])) {
metaRefresh("conftypes.php");
exit;
}
// go to modules page
elseif (isset($_POST['editmodules'])) {
metaRefresh("confmodules.php");
exit;
}
// go to types page
elseif (isset($_POST['generalSettingsButton'])) {
metaRefresh("confmain.php");
exit;
}
// go to jobs page
elseif (isset($_POST['jobs'])) {
metaRefresh("jobs.php");
exit;
}
if ((isset($_POST['saveSettings']) || isset($_POST['editmodules'])
|| isset($_POST['edittypes']) || isset($_POST['generalSettingsButton'])
|| isset($_POST['moduleSettings']) || isset($_POST['jobs']))
&& (count($errorsToDisplay) == 0)) {
// go to final page
if (isset($_POST['saveSettings'])) {
metaRefresh("confsave.php");
exit;
}
// go to types page
elseif (isset($_POST['edittypes'])) {
metaRefresh("conftypes.php");
exit;
}
// go to modules page
elseif (isset($_POST['editmodules'])) {
metaRefresh("confmodules.php");
exit;
}
// go to types page
elseif (isset($_POST['generalSettingsButton'])) {
metaRefresh("confmain.php");
exit;
}
// go to jobs page
elseif (isset($_POST['jobs'])) {
metaRefresh("jobs.php");
exit;
}
}
@ -112,7 +114,7 @@ printJsIncludes('../..');
printConfigurationPageHeaderBar($conf);
// print error messages
for ($i = 0; $i < sizeof($errorsToDisplay); $i++) {
for ($i = 0; $i < count($errorsToDisplay); $i++) {
call_user_func_array(StatusMessage(...), $errorsToDisplay[$i]);
}
@ -121,10 +123,10 @@ echo "<form id=\"inputForm\" action=\"moduleSettings.php\" method=\"post\" autoc
printConfigurationPageTabs(ConfigurationPageTab::MODULE_SETTINGS);
?>
<input type="text" name="hiddenPreventAutocomplete" autocomplete="false" class="hidden" value="">
<input type="password" name="hiddenPreventAutocompletePwd1" autocomplete="false" class="hidden" value="123">
<input type="password" name="hiddenPreventAutocompletePwd2" autocomplete="false" class="hidden" value="321">
<?php
<input type="text" name="hiddenPreventAutocomplete" autocomplete="false" class="hidden" value="">
<input type="password" name="hiddenPreventAutocompletePwd1" autocomplete="false" class="hidden" value="123">
<input type="password" name="hiddenPreventAutocompletePwd2" autocomplete="false" class="hidden" value="321">
<?php
// module settings
@ -135,7 +137,7 @@ $types = $typeManager->getConfiguredTypes();
$scopes = [];
foreach ($types as $type) {
$mods = $conf->get_AccountModules($type->getId());
for ($i = 0; $i < sizeof($mods); $i++) {
for ($i = 0; $i < count($mods); $i++) {
$scopes[$mods[$i]][] = $type->getId();
}
}
@ -149,16 +151,14 @@ $old_options = $conf->get_moduleSettings();
// display module boxes
$modules = array_keys($options);
$_SESSION['conf_types'] = [];
for ($i = 0; $i < sizeof($modules); $i++) {
for ($i = 0; $i < count($modules); $i++) {
if (empty($options[$modules[$i]])) {
continue;
}
$module = moduleCache::getModule($modules[$i], null);
$iconImage = $module->getIcon();
if ($iconImage != null) {
if (!(str_starts_with($iconImage, 'http')) && !(str_starts_with($iconImage, '/'))) {
$iconImage = '../../graphics/' . $iconImage;
}
if (($iconImage != null) && !(str_starts_with($iconImage, 'http')) && !(str_starts_with($iconImage, '/'))) {
$iconImage = '../../graphics/' . $iconImage;
}
$row = new htmlResponsiveRow();
$row->add(new htmlSubTitle(getModuleAlias($modules[$i], null), $iconImage, null, true), 12);
@ -190,7 +190,7 @@ $buttonContainer->addElement(new htmlSpacer(null, '10px'), true);
if (empty($errorsToDisplay) && isset($_POST['scrollPositionTop']) && isset($_POST['scrollPositionLeft'])) {
// scroll to last position
$buttonContainer->addElement(new htmlJavaScript('window.lam.utility.restoreScrollPosition(' . $_POST['scrollPositionTop'] .', ' . $_POST['scrollPositionLeft'] . ')'));
$buttonContainer->addElement(new htmlJavaScript('window.lam.utility.restoreScrollPosition(' . $_POST['scrollPositionTop'] . ', ' . $_POST['scrollPositionLeft'] . ')'));
}
parseHtml(null, $buttonContainer, [], false, null);
@ -221,7 +221,7 @@ function checkInput(): array {
$scopes = [];
foreach ($types as $type) {
$mods = $conf->get_AccountModules($type->getId());
for ($i = 0; $i < sizeof($mods); $i++) {
for ($i = 0; $i < count($mods); $i++) {
$scopes[$mods[$i]][] = $type->getId();
}
}

View file

@ -47,9 +47,9 @@ use ServerProfilePersistenceManager;
/** Access to config functions */
include_once('../../lib/config.inc');
include_once(__DIR__ . '/../../lib/config.inc');
/** Used to print status messages */
include_once('../../lib/status.inc');
include_once(__DIR__ . '/../../lib/status.inc');
// start session
if (isFileBasedSession()) {
@ -114,7 +114,7 @@ if (isset($_POST['action'])) {
// update default profile setting if needed
if ($cfg->default == $_POST['delfilename']) {
$filesNew = array_delete([$_POST['delfilename']], $files);
if (sizeof($filesNew) > 0) {
if (count($filesNew) > 0) {
sort($filesNew);
$cfg->default = $filesNew[0];
$cfg->save();

View file

@ -113,14 +113,14 @@ if (isset($_GET['type']) && isset($_SESSION['delete_dn'])) {
//load account
$_SESSION[$sessionKey] = new \accountContainer($type, $sessionKey);
// Show HTML Page
include '../lib/adminHeader.inc';
include __DIR__ . '/../lib/adminHeader.inc';
echo "<div class=\"smallPaddingContent\">";
echo "<br>\n";
echo "<form action=\"delete.php\" method=\"post\">\n";
$container = new htmlResponsiveRow();
$container->add(new htmlOutputText(_("Do you really want to remove the following accounts?")), 12);
$container->addVerticalSpacer('2rem');
$userCount = sizeof($users);
$userCount = count($users);
for ($i = 0; $i < $userCount; $i++) {
$container->addLabel(new htmlOutputText(_("Account name:")));
$container->addField(new htmlOutputText($users[$i]));
@ -161,7 +161,7 @@ if (isset($_GET['type']) && isset($_SESSION['delete_dn'])) {
parseHtml(null, $buttonContainer, [], false, $type->getScope());
echo "</form>\n";
echo "</div>\n";
include '../lib/adminFooter.inc';
include __DIR__ . '/../lib/adminFooter.inc';
}
if (isset($_POST['cancel'])) {
@ -349,5 +349,5 @@ if (isset($_POST['delete'])) {
*/
function getChildCount($dn) {
$entries = searchLDAP($dn, '(objectClass=*)', ['dn']);
return (sizeof($entries) - 1);
return (count($entries) - 1);
}

View file

@ -1,4 +1,5 @@
<?php
namespace LAM\HELP;
/*
@ -68,8 +69,8 @@ function echoHTMLHead(): void {
$title = "LDAP Account Manager Help";
printHeaderContents($title, '..');
?>
</head>
<body>
</head>
<body>
<?php
// include all JavaScript files
printJsIncludes('..');
@ -80,8 +81,8 @@ function echoHTMLHead(): void {
*/
function echoHTMLFoot(): void {
?>
</body>
</html>
</body>
</html>
<?php
}
@ -98,7 +99,7 @@ function displayHelp(array $helpEntry): void {
$format .= '<br><hr>' . _('Technical name') . ': <i>' . $helpEntry['attr'] . '</i>';
}
echo $format;
if(isset($helpEntry['SeeAlso']) && is_array($helpEntry['SeeAlso'])) {
if (isset($helpEntry['SeeAlso']) && is_array($helpEntry['SeeAlso'])) {
echo '<p class="help">' . _('See also') . ': <a class="helpSeeAlso" href="' . $helpEntry['SeeAlso']['link'] . '">' . $helpEntry['SeeAlso']['text'] . '</a></p>';
}
echoHTMLFoot();
@ -116,24 +117,19 @@ if (!isset($_GET['HelpNumber'])) {
$helpEntry = [];
// module help
if (isset($_GET['module']) && !($_GET['module'] == 'main') && !($_GET['module'] == '')) {
if (isset($_GET['module']) && ($_GET['module'] != 'main') && ($_GET['module'] != '')) {
include_once(__DIR__ . "/../lib/modules.inc");
$moduleName = $_GET['module'];
if (!ScopeAndModuleValidation::isValidModuleName($moduleName)) {
logNewMessage(LOG_ERR, 'Invalid module name: ' . $moduleName);
die();
}
if (!empty($_GET['scope'])) {
$scope = $_GET['scope'];
logNewMessage(LOG_ERR, 'Invalid module name: ' . $moduleName);
die();
}
else {
$scope = 'user';
}
if (!ScopeAndModuleValidation::isValidScopeName($scope)) {
logNewMessage(LOG_ERR, 'Invalid scope name: ' . $scope);
die();
}
$helpEntry = getHelp($moduleName, $_GET['HelpNumber'], $scope);
$scope = empty($_GET['scope']) ? 'user' : $_GET['scope'];
if (!ScopeAndModuleValidation::isValidScopeName($scope)) {
logNewMessage(LOG_ERR, 'Invalid scope name: ' . $scope);
die();
}
$helpEntry = getHelp($moduleName, $_GET['HelpNumber'], $scope);
if (!$helpEntry) {
$variables = [htmlspecialchars((string) $_GET['HelpNumber']), htmlspecialchars((string) $moduleName)];
$errorMessage = _("Sorry, the help id '%s' is not available for the module '%s'.");
@ -143,20 +139,17 @@ if (isset($_GET['module']) && !($_GET['module'] == 'main') && !($_GET['module']
exit;
}
}
// help entry in help.inc
else {
elseif (!array_key_exists($_GET['HelpNumber'], $helpArray)) {
/* If submitted help number is not in help/help.inc print error message */
if (!array_key_exists($_GET['HelpNumber'], $helpArray)) {
$variables = [htmlspecialchars((string) $_GET['HelpNumber'])];
$errorMessage = _("Sorry, the help number %s is not available.");
echoHTMLHead();
statusMessage("ERROR", "", $errorMessage, $variables);
echoHTMLFoot();
exit;
}
else {
$helpEntry = $helpArray[$_GET['HelpNumber']];
}
$variables = [htmlspecialchars((string) $_GET['HelpNumber'])];
$errorMessage = _("Sorry, the help number %s is not available.");
echoHTMLHead();
statusMessage("ERROR", "", $errorMessage, $variables);
echoHTMLFoot();
exit;
}
else {
$helpEntry = $helpArray[$_GET['HelpNumber']];
}
displayHelp($helpEntry);

View file

@ -75,7 +75,7 @@ if (isset($_POST['add_suff']) || isset($_POST['cancel'])) {
$name = explode("=", $tmp[0]);
array_shift($tmp);
$end = implode(",", $tmp);
if ($name[0] != "ou") { // add root entry
if ($name[0] !== "ou") { // add root entry
$attr = [];
$attr[$name[0]] = $name[1];
$attr['objectClass'] = 'organization';
@ -97,10 +97,10 @@ if (isset($_POST['add_suff']) || isset($_POST['cancel'])) {
$dnParts = explode(",", $suff);
$subsuffs = [];
// make list of subsuffixes
$dnPartsCount = sizeof($dnParts);
$dnPartsCount = count($dnParts);
for ($k = 0; $k < $dnPartsCount; $k++) {
$part = explode("=", $dnParts[$k]);
if ($part[0] == "ou") {
if ($part[0] === "ou") {
$subsuffs[] = implode(",", array_slice($dnParts, $k));
}
else {
@ -109,7 +109,7 @@ if (isset($_POST['add_suff']) || isset($_POST['cancel'])) {
}
}
// create missing entries
$subsuffCount = sizeof($subsuffs);
$subsuffCount = count($subsuffs);
for ($k = $subsuffCount - 1; $k >= 0; $k--) {
// check if subsuffix is present
$info = @ldap_read($_SESSION['ldap']->server(), $subsuffs[$k], "(objectclass=*)", ['dn'], 0, 0, 0, LDAP_DEREF_NEVER);
@ -120,7 +120,7 @@ if (isset($_POST['add_suff']) || isset($_POST['cancel'])) {
if (!$res) {
$suffarray = explode(",", $subsuffs[$k]);
$headarray = explode("=", $suffarray[0]);
if ($headarray[0] == "ou") { // add ou entry
if ($headarray[0] === "ou") { // add ou entry
$attr = [];
$attr['objectClass'] = 'organizationalunit';
$attr['ou'] = $headarray[1];
@ -134,7 +134,7 @@ if (isset($_POST['add_suff']) || isset($_POST['cancel'])) {
$attr = [];
$attr['objectClass'][] = 'organization';
$attr[$headarray[0]] = $headarray[1];
if ($headarray[0] == "dc") {
if ($headarray[0] === "dc") {
$attr['o'] = $headarray[1];
$attr['objectClass'][] = 'dcObject';
}
@ -154,26 +154,26 @@ if (isset($_POST['add_suff']) || isset($_POST['cancel'])) {
}
}
}
include '../lib/adminHeader.inc';
include __DIR__ . '/../lib/adminHeader.inc';
// print error/success messages
if (isset($_POST['add_suff'])) {
if (sizeof($failedDNs) > 0) {
if ($failedDNs !== []) {
// print error messages
foreach ($failedDNs as $suffix => $error) {
StatusMessage("ERROR", _("Failed to create entry!") . "<br>" . htmlspecialchars($error), htmlspecialchars($suffix));
}
include '../lib/adminFooter.inc';
include __DIR__ . '/../lib/adminFooter.inc';
}
else {
// print success message
StatusMessage("INFO", "", _("All changes were successful."));
include '../lib/adminFooter.inc';
include __DIR__ . '/../lib/adminFooter.inc';
}
}
else {
// no suffixes were created
StatusMessage("INFO", "", _("No changes were made."));
include '../lib/adminFooter.inc';
include __DIR__ . '/../lib/adminFooter.inc';
}
exit;
}

Some files were not shown because too many files have changed in this diff Show more