From 146c975a61d87d415b409f0d94c7093fc80db85a Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Fri, 6 Dec 2024 20:31:17 +0100 Subject: [PATCH 01/78] refactoring --- rector.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/rector.php b/rector.php index fd6120e10..47b7a8886 100644 --- a/rector.php +++ b/rector.php @@ -1,5 +1,7 @@ withSets([ SetList::DEAD_CODE, - LevelSetList::UP_TO_PHP_81 + LevelSetList::UP_TO_PHP_81, + SetList::CODE_QUALITY, ]) ->withSkip([ __DIR__ . '/lam/lib/3rdParty', @@ -30,6 +33,8 @@ return RectorConfig::configure() StaticCallOnNonStaticToInstanceCallRector::class, StringifyStrNeedlesRector::class, RestoreDefaultNullToNullableTypePropertyRector::class, + ForRepeatedCountToOwnVariableRector::class, + SimplifyEmptyCheckOnEmptyArrayRector::class ]) ->withFileExtensions([ 'php', From 66dcc2ecedde5e8b210d6569679e53c668058a79 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Fri, 6 Dec 2024 20:35:14 +0100 Subject: [PATCH 02/78] refactoring --- rector.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/rector.php b/rector.php index 47b7a8886..d701f1146 100644 --- a/rector.php +++ b/rector.php @@ -11,6 +11,7 @@ use Rector\Php81\Rector\Property\ReadOnlyPropertyRector; use Rector\Set\ValueObject\LevelSetList; use Rector\Set\ValueObject\SetList; use Rector\Php81\Rector\FuncCall\NullToStrictStringFuncCallArgRector; +use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector; return RectorConfig::configure() ->withParallel(240, 8) @@ -34,7 +35,8 @@ return RectorConfig::configure() StringifyStrNeedlesRector::class, RestoreDefaultNullToNullableTypePropertyRector::class, ForRepeatedCountToOwnVariableRector::class, - SimplifyEmptyCheckOnEmptyArrayRector::class + SimplifyEmptyCheckOnEmptyArrayRector::class, + DisallowedEmptyRuleFixerRector::class ]) ->withFileExtensions([ 'php', From 002163e1e9de8e07aada0f7ad77f2acd4dc3f2fb Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sat, 7 Dec 2024 19:56:55 +0100 Subject: [PATCH 03/78] refactoring --- lam/lib/ldap.inc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lam/lib/ldap.inc b/lam/lib/ldap.inc index 8eb8003bd..67836edae 100644 --- a/lam/lib/ldap.inc +++ b/lam/lib/ldap.inc @@ -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; } } From 6323c4fcd8cbd1b78c51d34bafe530cfe9aa5310 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sat, 7 Dec 2024 20:09:55 +0100 Subject: [PATCH 04/78] refactoring --- lam/lib/types/dhcp.inc | 10 ++++------ lam/lib/types/group.inc | 29 ++++++++++++----------------- lam/lib/types/netgroup.inc | 2 +- lam/lib/types/smbDomain.inc | 2 +- lam/lib/types/user.inc | 13 +++++-------- 5 files changed, 23 insertions(+), 33 deletions(-) diff --git a/lam/lib/types/dhcp.inc b/lam/lib/types/dhcp.inc index b2ed96405..1500711ed 100644 --- a/lam/lib/types/dhcp.inc +++ b/lam/lib/types/dhcp.inc @@ -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; } } } diff --git a/lam/lib/types/group.inc b/lam/lib/types/group.inc index be392a608..a553290a5 100644 --- a/lam/lib/types/group.inc +++ b/lam/lib/types/group.inc @@ -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] = "" . $user . ""; @@ -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]; } } diff --git a/lam/lib/types/netgroup.inc b/lam/lib/types/netgroup.inc index 7f67199be..2f541eda0 100644 --- a/lam/lib/types/netgroup.inc +++ b/lam/lib/types/netgroup.inc @@ -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; diff --git a/lam/lib/types/smbDomain.inc b/lam/lib/types/smbDomain.inc index b3b814e29..74bd0b13c 100644 --- a/lam/lib/types/smbDomain.inc +++ b/lam/lib/types/smbDomain.inc @@ -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; diff --git a/lam/lib/types/user.inc b/lam/lib/types/user.inc index a28bb1bcf..3b82d1228 100644 --- a/lam/lib/types/user.inc +++ b/lam/lib/types/user.inc @@ -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'; } /** From 363b33417e995a4e63af401ee33c269a4f7ce547 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sat, 7 Dec 2024 20:11:30 +0100 Subject: [PATCH 05/78] refactoring --- lam/lib/tools/fileUpload.inc | 2 +- lam/lib/tools/ouEditor.inc | 2 +- lam/lib/tools/pdfEdit.inc | 2 +- lam/lib/tools/profileEditor.inc | 2 +- lam/lib/tools/tests.inc | 2 +- lam/lib/tools/treeview.inc | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lam/lib/tools/fileUpload.inc b/lam/lib/tools/fileUpload.inc index b0399a950..633659a6a 100644 --- a/lam/lib/tools/fileUpload.inc +++ b/lam/lib/tools/fileUpload.inc @@ -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); } } diff --git a/lam/lib/tools/ouEditor.inc b/lam/lib/tools/ouEditor.inc index be3bac4f0..b3f17d99c 100644 --- a/lam/lib/tools/ouEditor.inc +++ b/lam/lib/tools/ouEditor.inc @@ -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); } } diff --git a/lam/lib/tools/pdfEdit.inc b/lam/lib/tools/pdfEdit.inc index f1f6354dd..8b3c0e9af 100644 --- a/lam/lib/tools/pdfEdit.inc +++ b/lam/lib/tools/pdfEdit.inc @@ -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); } } diff --git a/lam/lib/tools/profileEditor.inc b/lam/lib/tools/profileEditor.inc index 4401c4a6f..09ca1b5af 100644 --- a/lam/lib/tools/profileEditor.inc +++ b/lam/lib/tools/profileEditor.inc @@ -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); } } diff --git a/lam/lib/tools/tests.inc b/lam/lib/tools/tests.inc index 4a9e72605..c3c79bb3d 100644 --- a/lam/lib/tools/tests.inc +++ b/lam/lib/tools/tests.inc @@ -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); } } diff --git a/lam/lib/tools/treeview.inc b/lam/lib/tools/treeview.inc index d856b60c5..6b57ad2e4 100644 --- a/lam/lib/tools/treeview.inc +++ b/lam/lib/tools/treeview.inc @@ -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; From e881ed73e44bf3e5cdb99b7366d86bfbfd2236bf Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sat, 7 Dec 2024 20:17:53 +0100 Subject: [PATCH 06/78] refactoring --- lam/lib/schema.inc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lam/lib/schema.inc b/lam/lib/schema.inc index 7a7e1067f..0ab198033 100644 --- a/lam/lib/schema.inc +++ b/lam/lib/schema.inc @@ -1,4 +1,5 @@ Date: Sat, 7 Dec 2024 20:25:54 +0100 Subject: [PATCH 07/78] refactoring --- lam/lib/adminHeader.inc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lam/lib/adminHeader.inc b/lam/lib/adminHeader.inc index 83833a06c..51aef433a 100644 --- a/lam/lib/adminHeader.inc +++ b/lam/lib/adminHeader.inc @@ -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);"); From f47f2f1c50ab15573898703b9da21f4f49ced92e Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sat, 7 Dec 2024 20:51:27 +0100 Subject: [PATCH 08/78] refactoring --- lam/lib/account.inc | 8 ++++---- lam/tests/lib/AccountTest.php | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/lam/lib/account.inc b/lam/lib/account.inc index 4ba08b22d..149074836 100644 --- a/lam/lib/account.inc +++ b/lam/lib/account.inc @@ -584,18 +584,18 @@ 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 'groupnameList': // comma separated list of group names diff --git a/lam/tests/lib/AccountTest.php b/lam/tests/lib/AccountTest.php index d5544e1bb..53ab776b0 100644 --- a/lam/tests/lib/AccountTest.php +++ b/lam/tests/lib/AccountTest.php @@ -252,4 +252,23 @@ class AccountTest extends TestCase { $this->assertEquals(20, strlen(generateRandomText(20))); } + function testGetPreg() { + $this->assertTrue(get_preg('abc123', 'password')); + $this->assertTrue(get_preg('abc ^|#*,.;:_+!%&/?{}()[]$§°@=-123', 'password')); + $this->assertFalse(get_preg('abc\\123', 'password')); + + $this->assertTrue(get_preg('abc123', 'username')); + $this->assertTrue(get_preg('abc%#@. _$-123', 'username')); + $this->assertFalse(get_preg('abc?123', 'username')); + + $this->assertTrue(get_preg('abc123', 'krbUserName')); + $this->assertTrue(get_preg('abc#@. _$-123', 'krbUserName')); + $this->assertFalse(get_preg('abc?123', 'krbUserName')); + + $this->assertTrue(get_preg('abc123', 'hostObject')); + $this->assertTrue(get_preg('!abc123', 'hostObject')); + $this->assertTrue(get_preg('abc@. _$:*-123', 'hostObject')); + $this->assertFalse(get_preg('abc!123', 'hostObject')); + } + } From 53b3c67ed44298861b7325b98ab8a19239c18528 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sat, 7 Dec 2024 21:04:03 +0100 Subject: [PATCH 09/78] refactoring --- lam/lib/account.inc | 6 +++--- lam/tests/lib/AccountTest.php | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/lam/lib/account.inc b/lam/lib/account.inc index 149074836..43de5cf0f 100644 --- a/lam/lib/account.inc +++ b/lam/lib/account.inc @@ -597,13 +597,13 @@ function get_preg($argument, $regexp) { case 'hostObject': $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\\.\\ \\(\\)\\/-])*$/'; diff --git a/lam/tests/lib/AccountTest.php b/lam/tests/lib/AccountTest.php index 53ab776b0..b2c1b4b88 100644 --- a/lam/tests/lib/AccountTest.php +++ b/lam/tests/lib/AccountTest.php @@ -269,6 +269,23 @@ class AccountTest extends TestCase { $this->assertTrue(get_preg('!abc123', 'hostObject')); $this->assertTrue(get_preg('abc@. _$:*-123', 'hostObject')); $this->assertFalse(get_preg('abc!123', 'hostObject')); + + $this->assertTrue(get_preg('abc123', 'usernameList')); + $this->assertTrue(get_preg('abc123,def456', 'usernameList')); + $this->assertTrue(get_preg('abc123,def456,ghi789', 'usernameList')); + $this->assertTrue(get_preg('abc%#@. _-123,def%#@. _-456,ghi%#@. _-789', 'usernameList')); + $this->assertFalse(get_preg('abc!123', 'usernameList')); + $this->assertFalse(get_preg('abcdef,abc!123', 'usernameList')); + + $this->assertTrue(get_preg('abc123', 'cn')); + $this->assertTrue(get_preg('abc123$', 'cn')); + $this->assertTrue(get_preg('abc#@. _-123', 'cn')); + $this->assertFalse(get_preg('abc\123', 'cn')); + $this->assertFalse(get_preg('abc<123', 'cn')); + $this->assertFalse(get_preg('abc>123', 'cn')); + $this->assertFalse(get_preg('abc=123', 'cn')); + $this->assertFalse(get_preg('abc$123', 'cn')); + $this->assertFalse(get_preg('abc?123', 'cn')); } } From e7400e4f6d0dbfd7b2b84313d5b558e47703e6a7 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Mon, 9 Dec 2024 07:53:23 +0100 Subject: [PATCH 10/78] refactoring --- lam/lib/account.inc | 43 ++++++++++++++++------------------- lam/tests/lib/AccountTest.php | 37 ++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 23 deletions(-) diff --git a/lam/lib/account.inc b/lam/lib/account.inc index 43de5cf0f..3e7ff4d42 100644 --- a/lam/lib/account.inc +++ b/lam/lib/account.inc @@ -606,33 +606,33 @@ function get_preg($argument, $regexp) { $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 +644,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][0-9])|30|31)-((0?[1-9])|(1[0-2]))-[1-3][0-9][0-9][0-9]$/'; 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][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]))$/'; break; case 'sambaLogonHours': $pregexpr = '/^[0-9a-fA-F]{42}$/'; @@ -683,10 +680,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,7 +692,7 @@ 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-[0-9]-[0-9]-[0-9]{2,2}-[0-9]+-[0-9]+-[0-9]+$/"; break; case 'ip': // IP address $pregexpr = '/^[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}$/'; @@ -713,7 +710,7 @@ 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$/'; diff --git a/lam/tests/lib/AccountTest.php b/lam/tests/lib/AccountTest.php index b2c1b4b88..c3bcc63e4 100644 --- a/lam/tests/lib/AccountTest.php +++ b/lam/tests/lib/AccountTest.php @@ -286,6 +286,43 @@ class AccountTest extends TestCase { $this->assertFalse(get_preg('abc=123', 'cn')); $this->assertFalse(get_preg('abc$123', 'cn')); $this->assertFalse(get_preg('abc?123', 'cn')); + + $this->assertTrue(get_preg('abc123ABC', 'telephone')); + $this->assertTrue(get_preg('abc -.(123)12/3', 'telephone')); + $this->assertFalse(get_preg('abc?123', 'telephone')); + + $this->assertTrue(get_preg('abc@abc123.com', 'email')); + $this->assertTrue(get_preg('ab!~#+*%$/._-c@abc123.com', 'email')); + $this->assertFalse(get_preg('abc?abc123.com', 'email')); + $this->assertFalse(get_preg('abc@abc~123.com', 'email')); + $this->assertFalse(get_preg('abc', 'email')); + + $this->assertTrue(get_preg('abc abc ', 'emailWithName')); + $this->assertTrue(get_preg('abc \'!~#+*%$()_- abc ', 'emailWithName')); + $this->assertFalse(get_preg('abc ', 'emailWithName')); + $this->assertFalse(get_preg('abc ', 'emailWithName')); + $this->assertFalse(get_preg('abc ', 'emailWithName')); + $this->assertFalse(get_preg('a?bc ', 'emailWithName')); + + $this->assertTrue(get_preg('31-12-2012', 'date')); + $this->assertTrue(get_preg('01-02-2012', 'date')); + $this->assertTrue(get_preg('1-2-2012', 'date')); + $this->assertFalse(get_preg('42-20-9999', 'date')); + $this->assertFalse(get_preg('10-10-12345', 'date')); + + $this->assertTrue(get_preg('2012-12-31 10:11:30', 'dateTime')); + $this->assertTrue(get_preg('2012-01-02 10:11:30', 'dateTime')); + $this->assertTrue(get_preg('2012-02-01 10:11:30', 'dateTime')); + $this->assertFalse(get_preg('2012-2-1 10:11:30', 'dateTime')); + $this->assertFalse(get_preg('9999-20-41 10:11:30', 'dateTime')); + $this->assertFalse(get_preg('12345-10-10 10:11:30', 'dateTime')); + $this->assertFalse(get_preg('1234-10-10 99:11:30', 'dateTime')); + + $this->assertTrue(get_preg('abc.123:6567', 'hostAndPort')); + $this->assertTrue(get_preg('ab_-c.123:132', 'hostAndPort')); + $this->assertFalse(get_preg('abc', 'hostAndPort')); + $this->assertFalse(get_preg('abc:abc', 'hostAndPort')); + $this->assertFalse(get_preg('ab?c:80', 'hostAndPort')); } } From c959f4e022ef94e9d3f1ecaeb33adb39af215f77 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Mon, 9 Dec 2024 07:58:07 +0100 Subject: [PATCH 11/78] refactoring --- lam/lib/account.inc | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lam/lib/account.inc b/lam/lib/account.inc index 3e7ff4d42..be175857f 100644 --- a/lam/lib/account.inc +++ b/lam/lib/account.inc @@ -467,16 +467,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('/[0-9]/', $password)) { $classesCount++; } - if (preg_match("/[^a-z0-9]/i", $password)) { + if (preg_match('/[^a-z0-9]/i', $password)) { $classesCount++; } return $classesCount; From dbead8ef94fe11ecf477c8f6dd0b9cca2e4298f0 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Mon, 9 Dec 2024 16:56:18 +0100 Subject: [PATCH 12/78] refactoring --- lam/lib/account.inc | 119 +++++++++++++++++++------------------------- 1 file changed, 52 insertions(+), 67 deletions(-) diff --git a/lam/lib/account.inc b/lam/lib/account.inc index be175857f..b26b844c2 100644 --- a/lam/lib/account.inc +++ b/lam/lib/account.inc @@ -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]; @@ -473,7 +466,7 @@ function getNumberOfCharacterClasses($password): int { 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)) { @@ -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]; @@ -668,10 +661,10 @@ function get_preg($argument, $regexp) { $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]$/'; + $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}$/'; @@ -692,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,13 +706,13 @@ function get_preg($argument, $regexp) { $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 @@ -735,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); } /** @@ -806,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(); @@ -879,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); @@ -1003,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(); @@ -1039,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]; } } @@ -1152,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++) { @@ -1162,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']); @@ -1188,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]; } } @@ -1229,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 @@ -1243,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; } @@ -1429,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]); } @@ -1473,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); } } @@ -1516,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); @@ -1712,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); @@ -1783,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; @@ -1902,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; @@ -1929,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; From b2f35cd68232ed153d53d26ae55c3747b70190b5 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Mon, 9 Dec 2024 17:04:44 +0100 Subject: [PATCH 13/78] refactoring --- lam/lib/baseModule.inc | 94 ++++++++++++++++++------------------------ 1 file changed, 40 insertions(+), 54 deletions(-) diff --git a/lam/lib/baseModule.inc b/lam/lib/baseModule.inc index 1c7bfa619..e6bcf431f 100644 --- a/lam/lib/baseModule.inc +++ b/lam/lib/baseModule.inc @@ -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('
', $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", '
', $value); - $field = new htmlOutputText($value, false); - } + $value = htmlspecialchars($value); + $value = str_replace("\n", '
', $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'); From 26f6931e2b53ec50b412a1b7c66e7891a7818b01 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Mon, 9 Dec 2024 17:21:07 +0100 Subject: [PATCH 14/78] refactoring --- lam/lib/checkEnvironment.inc | 4 +- lam/lib/config.inc | 125 ++++++++++++++--------------------- lam/lib/cronRunner.inc | 4 +- 3 files changed, 52 insertions(+), 81 deletions(-) diff --git a/lam/lib/checkEnvironment.inc b/lam/lib/checkEnvironment.inc index 4edaaf6b2..77f09257b 100644 --- a/lam/lib/checkEnvironment.inc +++ b/lam/lib/checkEnvironment.inc @@ -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."]; diff --git a/lam/lib/config.inc b/lam/lib/config.inc index 120468e60..153274a3c 100644 --- a/lam/lib/config.inc +++ b/lam/lib/config.inc @@ -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.'), $e->getCode(), $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.'), $e->getCode(), $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; diff --git a/lam/lib/cronRunner.inc b/lam/lib/cronRunner.inc index d96ca4372..ab1ddf388 100644 --- a/lam/lib/cronRunner.inc +++ b/lam/lib/cronRunner.inc @@ -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(), $e->getCode(), $e); } catch (LAMException $e) { - throw new LAMException("Unable to connect to database. " . $e->getTitle()); + throw new LAMException("Unable to connect to database. " . $e->getTitle(), $e->getCode(), $e); } // get jobs to run if (empty($cronDatabase->getJobs())) { From f472abaa55d8a3a76f5648b4a9bf769eb163172d Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Mon, 9 Dec 2024 17:30:54 +0100 Subject: [PATCH 15/78] refactoring --- lam/lib/export.inc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lam/lib/export.inc b/lam/lib/export.inc index 0b1cae01d..62ce93d04 100644 --- a/lam/lib/export.inc +++ b/lam/lib/export.inc @@ -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; From 56a8595e48dd8f8cf563f6a3bb3347365f3700a2 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Tue, 10 Dec 2024 07:42:24 +0100 Subject: [PATCH 16/78] refactoring --- lam/lib/html.inc | 119 ++++++++++++++++++++--------------------------- 1 file changed, 50 insertions(+), 69 deletions(-) diff --git a/lam/lib/html.inc b/lam/lib/html.inc index 79feaae87..5db15d67a 100644 --- a/lam/lib/html.inc +++ b/lam/lib/html.inc @@ -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[] = "\n"; - } - else { - $this->elements[] = self::NEWLINE; - } + $this->elements[] = $this->rowOpen ? self::NEWLINE : "\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 "\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[] = "\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 ''; - if (sizeof($this->elements) == 1) { + if (count($this->elements) == 1) { echo ' '; 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 = ''; } // 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 .= ' - - - + + + + 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']); diff --git a/lam/templates/config/confmodules.php b/lam/templates/config/confmodules.php index 0dd9e43a7..2dd643f42 100644 --- a/lam/templates/config/confmodules.php +++ b/lam/templates/config/confmodules.php @@ -1,5 +1,7 @@ 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 "\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++; } diff --git a/lam/templates/config/confsave.php b/lam/templates/config/confsave.php index 6b95518eb..a997b6f66 100644 --- a/lam/templates/config/confsave.php +++ b/lam/templates/config/confsave.php @@ -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]]); } diff --git a/lam/templates/config/conftypes.php b/lam/templates/config/conftypes.php index 5fbddd267..1745232ee 100644 --- a/lam/templates/config/conftypes.php +++ b/lam/templates/config/conftypes.php @@ -1,5 +1,7 @@ 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 diff --git a/lam/templates/config/index.php b/lam/templates/config/index.php index 60b3b2836..c524b601b 100644 --- a/lam/templates/config/index.php +++ b/lam/templates/config/index.php @@ -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()) { diff --git a/lam/templates/config/mainlogin.php b/lam/templates/config/mainlogin.php index 1c1f6df5c..533ed0a6f 100644 --- a/lam/templates/config/mainlogin.php +++ b/lam/templates/config/mainlogin.php @@ -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"), '../..'); ?> - - - -
-
- - help - + + + + -
- 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.')); - } + +
+ -
- -
- - + + + + +
- - + +
+ + menu +   + + + + 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); + } + ?> + +
+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.')); +} +?> +
+ + + + + - -
+ + + -
+ 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'); - ?> -
-
-
-
- + parseHtml(null, $div, [], false, 'user'); + ?> +
+
+
+
+ -



+



- + diff --git a/lam/templates/config/mainmanage.php b/lam/templates/config/mainmanage.php index 327e584a5..030d3a5c3 100644 --- a/lam/templates/config/mainmanage.php +++ b/lam/templates/config/mainmanage.php @@ -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')) { diff --git a/lam/templates/config/moduleSettings.php b/lam/templates/config/moduleSettings.php index f2a29a3f8..12fcc8fdf 100644 --- a/lam/templates/config/moduleSettings.php +++ b/lam/templates/config/moduleSettings.php @@ -1,5 +1,7 @@ - - - - + + + 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(); } } diff --git a/lam/templates/config/profmanage.php b/lam/templates/config/profmanage.php index 2f7ffe452..8f1699474 100644 --- a/lam/templates/config/profmanage.php +++ b/lam/templates/config/profmanage.php @@ -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(); From 7bdacedd50efc8d646979f521a5349d681479ce2 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 12 Dec 2024 16:46:10 +0100 Subject: [PATCH 36/78] refactoring --- lam/templates/lists/userlink.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lam/templates/lists/userlink.php b/lam/templates/lists/userlink.php index b158d15be..29f86d03c 100644 --- a/lam/templates/lists/userlink.php +++ b/lam/templates/lists/userlink.php @@ -80,7 +80,7 @@ else { */ function search_username(string $name): ?string { $entries = searchLDAPByAttribute('uid', $name, null, ['dn'], ['user']); - if (sizeof($entries) > 0 ) { + if (count($entries) > 0 ) { return $entries[0]['dn']; } else { From 91def59ae93285f488f43dd00cb671055c49b865 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 12 Dec 2024 18:42:13 +0100 Subject: [PATCH 37/78] refactoring --- lam/templates/misc/ajax.php | 48 ++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 28 deletions(-) diff --git a/lam/templates/misc/ajax.php b/lam/templates/misc/ajax.php index a7f7b22fc..3cb10166c 100644 --- a/lam/templates/misc/ajax.php +++ b/lam/templates/misc/ajax.php @@ -1,5 +1,7 @@ managePasswordChange(json_decode((string) $_POST['jsonInput'], true, 512, JSON_THROW_ON_ERROR)); } elseif ($function === 'import') { - include_once('../../lib/import.inc'); + include_once(__DIR__ . '/../../lib/import.inc'); $importer = new Importer(); ob_start(); $jsonOut = $importer->doImport(); @@ -139,7 +141,7 @@ class Ajax { echo $jsonOut; } elseif ($function === 'export') { - include_once('../../lib/export.inc'); + include_once(__DIR__ . '/../../lib/export.inc'); $attributes = $_POST['attributes']; $baseDn = $_POST['baseDn']; $ending = $_POST['ending']; @@ -155,7 +157,7 @@ class Ajax { echo $jsonOut; } elseif ($function === 'upload') { - include_once('../../lib/upload.inc'); + include_once(__DIR__ . '/../../lib/upload.inc'); $typeManager = new \LAM\TYPES\TypeManager(); $uploader = new \LAM\UPLOAD\Uploader($typeManager->getConfiguredType($_GET['typeId'])); ob_start(); @@ -199,8 +201,8 @@ class Ajax { * * @param array $input input parameters */ - private static function managePasswordChange(array $input): void { - $sessionKey = htmlspecialchars((string) $_GET['editKey']); + private function managePasswordChange(array $input): void { + $sessionKey = htmlspecialchars((string) $_GET['editKey']); $return = $_SESSION[$sessionKey]->setNewPassword($input); echo json_encode($return, JSON_THROW_ON_ERROR); } @@ -309,7 +311,7 @@ class Ajax { $delButton->addDataAttribute('oktext', _('Ok')); $delButton->addDataAttribute('canceltext', _('Cancel')); $delButton->setCSSClasses(['webauthn-delete']); - $name = !empty($result['name']) ? $result['name'] : ''; + $name = empty($result['name']) ? '' : $result['name']; $data[] = [ new htmlOutputText($result['dn']), new htmlOutputText($name), @@ -408,12 +410,7 @@ class Ajax { */ private function dnSelection(): string { $dn = trim((string) $_POST['dn']); - if (empty($dn) || !get_preg($dn, 'dn')) { - $dnList = $this->getDefaultDns(); - } - else { - $dnList = $this->getSubDns($dn); - } + $dnList = (empty($dn) || !get_preg($dn, 'dn')) ? $this->getDefaultDns() : $this->getSubDns($dn); $html = $this->buildDnSelectionHtml($dnList, $dn); return json_encode(['dialogData' => $html], JSON_THROW_ON_ERROR); } @@ -452,8 +449,8 @@ class Ajax { $fieldId = trim((string) $_POST['fieldId']); $mainRow = new htmlResponsiveRow(); $onclickUp = 'window.lam.html.updateDnSelection(this, \'' - . htmlspecialchars($fieldId) . '\', \'' . getSecurityTokenName() . '\', \'' - . getSecurityTokenValue() . '\')'; + . htmlspecialchars($fieldId) . '\', \'' . getSecurityTokenName() . '\', \'' + . getSecurityTokenValue() . '\')'; if (!empty($currentDn)) { $row = new htmlResponsiveRow(); $row->addDataAttribute('dn', $currentDn); @@ -525,12 +522,7 @@ class Ajax { * Dies if password is not set. */ private function enforceUserIsLoggedInToMainConfiguration(): void { - if (!isset($_SESSION['cfgMain'])) { - $cfg = new LAMCfgMain(); - } - else { - $cfg = $_SESSION['cfgMain']; - } + $cfg = $_SESSION['cfgMain'] ?? new LAMCfgMain(); if (isset($_SESSION["mainconf_password"]) && ($cfg->checkPassword($_SESSION["mainconf_password"]))) { return; } @@ -540,7 +532,7 @@ class Ajax { /** * Checks if the given password matches the hash value. */ - private function checkPassword() : void { + private function checkPassword(): void { $hashValue = $_POST['hashValue']; $checkValue = $_POST['checkValue']; $hashPart = preg_replace('/^\\{([A-Z0-9-]+)\\}[!]?/', '', $hashValue); From 4b9a1b086390c2be98e901aff744242181a22733 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 12 Dec 2024 18:46:48 +0100 Subject: [PATCH 38/78] refactoring --- lam/templates/pdfedit/pdfmain.php | 4 +- lam/templates/pdfedit/pdfpage.php | 152 ++++++++++++------------- lam/templates/profedit/profilemain.php | 2 +- lam/templates/profedit/profilepage.php | 61 +++++----- 4 files changed, 107 insertions(+), 112 deletions(-) diff --git a/lam/templates/pdfedit/pdfmain.php b/lam/templates/pdfedit/pdfmain.php index 877614f49..74d9ac89e 100644 --- a/lam/templates/pdfedit/pdfmain.php +++ b/lam/templates/pdfedit/pdfmain.php @@ -296,7 +296,7 @@ if (!empty($_POST['importLogoSourceProfile'])) { try { foreach ($_POST['importLogoSourceProfile'] as $sourceLogo) { $parts = explode('##', $sourceLogo); - if (sizeof($parts) !== 2) { + if (count($parts) !== 2) { continue; } $profileName = $parts[0]; @@ -384,7 +384,7 @@ include __DIR__ . '/../../lib/adminHeader.inc'; $deleteLink->setCSSClasses(['margin3']); $buttonGroup->addElement($deleteLink); - if (sizeof($configProfiles) > 1) { + if (count($configProfiles) > 1) { $importLink = new htmlLink(null, '#', '../../graphics/import.svg'); $importLink->setTitle(_('Import PDF structures')); $importLink->setOnClick("window.lam.profilePdfEditor.showDistributionDialog('" . _("Import PDF structures") . "', '" . diff --git a/lam/templates/pdfedit/pdfpage.php b/lam/templates/pdfedit/pdfpage.php index 0dc296860..f82baa3ea 100644 --- a/lam/templates/pdfedit/pdfpage.php +++ b/lam/templates/pdfedit/pdfpage.php @@ -1,5 +1,7 @@ isHidden() || !checkIfWriteAccessIsAllowed($type->getId())) { // Abort and go back to main pdf structure page -if(isset($_GET['abort'])) { +if (isset($_GET['abort'])) { metarefresh('pdfmain.php'); exit; } @@ -113,19 +115,19 @@ if (!isset($_SESSION['currentPDFStructure'])) { try { if (isset($_GET['edit'])) { $_SESSION['currentPDFStructure'] = $pdfStructurePersistenceManager->readPdfStructure($_SESSION['config']->getName(), - $type->getId(), $_GET['edit']); + $type->getId(), $_GET['edit']); } // Load default structure file when creating a new one else { - $structureNames = $pdfStructurePersistenceManager->getPDFStructures($_SESSION['config']->getName(), - $type->getId()); - if (in_array('default', $structureNames)) { - $_SESSION['currentPDFStructure'] = $pdfStructurePersistenceManager->readPdfStructure($_SESSION['config']->getName(), - $type->getId(), 'default'); - } - else { - $_SESSION['currentPDFStructure'] = new PDFStructure(); - } + $structureNames = $pdfStructurePersistenceManager->getPDFStructures($_SESSION['config']->getName(), + $type->getId()); + if (in_array('default', $structureNames)) { + $_SESSION['currentPDFStructure'] = $pdfStructurePersistenceManager->readPdfStructure($_SESSION['config']->getName(), + $type->getId(), 'default'); + } + else { + $_SESSION['currentPDFStructure'] = new PDFStructure(); + } } } catch (LAMException $e) { @@ -149,9 +151,9 @@ if (!empty($_POST['form_submit'])) { // Check if pdfname is valid, then save current structure to file and go to // main pdf structure page $saveErrors = []; -if(isset($_GET['submit'])) { +if (isset($_GET['submit'])) { try { - $pdfStructurePersistenceManager->savePdfStructure($_SESSION['config']->getName(), $type->getId(), $_POST['pdfname'], $_SESSION['currentPDFStructure']); + $pdfStructurePersistenceManager->savePdfStructure($_SESSION['config']->getName(), $type->getId(), $_POST['pdfname'], $_SESSION['currentPDFStructure']); unset($_SESSION['currentPDFStructure']); metaRefresh('pdfmain.php?savedSuccessfully=' . $_POST['pdfname']); exit; @@ -169,40 +171,35 @@ $modules = []; $section_items_array = []; $section_items = ''; $sortedModules = []; -foreach($availablePDFFields as $module => $fields) { - if ($module != 'main') { - $title = getModuleAlias($module, $type->getScope()); - } - else { - $title = _('Main'); - } +foreach ($availablePDFFields as $module => $fields) { + $title = ($module != 'main') ? getModuleAlias($module, $type->getScope()) : _('Main'); $sortedModules[$module] = $title; } natcasesort($sortedModules); -foreach($sortedModules as $module => $title) { +foreach ($sortedModules as $module => $title) { $values = $availablePDFFields[$module]; - if (!is_array($values) || (sizeof($values) < 1)) { + if (!is_array($values) || (count($values) < 1)) { continue; } $modules[] = $module; $section_items .= ""; natcasesort($values); - foreach($values as $attribute => $attributeLabel) { + foreach ($values as $attribute => $attributeLabel) { $section_items_array[] = $module . '_' . $attribute; $section_items .= "\n"; } $section_items .= "\n"; } -$modules = join(',',$modules); +$modules = implode(',', $modules); // print header include __DIR__ . '/../../lib/adminHeader.inc'; ?> -
- + 0) { +if ($saveErrors !== []) { foreach ($saveErrors as $saveError) { call_user_func_array(StatusMessage(...), $saveError); } @@ -210,9 +207,9 @@ if (sizeof($saveErrors) > 0) { } $newFieldFieldElements = []; -foreach($sortedModules as $module => $title) { +foreach ($sortedModules as $module => $title) { $fields = $availablePDFFields[$module]; - if (isset($fields) && is_array($fields) && (sizeof($fields) > 0)) { + if (isset($fields) && is_array($fields) && ($fields !== [])) { $moduleFields = []; foreach ($fields as $field => $fieldLabel) { $moduleFields[$fieldLabel] = $module . "_" . $field; @@ -226,14 +223,14 @@ $structureName = ''; if (isset($_GET['edit'])) { $structureName = $_GET['edit']; } -else if (isset($_POST['pdfname'])) { +elseif (isset($_POST['pdfname'])) { $structureName = $_POST['pdfname']; } // headline $headline = $_SESSION['currentPDFStructure']->getTitle(); // logo $logos = [_('No logo') => 'none']; -foreach($logoFiles as $logoFile) { +foreach ($logoFiles as $logoFile) { $logos[$logoFile->getName() . ' (' . $logoFile->getWidth() . ' x ' . $logoFile->getHeight() . ")"] = $logoFile->getName(); } $selectedLogo = ['printLogo.jpg']; @@ -242,8 +239,9 @@ if (isset($_SESSION['currentPDFStructure'])) { } ?> -
- + getFoldingMarks(); } $possibleFoldingMarks = [ - _('No') => PDFStructure::FOLDING_NONE, - _('Yes') => PDFStructure::FOLDING_STANDARD + _('No') => PDFStructure::FOLDING_NONE, + _('Yes') => PDFStructure::FOLDING_STANDARD ]; $foldingMarksSelect = new htmlResponsiveSelect('foldingmarks', $possibleFoldingMarks, [$foldingMarks], _('Folding marks')); $foldingMarksSelect->setHasDescriptiveElements(true); @@ -286,8 +284,8 @@ foreach ($sections as $key => $section) { $linkRemove->setTitle(_("Remove")); $emptyBox = new htmlSpacer('19px', null); // We have a new section to start - if($section instanceof PDFEntrySection) { - if($section->isAttributeTitle()) { + if ($section instanceof PDFEntrySection) { + if ($section->isAttributeTitle()) { $section_headline = translateFieldIDToName($section->getPdfKey(), $type->getScope(), $availablePDFFields); if ($section_headline === null) { continue; @@ -300,9 +298,9 @@ foreach ($sections as $key => $section) { $sectionElements[$section_headline] = $key; $structureContent->addVerticalSpacer('2rem'); // Section headline is a value entry - if($section->isAttributeTitle()) { + if ($section->isAttributeTitle()) { $headlineElements = []; - foreach($section_items_array as $item) { + foreach ($section_items_array as $item) { $headlineElements[translateFieldIDToName($item, $type->getScope(), $availablePDFFields)] = '_' . $item; } $sectionHeadlineSelect = new htmlSelect('section_' . $key, $headlineElements, ['_' . $section->getPdfKey()]); @@ -321,7 +319,7 @@ foreach ($sections as $key => $section) { else { $actionGroup->addElement($emptyBox); } - $hasAdditionalSections = $key < (sizeof($sections) - 1); + $hasAdditionalSections = $key < (count($sections) - 1); if ($hasAdditionalSections) { $actionGroup->addElement($linkDown); } @@ -349,7 +347,7 @@ foreach ($sections as $key => $section) { else { $actionGroup->addElement($emptyBox); } - if ($e < (sizeof($sectionEntries) - 1)) { + if ($e < (count($sectionEntries) - 1)) { $linkDown = new htmlButton('down_entry_' . $key . '_' . $e, 'down.svg', true); $linkDown->setTitle(_("Down")); $actionGroup->addElement($linkDown); @@ -364,7 +362,7 @@ foreach ($sections as $key => $section) { } } // We have to include a static text. - elseif($section instanceof PDFTextSection) { + elseif ($section instanceof PDFTextSection) { // Add current satic text for dropdown box needed for the position when inserting a new // section or static text entry $textSnippet = $section->getText(); @@ -384,7 +382,7 @@ foreach ($sections as $key => $section) { else { $actionGroup->addElement($emptyBox); } - if ($key != sizeof($sections) - 1) { + if ($key != count($sections) - 1) { $actionGroup->addElement($linkDown); } else { @@ -398,7 +396,7 @@ foreach ($sections as $key => $section) { $structureContent->add($staticTextOutput, 12); } } -$sectionElements[_('End')] = sizeof($structure->getSections()); +$sectionElements[_('End')] = count($structure->getSections()); $mainContent->add($structureContent, 12); $container->add($mainContent, 12); $container->addVerticalSpacer('2rem'); @@ -476,9 +474,9 @@ $buttonContainer->add(new htmlHiddenInput('form_submit', 'true'), 4); $container->add($buttonContainer, 12); addSecurityTokenToMetaHTML($container); -if ((sizeof($saveErrors) == 0) && isset($_POST['scrollPositionTop']) && isset($_POST['scrollPositionLeft'])) { +if ((count($saveErrors) == 0) && isset($_POST['scrollPositionTop']) && isset($_POST['scrollPositionLeft'])) { // scroll to last position - $container->add(new htmlJavaScript('window.lam.utility.restoreScrollPosition(' . $_POST['scrollPositionTop'] .', ' . $_POST['scrollPositionLeft'] . ')')); + $container->add(new htmlJavaScript('window.lam.utility.restoreScrollPosition(' . $_POST['scrollPositionTop'] . ', ' . $_POST['scrollPositionLeft'] . ')')); } parseHtml(null, $container, [], false, $type->getScope()); @@ -501,11 +499,11 @@ function translateFieldIDToName($id, $scope, $availablePDFFields): ?string { continue; } foreach ($fields as $name => $label) { - if ($id == $module . '_' . $name) { + if ($id === $module . '_' . $name) { if ($module == 'main') { return _('Main') . ': ' . $label; } - else { + else { return getModuleAlias($module, $scope) . ': ' . $label; } } @@ -527,19 +525,19 @@ function updateBasicSettings(PDFStructure &$structure, array $logoFiles): void { } // set logo if (isset($_POST['logoFile'])) { - $fileName = $_POST['logoFile']; - if ($fileName !== 'none') { - $found = false; - foreach ($logoFiles as $logoFile) { - if ($logoFile->getName() === $fileName) { - $found = true; - } - } - if (!$found) { - logNewMessage(LOG_ERR, 'Invalid PDF logo file: ' . $fileName); - return; - } - } + $fileName = $_POST['logoFile']; + if ($fileName !== 'none') { + $found = false; + foreach ($logoFiles as $logoFile) { + if ($logoFile->getName() === $fileName) { + $found = true; + } + } + if (!$found) { + logNewMessage(LOG_ERR, 'Invalid PDF logo file: ' . $fileName); + return; + } + } $structure->setLogo($fileName); } // set folding marks @@ -571,10 +569,10 @@ function updateSectionTitles(PDFStructure &$structure): void { function addSection(PDFStructure &$structure): void { $sections = $structure->getSections(); // add a new text field - if(isset($_POST['add_text'])) { + if (isset($_POST['add_text'])) { // Check if text for static text field is specified - if(empty($_POST['text_text'])) { - StatusMessage('ERROR',_('No static text specified'),_('The static text must contain at least one character.')); + if (empty($_POST['text_text'])) { + StatusMessage('ERROR', _('No static text specified'), _('The static text must contain at least one character.')); } else { $section = new PDFTextSection(str_replace("\r", "", $_POST['text_text'])); @@ -583,10 +581,10 @@ function addSection(PDFStructure &$structure): void { } } // add a new section with text headline - elseif(isset($_POST['add_sectionText'])) { + elseif (isset($_POST['add_sectionText'])) { // Check if name for new section is specified when needed - if(empty($_POST['new_section_text'])) { - StatusMessage('ERROR',_('No section text specified'),_('The headline for a new section must contain at least one character.')); + if (empty($_POST['new_section_text'])) { + StatusMessage('ERROR', _('No section text specified'), _('The headline for a new section must contain at least one character.')); } else { $section = new PDFEntrySection($_POST['new_section_text']); @@ -595,7 +593,7 @@ function addSection(PDFStructure &$structure): void { } } // Add a new section with item as headline - elseif(isset($_POST['add_section'])) { + elseif (isset($_POST['add_section'])) { $section = new PDFEntrySection('_' . $_POST['new_section_item']); array_splice($sections, $_POST['add_section_position'], 0, [$section]); $structure->setSections($sections); @@ -626,7 +624,7 @@ function addSectionEntry(PDFStructure &$structure): void { */ function removeItem(PDFStructure &$structure): void { $sections = $structure->getSections(); - foreach ($_POST as $key => $value) { + foreach (array_keys($_POST) as $key) { // remove section if (str_starts_with($key, 'remove_section_')) { $pos = substr($key, strlen('remove_section_')); @@ -656,7 +654,7 @@ function removeItem(PDFStructure &$structure): void { */ function moveUp(PDFStructure &$structure): void { $sections = $structure->getSections(); - foreach ($_POST as $key => $value) { + foreach (array_keys($_POST) as $key) { // move section if (str_starts_with($key, 'up_section_')) { $pos = intval(substr($key, strlen('up_section_'))); @@ -688,7 +686,7 @@ function moveUp(PDFStructure &$structure): void { */ function moveDown(PDFStructure &$structure): void { $sections = $structure->getSections(); - foreach ($_POST as $key => $value) { + foreach (array_keys($_POST) as $key) { // move section if (str_starts_with($key, 'down_section_')) { $pos = intval(substr($key, strlen('down_section_'))); diff --git a/lam/templates/profedit/profilemain.php b/lam/templates/profedit/profilemain.php index 209080d6d..72a930705 100644 --- a/lam/templates/profedit/profilemain.php +++ b/lam/templates/profedit/profilemain.php @@ -269,7 +269,7 @@ foreach ($profileClasses as $profileClass) { $deleteLink->setOnClick("profileShowDeleteDialog('" . _('Delete') . "', '" . _('Ok') . "', '" . _('Cancel') . "', '" . $profileClass['typeId'] . "', '" . 'profile_' . $profileClass['typeId'] . "'); return false;"); $deleteLink->setCSSClasses(['margin3']); $buttonGroup->addElement($deleteLink); - if (sizeof($configProfiles) > 1) { + if (count($configProfiles) > 1) { $importLink = new htmlLink(null, '#', '../../graphics/import.svg'); $importLink->setTitle(_('Import profiles')); $importLink->setOnClick("window.lam.profilePdfEditor.showDistributionDialog('" . _("Import profiles") . "', '" . diff --git a/lam/templates/profedit/profilepage.php b/lam/templates/profedit/profilepage.php index e17b812f1..43dbcc434 100644 --- a/lam/templates/profedit/profilepage.php +++ b/lam/templates/profedit/profilepage.php @@ -1,5 +1,6 @@ writeAccountProfile($_POST['accounttype'], $_POST['profname'], $_SESSION['config']->getName(), $options); - metaRefresh('profilemain.php?savedSuccessfully=' . $_POST['profname']); - exit(); - } - catch (LAMException $e) { - logNewMessage(LOG_ERR, $e->getTitle()); - $errors[] = ["ERROR", _("Unable to save profile!"), $_POST['profname']]; - } + try { + $accountProfilePersistenceManager->writeAccountProfile($_POST['accounttype'], $_POST['profname'], $_SESSION['config']->getName(), $options); + metaRefresh('profilemain.php?savedSuccessfully=' . $_POST['profname']); + exit(); + } + catch (LAMException $e) { + logNewMessage(LOG_ERR, $e->getTitle()); + $errors[] = ["ERROR", _("Unable to save profile!"), $_POST['profname']]; + } } } @@ -149,7 +150,7 @@ include __DIR__ . '/../../lib/adminHeader.inc'; echo '
'; // print error messages if any -if (sizeof($errors) > 0) { +if (count($errors) > 0) { echo "
\n"; foreach ($errors as $error) { call_user_func_array(StatusMessage(...), $error); @@ -166,19 +167,15 @@ $options = getProfileOptions($type->getId()); $old_options = []; if (isset($_POST['save'])) { foreach ($_POST as $key => $value) { - if (!is_array($value)) { - $old_options[$key] = [$value]; - } - else { - $old_options[$key] = $value; - } + $old_options[$key] = is_array($value) ? $value : [$value]; } } elseif (isset($_GET['edit'])) { try { $old_options = $accountProfilePersistenceManager->loadAccountProfile($type->getId(), $_GET['edit'], $_SESSION['config']->getName()); - } catch (LAMException $e) { - StatusMessage('ERROR', $e->getTitle(), $e->getMessage()); + } + catch (LAMException $e) { + StatusMessage('ERROR', $e->getTitle(), $e->getMessage()); } } From 3729b3639f374e558701513960eb896b18d2765b Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 12 Dec 2024 18:47:46 +0100 Subject: [PATCH 39/78] refactoring --- lam/templates/tests/index.php | 4 ++-- lam/templates/tests/lamdaemonTest.php | 8 ++++---- lam/templates/tests/schemaTest.php | 14 +++++++------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/lam/templates/tests/index.php b/lam/templates/tests/index.php index 7cea77a2a..ce8ce19f3 100644 --- a/lam/templates/tests/index.php +++ b/lam/templates/tests/index.php @@ -50,7 +50,7 @@ checkIfToolIsActive('toolTests'); setlanguage(); -include '../../lib/adminHeader.inc'; +include __DIR__ . '/../../lib/adminHeader.inc'; echo "
\n"; $container = new htmlResponsiveRow(); @@ -67,4 +67,4 @@ $container->add(new htmlOutputText(_("Check if quotas and homedirectories can be parseHtml(null, $container, [], true, 'user'); echo "
\n"; -include '../../lib/adminFooter.inc'; +include __DIR__ . '/../../lib/adminFooter.inc'; diff --git a/lam/templates/tests/lamdaemonTest.php b/lam/templates/tests/lamdaemonTest.php index bf40b892a..6c3b3f9ce 100644 --- a/lam/templates/tests/lamdaemonTest.php +++ b/lam/templates/tests/lamdaemonTest.php @@ -60,7 +60,7 @@ checkIfToolIsActive('toolTests'); setlanguage(); -include '../../lib/adminHeader.inc'; +include __DIR__ . '/../../lib/adminHeader.inc'; echo "
\n"; echo "\n"; @@ -114,7 +114,7 @@ parseHtml(null, $container, [], false, 'user'); echo "\n"; echo "
\n"; -include '../../lib/adminFooter.inc'; +include __DIR__ . '/../../lib/adminFooter.inc'; /** @@ -152,10 +152,10 @@ function testRemoteCommand($command, $stopTest, $remote, $testText, $container) else { // error messages from lamdaemon $parts = explode(",", $output); - if (sizeof($parts) == 2) { + if (count($parts) == 2) { $container->add(new htmlStatusMessage($parts[0], $parts[1]), 12, 6); } - elseif (sizeof($parts) == 3) { + elseif (count($parts) == 3) { $container->add(new htmlStatusMessage($parts[0], $parts[1], $parts[2]), 12, 6); } else { diff --git a/lam/templates/tests/schemaTest.php b/lam/templates/tests/schemaTest.php index 36812aef2..a24eb629c 100644 --- a/lam/templates/tests/schemaTest.php +++ b/lam/templates/tests/schemaTest.php @@ -58,7 +58,7 @@ checkIfToolIsActive('toolTests'); setlanguage(); -include '../../lib/adminHeader.inc'; +include __DIR__ . '/../../lib/adminHeader.inc'; echo "
\n"; $container = new htmlResponsiveRow(); @@ -78,7 +78,7 @@ else { foreach ($types as $type) { $modules = $_SESSION['config']->get_AccountModules($type->getId()); $container->add(new htmlSubTitle($type->getAlias()), 12); - for ($m = 0; $m < sizeof($modules); $m++) { + for ($m = 0; $m < count($modules); $m++) { $error = checkSchemaForModule($modules[$m], $type->getScope(), $type->getId()); $message = _("No problems found."); $icon = '../../graphics/pass.svg'; @@ -100,7 +100,7 @@ else { parseHtml(null, $container, [], true, 'user'); echo "
\n"; -include '../../lib/adminFooter.inc'; +include __DIR__ . '/../../lib/adminFooter.inc'; /** * Checks if the object classes and attributes for this module are available. @@ -115,13 +115,13 @@ function checkSchemaForModule($name, $scope, $typeId): ?string { $classes = $module->getManagedObjectClasses($typeId); $attrs = $module->getManagedAttributes($typeId); $aliases = array_flip($module->getLDAPAliases($typeId)); - if (sizeof($classes) == 0) { + if (count($classes) == 0) { return null; } $schemaClasses = get_cached_schema('objectclasses'); $schemaAttrs = []; // check if object classes are supported - for ($o = 0; $o < sizeof($classes); $o++) { + for ($o = 0; $o < count($classes); $o++) { if (!isset($schemaClasses[strtolower($classes[$o])])) { return sprintf(_("The object class %s is not supported by your LDAP server."), $classes[$o]); } @@ -129,7 +129,7 @@ function checkSchemaForModule($name, $scope, $typeId): ?string { $schemaAttrs = array_merge($schemaAttrs, getRecursiveAttributesFromObjectClass($schemaClasses[strtolower($classes[$o])])); } // check if attributes are supported - for ($a = 0; $a < sizeof($attrs); $a++) { + for ($a = 0; $a < count($attrs); $a++) { if (str_starts_with($attrs[$a], 'INFO.')) { continue; } @@ -154,7 +154,7 @@ function getRecursiveAttributesFromObjectClass($oClass): array { $attrs = array_merge($attrs, $oClass->getMustAttrNames()); $attrs = array_merge($attrs, $oClass->getMayAttrNames()); $subClassNames = $oClass->getSupClasses(); - for ($i = 0; $i < sizeof($subClassNames); $i++) { + for ($i = 0; $i < count($subClassNames); $i++) { $schemaClasses = get_cached_schema('objectclasses'); $subClass = $schemaClasses[strtolower($subClassNames[$i])]; $attrs = array_merge($attrs, getRecursiveAttributesFromObjectClass($subClass)); From f8313d826e8702d8e3d71fb6e271bef489a7c00f Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 12 Dec 2024 18:50:11 +0100 Subject: [PATCH 40/78] refactoring --- lam/templates/upload/massBuildAccounts.php | 17 ++- lam/templates/upload/massDoUpload.php | 4 +- lam/templates/upload/masscreate.php | 122 ++++++++++----------- 3 files changed, 66 insertions(+), 77 deletions(-) diff --git a/lam/templates/upload/massBuildAccounts.php b/lam/templates/upload/massBuildAccounts.php index 58ba9e08c..af039ee47 100644 --- a/lam/templates/upload/massBuildAccounts.php +++ b/lam/templates/upload/massBuildAccounts.php @@ -56,7 +56,9 @@ enforceUserIsLoggedIn(); checkIfToolIsActive('toolFileUpload'); // die if no write access -if (!checkIfWriteAccessIsAllowed()) die(); +if (!checkIfWriteAccessIsAllowed()) { + die(); +} // Redirect to startpage if user is not logged in if (!isLoggedIn()) { @@ -196,7 +198,7 @@ if ($_FILES['inputfile'] && ($_FILES['inputfile']['size'] > 0)) { $values_given[] = $dataRow[$colNumber]; } $values_unique = array_unique($values_given); - if (sizeof($values_given) != sizeof($values_unique)) { + if (count($values_given) !== count($values_unique)) { $duplicates = []; foreach ($values_given as $key => $value) { if (!isset($values_unique[$key]) && ($value !== null)) { @@ -211,7 +213,7 @@ if ($_FILES['inputfile'] && ($_FILES['inputfile']['size'] > 0)) { logNewMessage(LOG_DEBUG, 'End of generic checks'); // if input data is invalid just display error messages (max 50) - if (sizeof($errors) > 0) { + if ($errors !== []) { foreach ($errors as $error) { $container->add(new htmlStatusMessage("ERROR", $error[0], $error[1]), 12); } @@ -237,12 +239,7 @@ if ($_FILES['inputfile'] && ($_FILES['inputfile']['size'] > 0)) { $rdnValue = $rdnValue[0]; } $account_dn = $data[$i][$ids['dn_rdn']] . "=" . ldap_escape($rdnValue, '', LDAP_ESCAPE_DN) . ","; - if ($data[$i][$ids['dn_suffix']] == "") { - $account_dn = $account_dn . $suffix; - } - else { - $account_dn = $account_dn . $data[$i][$ids['dn_suffix']]; - } + $account_dn = ($data[$i][$ids['dn_suffix']] == "") ? $account_dn . $suffix : $account_dn . $data[$i][$ids['dn_suffix']]; $accounts[$i]['dn'] = $account_dn; } // set overwrite @@ -251,7 +248,7 @@ if ($_FILES['inputfile'] && ($_FILES['inputfile']['size'] > 0)) { } } // print errors if DN could not be built - if (sizeof($errors) > 0) { + if ($errors !== []) { foreach ($errors as $error) { $container->add(new htmlStatusMessage("ERROR", $error[0], $error[1], $error[2]), 12); } diff --git a/lam/templates/upload/massDoUpload.php b/lam/templates/upload/massDoUpload.php index 912d5665d..e9f800e72 100644 --- a/lam/templates/upload/massDoUpload.php +++ b/lam/templates/upload/massDoUpload.php @@ -54,7 +54,9 @@ enforceUserIsLoggedIn(); checkIfToolIsActive('toolFileUpload'); // die if no write access -if (!checkIfWriteAccessIsAllowed()) die(); +if (!checkIfWriteAccessIsAllowed()) { + die(); +} // Redirect to startpage if user is not logged in if (!isLoggedIn()) { diff --git a/lam/templates/upload/masscreate.php b/lam/templates/upload/masscreate.php index 03fda066e..3f2d4cfd1 100644 --- a/lam/templates/upload/masscreate.php +++ b/lam/templates/upload/masscreate.php @@ -1,5 +1,7 @@ getConfiguredTypes(); -$count = sizeof($types); +$count = count($types); for ($i = 0; $i < $count; $i++) { $myType = $types[$i]; if (!$myType->getBaseType()->supportsFileUpload() || $myType->isHidden() - || !checkIfNewEntriesAreAllowed($myType->getId()) || !checkIfWriteAccessIsAllowed($myType->getId())) { + || !checkIfNewEntriesAreAllowed($myType->getId()) || !checkIfWriteAccessIsAllowed($myType->getId())) { unset($types[$i]); } } @@ -127,11 +132,11 @@ if (isset($_POST['type'])) { } $deps = getModulesDependencies($type->getScope()); $depErrors = check_module_depends($selectedModules, $deps); - if (is_array($depErrors) && (sizeof($depErrors) > 0)) { + if (is_array($depErrors) && ($depErrors !== [])) { foreach ($depErrors as $depError) { StatusMessage('ERROR', _("Unsolved dependency:") . ' ' . - getModuleAlias($depError[0], $type->getScope()) . " (" . - getModuleAlias($depError[1], $type->getScope()) . ")"); + getModuleAlias($depError[0], $type->getScope()) . " (" . + getModuleAlias($depError[1], $type->getScope()) . ")"); } } else { @@ -214,14 +219,14 @@ foreach ($types as $type) { $moduleGroup->addElement(new htmlLabel($type->getId() . '___' . $moduleName, getModuleAlias($moduleName, $type->getScope()))); $innerRow->add($moduleGroup, 12, 6, 4); } - $moduleCount = sizeof($modules); - if ($moduleCount%3 == 2) { + $moduleCount = count($modules); + if ($moduleCount % 3 == 2) { $innerRow->add(new htmlOutputText(' ', false), 0, 0, 4); } - if ($moduleCount%3 == 1) { + if ($moduleCount % 3 == 1) { $innerRow->add(new htmlOutputText(' ', false), 0, 0, 4); } - if ($moduleCount%2 == 1) { + if ($moduleCount % 2 == 1) { $innerRow->add(new htmlOutputText(' ', false), 0, 6, 0); } $typeDiv = new htmlDiv($type->getId(), $innerRow); @@ -232,8 +237,8 @@ foreach ($types as $type) { // ok button $row->addVerticalSpacer('3rem'); if (!empty($types)) { - $okButton = new htmlButton('submit', _('Ok')); - $okButton->setCSSClasses(['lam-primary']); + $okButton = new htmlButton('submit', _('Ok')); + $okButton->setCSSClasses(['lam-primary']); $row->add($okButton); } @@ -246,11 +251,11 @@ echo '
'; include __DIR__ . '/../../lib/adminFooter.inc'; /** -* Displays the account type specific main page of the upload. -* -* @param \LAM\TYPES\ConfiguredType $type account type -* @param string[] $selectedModules list of selected account modules -*/ + * Displays the account type specific main page of the upload. + * + * @param \LAM\TYPES\ConfiguredType $type account type + * @param string[] $selectedModules list of selected account modules + */ function showMainPage(\LAM\TYPES\ConfiguredType $type, array $selectedModules): void { $scope = $type->getScope(); echo '
'; @@ -297,7 +302,7 @@ function showMainPage(\LAM\TYPES\ConfiguredType $type, array $selectedModules): if (isset($_POST['pdfStructure'])) { $pdfSelected = [$_POST['pdfStructure']]; } - else if (in_array('default', $pdfStructures)) { + elseif (in_array('default', $pdfStructures)) { $pdfSelected = ['default']; } $row->add(new htmlResponsiveSelect('pdfStructure', $pdfStructures, $pdfSelected, _('PDF structure'))); @@ -386,7 +391,7 @@ function showMainPage(\LAM\TYPES\ConfiguredType $type, array $selectedModules): // module options foreach ($modules as $moduleName) { // skip modules without upload columns - if (sizeof($columns[$moduleName]) < 1) { + if (count($columns[$moduleName]) < 1) { continue; } $data = []; @@ -423,18 +428,8 @@ function showMainPage(\LAM\TYPES\ConfiguredType $type, array $selectedModules): $example = $column['example']; } $rowCells[] = new htmlOutputText($example); - if (isset($column['default'])) { - $rowCells[] = new htmlOutputText($column['default']); - } - else { - $rowCells[] = new htmlOutputText(''); - } - if (isset($column['values'])) { - $rowCells[] = new htmlOutputText($column['values']); - } - else { - $rowCells[] = new htmlOutputText(''); - } + $rowCells[] = isset($column['default']) ? new htmlOutputText($column['default']) : new htmlOutputText(''); + $rowCells[] = isset($column['values']) ? new htmlOutputText($column['values']) : new htmlOutputText(''); $data[] = $rowCells; } $table = new htmlResponsiveTable($titles, $data); @@ -450,38 +445,33 @@ function showMainPage(\LAM\TYPES\ConfiguredType $type, array $selectedModules): // build sample CSV $sampleCSV_head = []; $sampleCSV_row = []; - // DN attributes - $sampleCSV_head[] = "\"dn_suffix\""; - $sampleCSV_head[] = "\"dn_rdn\""; - $sampleCSV_head[] = "\"overwrite\""; - // module attributes - foreach ($modules as $moduleName) { - if (sizeof($columns[$moduleName]) < 1) { - continue; - } - foreach ($columns[$moduleName] as $column) { - $sampleCSV_head[] = "\"" . $column['name'] . "\""; - } + // DN attributes + $sampleCSV_head[] = "\"dn_suffix\""; + $sampleCSV_head[] = "\"dn_rdn\""; + $sampleCSV_head[] = "\"overwrite\""; + // module attributes + foreach ($modules as $moduleName) { + if (count($columns[$moduleName]) < 1) { + continue; } - $RDNs = getRDNAttributes($type->getId(), $selectedModules); - // DN attributes - $sampleCSV_row[] = "\"" . $type->getSuffix() . "\""; - $sampleCSV_row[] = "\"" . $RDNs[0] . "\""; - $sampleCSV_row[] = "\"false\""; - // module attributes - foreach ($modules as $moduleName) { - if (sizeof($columns[$moduleName]) < 1) { - continue; - } - foreach ($columns[$moduleName] as $column) { - if (isset($column['example'])) { - $sampleCSV_row[] = '"' . $column['example'] . '"'; - } - else { - $sampleCSV_row[] = '""'; - } - } + foreach ($columns[$moduleName] as $column) { + $sampleCSV_head[] = "\"" . $column['name'] . "\""; } + } + $RDNs = getRDNAttributes($type->getId(), $selectedModules); + // DN attributes + $sampleCSV_row[] = "\"" . $type->getSuffix() . "\""; + $sampleCSV_row[] = "\"" . $RDNs[0] . "\""; + $sampleCSV_row[] = "\"false\""; + // module attributes + foreach ($modules as $moduleName) { + if (count($columns[$moduleName]) < 1) { + continue; + } + foreach ($columns[$moduleName] as $column) { + $sampleCSV_row[] = isset($column['example']) ? '"' . $column['example'] . '"' : '""'; + } + } $sampleCSV = implode(",", $sampleCSV_head) . "\n" . implode(",", $sampleCSV_row) . "\n"; $_SESSION['mass_csv'] = $sampleCSV; From 1bb542616f6f1386eb111f5a82144f8934a189ac Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 12 Dec 2024 18:57:22 +0100 Subject: [PATCH 41/78] refactoring --- lam/templates/delete.php | 8 ++--- lam/templates/help.php | 57 +++++++++++++++------------------- lam/templates/initsuff.php | 22 ++++++------- lam/templates/login2Factor.php | 2 +- lam/templates/main.php | 8 ++--- 5 files changed, 45 insertions(+), 52 deletions(-) diff --git a/lam/templates/delete.php b/lam/templates/delete.php index c1bbc58dc..6405e1296 100644 --- a/lam/templates/delete.php +++ b/lam/templates/delete.php @@ -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 "
"; echo "
\n"; echo "
\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 "
\n"; echo "
\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); } diff --git a/lam/templates/help.php b/lam/templates/help.php index a76349b1a..0f58a696f 100644 --- a/lam/templates/help.php +++ b/lam/templates/help.php @@ -1,4 +1,5 @@ - - + + - - + +
' . _('Technical name') . ': ' . $helpEntry['attr'] . ''; } echo $format; - if(isset($helpEntry['SeeAlso']) && is_array($helpEntry['SeeAlso'])) { + if (isset($helpEntry['SeeAlso']) && is_array($helpEntry['SeeAlso'])) { echo '

' . _('See also') . ': ' . $helpEntry['SeeAlso']['text'] . '

'; } 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); diff --git a/lam/templates/initsuff.php b/lam/templates/initsuff.php index 604af9f9c..7cded1848 100644 --- a/lam/templates/initsuff.php +++ b/lam/templates/initsuff.php @@ -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!") . "
" . 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; } diff --git a/lam/templates/login2Factor.php b/lam/templates/login2Factor.php index c49e73155..8496e953e 100644 --- a/lam/templates/login2Factor.php +++ b/lam/templates/login2Factor.php @@ -43,7 +43,7 @@ use LAMException; */ /** config object */ -include_once '../lib/config.inc'; +include_once __DIR__ . '/../lib/config.inc'; // start session startSecureSession(); diff --git a/lam/templates/main.php b/lam/templates/main.php index 40ef3ae7f..049200f71 100644 --- a/lam/templates/main.php +++ b/lam/templates/main.php @@ -35,9 +35,9 @@ use LAMException; */ /** config object */ -include_once '../lib/config.inc'; +include_once __DIR__ . '/../lib/config.inc'; /** profiles */ -include_once '../lib/profiles.inc'; +include_once __DIR__ . '/../lib/profiles.inc'; // start session startSecureSession(); @@ -86,12 +86,12 @@ foreach ($types as $type) { } // display page to add suffixes, if needed -if ((sizeof($new_suffs) > 0) && checkIfWriteAccessIsAllowed()) { +if (($new_suffs !== []) && checkIfWriteAccessIsAllowed()) { metaRefresh("initsuff.php?suffs='" . implode(";", $new_suffs)); exit(); } -if (sizeof($types) > 0) { +if (count($types) > 0) { foreach ($types as $type) { if ($type->isHidden()) { continue; From 4d05002785c2135d102611fe321ee0f79074957c Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 12 Dec 2024 18:58:38 +0100 Subject: [PATCH 42/78] refactoring --- lam/templates/login.php | 560 ++++++++++++++++++++-------------------- 1 file changed, 283 insertions(+), 277 deletions(-) diff --git a/lam/templates/login.php b/lam/templates/login.php index 3011edc2c..5553105ca 100644 --- a/lam/templates/login.php +++ b/lam/templates/login.php @@ -1,5 +1,7 @@ getProfiles(); -} catch (LAMException $e) { +} +catch (LAMException $e) { logNewMessage(LOG_ERR, 'Unable to read server profiles: ' . $e->getTitle()); } @@ -120,7 +123,7 @@ if (isset($_COOKIE["lam_default_profile"]) && in_array($_COOKIE["lam_default_pro $error_message = null; try { - // Reload login page after a profile change + // Reload login page after a profile change if (isset($_GET['useProfile']) && in_array($_GET['useProfile'], $profiles)) { logNewMessage(LOG_DEBUG, "Change server profile to " . $_GET['useProfile']); $_SESSION['config'] = $serverProfilePersistenceManager->loadProfile($_GET['useProfile']); @@ -130,12 +133,13 @@ try { } // use first profile as fallback else if (sizeof($profiles) > 0) { $_SESSION["config"] = $serverProfilePersistenceManager->loadProfile($profiles[0]); - } else { + } + else { $_SESSION["config"] = null; } } catch (LAMException $e) { - $error_message = $e->getTitle(); + $error_message = $e->getTitle(); } if (!isset($default_Config->default) || !in_array($default_Config->default, $profiles)) { @@ -183,10 +187,10 @@ $_SESSION['header'] .= "\n "; $manifestBaseUrl = getCallingURL(); if (str_contains($manifestBaseUrl, '/templates/login.php')) { - $manifestBaseUrl = substr($manifestBaseUrl, 0, strpos($manifestBaseUrl, '/templates/login.php')); + $manifestBaseUrl = substr($manifestBaseUrl, 0, strpos($manifestBaseUrl, '/templates/login.php')); $urlMatches = []; if (preg_match('/^http(s)?:\\/\\/[^\\/]+(\\/.*)$/m', $manifestBaseUrl, $urlMatches)) { - $manifestBaseUrl = htmlspecialchars($urlMatches[2]); + $manifestBaseUrl = htmlspecialchars($urlMatches[2]); $_SESSION['header'] .= ''; } } @@ -207,9 +211,9 @@ function display_LoginPage(?LAMLicenseValidator $licenseValidator, ?string $erro $cfgMain = $_SESSION["cfgMain"]; logNewMessage(LOG_DEBUG, "Display login page"); // generate 256 bit key and initialization vector for user/passwd-encryption - $key = openssl_random_pseudo_bytes(32); - $iv = openssl_random_pseudo_bytes(16); - // save both in cookie + $key = openssl_random_pseudo_bytes(32); + $iv = openssl_random_pseudo_bytes(16); + // save both in cookie $cookieOptions = lamDefaultCookieOptions(); $cookieOptions['expires'] = 0; setcookie("Key", base64_encode($key), $cookieOptions); @@ -221,8 +225,8 @@ function display_LoginPage(?LAMLicenseValidator $licenseValidator, ?string $erro echo $_SESSION["header"]; printHeaderContents('LDAP Account Manager', '..'); ?> - - + + "; - } - } - // check TLS - $useTLS = $config_object->getUseTLS(); - if (isset($useTLS) && ($useTLS == "yes")) { - if (!function_exists('ldap_start_tls')) { - StatusMessage("ERROR", "Your PHP installation does not support TLS encryption!"); - echo "
"; - } + if (!empty($config_object)) { + // check extensions + $extList = getRequiredExtensions(); + foreach ($extList as $extension) { + if (!extension_loaded($extension)) { + StatusMessage("ERROR", "A required PHP extension is missing!", $extension); + echo "
"; } } - else { - StatusMessage('WARN', _('Please enter the configuration and create a server profile.')); + // check TLS + $useTLS = $config_object->getUseTLS(); + if (isset($useTLS) && ($useTLS == "yes")) { + if (!function_exists('ldap_start_tls')) { + StatusMessage("ERROR", "Your PHP installation does not support TLS encryption!"); + echo "
"; + } } - // check if session expired - if (isset($_GET['expired'])) { - StatusMessage("ERROR", _("Your session expired, please log in again.")); - echo "
"; - } - if (!empty($config_object)) { + } + else { + StatusMessage('WARN', _('Please enter the configuration and create a server profile.')); + } + // check if session expired + if (isset($_GET['expired'])) { + StatusMessage("ERROR", _("Your session expired, please log in again.")); + echo "
"; + } + if (!empty($config_object)) { ?> -


-
-
- - - + + +
-
- addLabel(new htmlLabel('username', _("User name"))); - if ($config_object->getLoginMethod() == LAMConfig::LOGIN_LIST) { - $admins = $config_object->get_Admins(); - $adminList = []; - foreach ($admins as $admin) { - $text = explode(",", (string) $admin); - $text = explode("=", $text[0]); - if (isset($text[1])) { - $adminList[$text[1]] = $admin; +


+
+
+ + + + + + + - - - - - - - + + + - - -
+ + addLabel(new htmlLabel('username', _("User name"))); + if ($config_object->getLoginMethod() == LAMConfig::LOGIN_LIST) { + $admins = $config_object->get_Admins(); + $adminList = []; + foreach ($admins as $admin) { + $text = explode(",", (string) $admin); + $text = explode("=", $text[0]); + if (isset($text[1])) { + $adminList[$text[1]] = $admin; + } + else { + $adminList[$text[0]] = $admin; + } } - else { - $adminList[$text[0]] = $admin; + $selectedAdmin = []; + if (isset($_POST['username']) && in_array($_POST['username'], $adminList)) { + $selectedAdmin = [$_POST['username']]; } - } - $selectedAdmin = []; - if (isset($_POST['username']) && in_array($_POST['username'], $adminList)) { - $selectedAdmin = [$_POST['username']]; - } - $userSelect = new htmlSelect('username', $adminList, $selectedAdmin); - $userSelect->setHasDescriptiveElements(true); - $userSelect->setTransformSingleSelect(false); - if (empty($_COOKIE['lam_login_name'])) { - $userSelect->setCSSClasses(['lam-initial-focus']); - } - $row->addField(new htmlDiv(null, $userSelect)); - } - else { - if ($config_object->getHttpAuthentication() == 'true') { - $httpAuth = new htmlDiv(null, new htmlOutputText($_SERVER['PHP_AUTH_USER'] . ' ', false)); - $httpAuth->setCSSClasses(['text-left', 'margin3']); - $row->addField($httpAuth); + $userSelect = new htmlSelect('username', $adminList, $selectedAdmin); + $userSelect->setHasDescriptiveElements(true); + $userSelect->setTransformSingleSelect(false); + if (empty($_COOKIE['lam_login_name'])) { + $userSelect->setCSSClasses(['lam-initial-focus']); + } + $row->addField(new htmlDiv(null, $userSelect)); } else { - $user = ''; + if ($config_object->getHttpAuthentication() == 'true') { + $httpAuth = new htmlDiv(null, new htmlOutputText($_SERVER['PHP_AUTH_USER'] . ' ', false)); + $httpAuth->setCSSClasses(['text-left', 'margin3']); + $row->addField($httpAuth); + } + else { + $user = ''; + if (isset($_COOKIE["lam_login_name"])) { + $user = $_COOKIE["lam_login_name"]; + } + $userNameInput = new htmlInputField('username', $user); + if (empty($_COOKIE['lam_login_name'])) { + $userNameInput->setCSSClasses(['lam-initial-focus']); + } + $userInput = new htmlDiv(null, $userNameInput); + $row->addField($userInput); + } + } + // password + $row->addLabel(new htmlLabel('passwd', _("Password"))); + if (($config_object->getLoginMethod() == LAMConfig::LOGIN_SEARCH) && ($config_object->getHttpAuthentication() == 'true')) { + $passwordInputFake = new htmlDiv(null, new htmlOutputText('**********')); + $passwordInputFake->setCSSClasses(['text-left', 'margin3']); + $row->addField($passwordInputFake); + } + else { + $passwordInput = new htmlInputField('passwd'); + $passwordInput->setIsPassword(true); + if (($config_object->getLoginMethod() == LAMConfig::LOGIN_SEARCH) && !empty($_COOKIE['lam_login_name'])) { + $passwordInput->setCSSClasses(['lam-initial-focus']); + } + $row->addField($passwordInput); + } + // language + $row->addLabel(new htmlLabel('language', _("Language"))); + $possibleLanguages = getLanguages(); + $languageList = []; + $defaultLanguage = []; + foreach ($possibleLanguages as $lang) { + $languageList[$lang->description] = $lang->code; + if (str_starts_with(trim((string) $_SESSION["language"]), $lang->code)) { + $defaultLanguage[] = $lang->code; + } + } + $languageSelect = new htmlSelect('language', $languageList, $defaultLanguage); + $languageSelect->setHasDescriptiveElements(true); + $row->addField($languageSelect, true); + // remember login user + if (($config_object->getLoginMethod() == LAMConfig::LOGIN_SEARCH) && !($config_object->getHttpAuthentication() == 'true')) { + $row->add(new htmlOutputText(' ', false), 0, 6, 6); + $rememberGroup = new htmlGroup(); + $doRemember = false; if (isset($_COOKIE["lam_login_name"])) { - $user = $_COOKIE["lam_login_name"]; + $doRemember = true; } - $userNameInput = new htmlInputField('username', $user); - if (empty($_COOKIE['lam_login_name'])) { - $userNameInput->setCSSClasses(['lam-initial-focus']); - } - $userInput = new htmlDiv(null, $userNameInput); - $row->addField($userInput); + $rememberGroup->addElement(new htmlInputCheckbox('rememberLogin', $doRemember)); + $rememberGroup->addElement(new htmlSpacer('1px', null)); + $rememberGroup->addElement(new htmlOutputText(_('Remember user name'))); + $rememberDiv = new htmlDiv(null, $rememberGroup); + $rememberDiv->setCSSClasses(['text-left', 'margin3']); + $row->add($rememberDiv, 12, 6, 6); } - } - // password - $row->addLabel(new htmlLabel('passwd', _("Password"))); - if (($config_object->getLoginMethod() == LAMConfig::LOGIN_SEARCH) && ($config_object->getHttpAuthentication() == 'true')) { - $passwordInputFake = new htmlDiv(null, new htmlOutputText('**********')); - $passwordInputFake->setCSSClasses(['text-left', 'margin3']); - $row->addField($passwordInputFake); - } - else { - $passwordInput = new htmlInputField('passwd'); - $passwordInput->setIsPassword(true); - if (($config_object->getLoginMethod() == LAMConfig::LOGIN_SEARCH) && !empty($_COOKIE['lam_login_name'])) { - $passwordInput->setCSSClasses(['lam-initial-focus']); - } - $row->addField($passwordInput); - } - // language - $row->addLabel(new htmlLabel('language', _("Language"))); - $possibleLanguages = getLanguages(); - $languageList = []; - $defaultLanguage = []; - foreach ($possibleLanguages as $lang) { - $languageList[$lang->description] = $lang->code; - if (str_starts_with(trim((string) $_SESSION["language"]), $lang->code)) { - $defaultLanguage[] = $lang->code; - } - } - $languageSelect = new htmlSelect('language', $languageList, $defaultLanguage); - $languageSelect->setHasDescriptiveElements(true); - $row->addField($languageSelect, true); - // remember login user - if (($config_object->getLoginMethod() == LAMConfig::LOGIN_SEARCH) && !($config_object->getHttpAuthentication() == 'true')) { - $row->add(new htmlOutputText(' ', false), 0, 6, 6); - $rememberGroup = new htmlGroup(); - $doRemember = false; - if (isset($_COOKIE["lam_login_name"])) { - $doRemember = true; - } - $rememberGroup->addElement(new htmlInputCheckbox('rememberLogin', $doRemember)); - $rememberGroup->addElement(new htmlSpacer('1px', null)); - $rememberGroup->addElement(new htmlOutputText(_('Remember user name'))); - $rememberDiv = new htmlDiv(null, $rememberGroup); - $rememberDiv->setCSSClasses(['text-left', 'margin3']); - $row->add($rememberDiv, 12, 6, 6); - } - // login button - $row->add(new htmlSpacer(null, '20px'), 12); - $loginButton = new htmlButton('checklogin', _("Login")); - $loginButton->setCSSClasses(['lam-primary']); - $row->add($loginButton); + // login button + $row->add(new htmlSpacer(null, '20px'), 12); + $loginButton = new htmlButton('checklogin', _("Login")); + $loginButton->setCSSClasses(['lam-primary']); + $row->add($loginButton); + parseHtml(null, $row, [], false, 'user'); + ?> + + +
+ add(new \htmlSpacer(null, '5px'), 12); + $message = new htmlStatusMessage('ERROR', $error_message, $errorDetails); + $row->add($message, 12); + } + if (!empty($extraMessage)) { + $extraMessage = new htmlStatusMessage('INFO', $extraMessage); + $row->add($extraMessage, 12); + } parseHtml(null, $row, [], false, 'user'); - ?> - - -
- add(new \htmlSpacer(null, '5px'), 12); - $message = new htmlStatusMessage('ERROR', $error_message, $errorDetails); - $row->add($message, 12); - } - if (!empty($extraMessage)) { - $extraMessage = new htmlStatusMessage('INFO', $extraMessage); - $row->add($extraMessage, 12); - } - parseHtml(null, $row, [], false, 'user'); - ?> -
-
-
- addLabel(new htmlOutputText(_("LDAP server"))); - $serverUrl = new htmlOutputText($config_object->getServerDisplayNameGUI()); - $serverUrlDiv = new htmlDiv(null, $serverUrl); - $serverUrlDiv->setCSSClasses(['text-left', 'margin3']); - $row->addField($serverUrlDiv); - $profileSelect = new htmlResponsiveSelect('profile', $profiles, [$_SESSION['config']->getName()], _("Server profile")); - $profileSelect->setOnchangeEvent('loginProfileChanged(this)'); - $row->add($profileSelect); + ?> +
+
+ + addLabel(new htmlOutputText(_("LDAP server"))); + $serverUrl = new htmlOutputText($config_object->getServerDisplayNameGUI()); + $serverUrlDiv = new htmlDiv(null, $serverUrl); + $serverUrlDiv->setCSSClasses(['text-left', 'margin3']); + $row->addField($serverUrlDiv); + $profileSelect = new htmlResponsiveSelect('profile', $profiles, [$_SESSION['config']->getName()], _("Server profile")); + $profileSelect->setOnchangeEvent('loginProfileChanged(this)'); + $row->add($profileSelect); - parseHtml(null, $row, [], true, 'user'); - ?> - - -
-
-
+ parseHtml(null, $row, [], true, 'user'); + ?> + +
+
+
+
+

+ isExpiringSoon()) { + $expirationDate = $licenseValidator->getLicense()->getExpirationDate()->format('Y-m-d'); + $expirationTimeStamp = $licenseValidator->getLicense()->getExpirationDate()->getTimestamp(); + if ($cfgMain->showLicenseWarningOnScreen()) { + $licenseMessage = sprintf(_('Your licence expires on %s. You need to purchase a new licence to be able to use LAM Pro after this date.'), $expirationDate); + StatusMessage('WARN', $licenseMessage); } - ?> -

- isExpiringSoon()) { - $expirationDate = $licenseValidator->getLicense()->getExpirationDate()->format('Y-m-d'); - $expirationTimeStamp = $licenseValidator->getLicense()->getExpirationDate()->getTimestamp(); - if ($cfgMain->showLicenseWarningOnScreen()) { - $licenseMessage = sprintf(_('Your licence expires on %s. You need to purchase a new licence to be able to use LAM Pro after this date.'), $expirationDate); - StatusMessage('WARN', $licenseMessage); - } - if ($cfgMain->sendLicenseWarningByEmail() && !$cfgMain->wasLicenseWarningSent($expirationTimeStamp)) { - $cfgMain->licenseEmailDateSent = $expirationTimeStamp; - $cfgMain->save(); - $mailer = new \LAM\ENV\LicenseWarningMailer($cfgMain); - $mailer->sendMail($expirationDate); - } - } - ?> -

- - -sendLicenseWarningByEmail() && !$cfgMain->wasLicenseWarningSent($expirationTimeStamp)) { + $cfgMain->licenseEmailDateSent = $expirationTimeStamp; + $cfgMain->save(); + $mailer = new \LAM\ENV\LicenseWarningMailer($cfgMain); + $mailer->sendMail($expirationDate); + } + } + ?> +

+ + + +function displayLoginHeader(): void { + ?>
- + menu @@ -475,20 +480,20 @@ function displayLoginHeader() : void { - + - +
-
- + getLoginMethod() == LAMConfig::LOGIN_SEARCH)) { setcookie('lam_login_name', '', $cookieOptions); } - if($_POST['passwd'] == "") { + if ($_POST['passwd'] == "") { logNewMessage(LOG_DEBUG, "Empty password for login"); $error_message = _("Empty password submitted. Please try again."); header("HTTP/1.1 403 Forbidden"); @@ -525,7 +530,7 @@ if (isset($_POST['checklogin'])) { $password = $_POST['passwd']; } // search user in LDAP if needed - $searchLDAP = null; + $searchLDAP = null; if ($_SESSION['config']->getLoginMethod() == LAMConfig::LOGIN_SEARCH) { $searchFilter = $_SESSION['config']->getLoginSearchFilter(); $searchFilter = str_replace('%USER%', ldap_escape($username, '', LDAP_ESCAPE_FILTER), $searchFilter); @@ -541,24 +546,24 @@ if (isset($_POST['checklogin'])) { $searchLDAP = new Ldap($_SESSION['config']); try { $searchLDAP->connect($searchDN, $searchPassword, true); - $searchResult = ldap_search($searchLDAP->server(), $_SESSION['config']->getLoginSearchSuffix(), $searchFilter, ['dn'], 0, 0, 0, LDAP_DEREF_NEVER); - if ($searchResult) { - $searchInfo = ldap_get_entries($searchLDAP->server(), $searchResult); - if ($searchInfo !== false) { - cleanLDAPResult($searchInfo); - if (empty($searchInfo)) { - $searchSuccess = false; - if ($default_Config->isHideLoginErrorDetails()) { + $searchResult = ldap_search($searchLDAP->server(), $_SESSION['config']->getLoginSearchSuffix(), $searchFilter, ['dn'], 0, 0, 0, LDAP_DEREF_NEVER); + if ($searchResult) { + $searchInfo = ldap_get_entries($searchLDAP->server(), $searchResult); + if ($searchInfo !== false) { + cleanLDAPResult($searchInfo); + if (empty($searchInfo)) { + $searchSuccess = false; + if ($default_Config->isHideLoginErrorDetails()) { $searchError = _('Wrong password/user name combination. Please try again.'); - } - else { + } + else { $searchError = _('Unable to find the user name in LDAP.'); - } + } logNewMessage(LOG_ERR, 'User ' . $username . ' (' . $clientSource . ') failed to log in. Unable to find the user name in LDAP.'); - header("HTTP/1.1 403 Forbidden"); - } + header("HTTP/1.1 403 Forbidden"); + } elseif (sizeof($searchInfo) > 1) { - $searchSuccess = false; + $searchSuccess = false; if ($default_Config->isHideLoginErrorDetails()) { $searchError = _('Wrong password/user name combination. Please try again.'); } @@ -566,29 +571,29 @@ if (isset($_POST['checklogin'])) { $searchError = _('The given user name matches multiple LDAP entries.'); } logNewMessage(LOG_ERR, 'User ' . $username . ' (' . $clientSource . ') failed to log in. The given user name matches multiple LDAP entries.'); - header("HTTP/1.1 403 Forbidden"); - } - else { - $username = $searchInfo[0]['dn']; - } - } - else { - $searchSuccess = false; + header("HTTP/1.1 403 Forbidden"); + } + else { + $username = $searchInfo[0]['dn']; + } + } + else { + $searchSuccess = false; if ($default_Config->isHideLoginErrorDetails()) { $searchError = _('Wrong password/user name combination. Please try again.'); } else { $searchError = _('Unable to find the user name in LDAP.'); } - header("HTTP/1.1 403 Forbidden"); - if (ldap_errno($searchLDAP->server()) != 0) { - $searchError .= ' ' . getDefaultLDAPErrorString($searchLDAP->server()); - } + header("HTTP/1.1 403 Forbidden"); + if (ldap_errno($searchLDAP->server()) != 0) { + $searchError .= ' ' . getDefaultLDAPErrorString($searchLDAP->server()); + } logNewMessage(LOG_ERR, 'User ' . $username . ' (' . $clientSource . ') failed to log in. Unable to find the user name in LDAP.'); - } - } - else { - $searchSuccess = false; + } + } + else { + $searchSuccess = false; if ($default_Config->isHideLoginErrorDetails()) { $searchError = _('Wrong password/user name combination. Please try again.'); } @@ -596,11 +601,11 @@ if (isset($_POST['checklogin'])) { $searchError = _('Unable to find the user name in LDAP.'); } logNewMessage(LOG_ERR, 'User ' . $username . ' (' . $clientSource . ') failed to log in. Unable to find the user name in LDAP.'); - header("HTTP/1.1 403 Forbidden"); - if (ldap_errno($searchLDAP->server()) != 0) { - $searchError .= ' ' . getDefaultLDAPErrorString($searchLDAP->server()); - } - } + header("HTTP/1.1 403 Forbidden"); + if (ldap_errno($searchLDAP->server()) != 0) { + $searchError .= ' ' . getDefaultLDAPErrorString($searchLDAP->server()); + } + } if (!$searchSuccess) { $error_message = $searchError; $searchLDAP->close(); @@ -609,15 +614,15 @@ if (isset($_POST['checklogin'])) { } $searchLDAP->close(); } - catch (LAMException $e) { - $searchLDAP->close(); - display_LoginPage($licenseValidator, $e->getTitle(), $e->getMessage()); - exit(); - } + catch (LAMException $e) { + $searchLDAP->close(); + display_LoginPage($licenseValidator, $e->getTitle(), $e->getMessage()); + exit(); + } } // try to connect to LDAP - try { - $_SESSION['ldap']->connect($username, $password); // Connect to LDAP server for verifying username/password + try { + $_SESSION['ldap']->connect($username, $password); // Connect to LDAP server for verifying username/password $_SESSION['loggedIn'] = true; // set security settings for session $_SESSION['sec_session_id'] = session_id(); @@ -640,23 +645,24 @@ if (isset($_POST['checklogin'])) { header("HTTP/1.1 403 Forbidden"); $extraMessage = null; if (($searchLDAP !== null) && ($e->getLdapErrorCode() == 49)) { - if (!$default_Config->isHideLoginErrorDetails()) { + if (!$default_Config->isHideLoginErrorDetails()) { $extraMessage = getExtraInvalidCredentialsMessage($searchLDAP->server(), $username); } $searchLDAP->close(); } $message = $e->getMessage(); if ($default_Config->isHideLoginErrorDetails()) { - $message = null; + $message = null; } display_LoginPage($licenseValidator, $e->getTitle(), $message, $extraMessage); exit(); - } + } } //displays the login window try { display_LoginPage($licenseValidator, $error_message); -} catch (LAMException $e) { - logNewMessage(LOG_ERR, 'Unable to render login page: ' . $e->getTitle()); +} +catch (LAMException $e) { + logNewMessage(LOG_ERR, 'Unable to render login page: ' . $e->getTitle()); } From 40d85f127a88c15a6d84741919242b886be6e02f Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 12 Dec 2024 19:00:22 +0100 Subject: [PATCH 43/78] refactoring --- lam/templates/login.php | 44 +++++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 24 deletions(-) diff --git a/lam/templates/login.php b/lam/templates/login.php index 5553105ca..61f47e3a5 100644 --- a/lam/templates/login.php +++ b/lam/templates/login.php @@ -131,7 +131,7 @@ try { elseif (!empty($default_Profile) && in_array($default_Profile, $profiles)) { $_SESSION["config"] = $serverProfilePersistenceManager->loadProfile($default_Profile); } // use first profile as fallback - else if (sizeof($profiles) > 0) { + elseif (count($profiles) > 0) { $_SESSION["config"] = $serverProfilePersistenceManager->loadProfile($profiles[0]); } else { @@ -247,11 +247,9 @@ function display_LoginPage(?LAMLicenseValidator $licenseValidator, ?string $erro } // check TLS $useTLS = $config_object->getUseTLS(); - if (isset($useTLS) && ($useTLS == "yes")) { - if (!function_exists('ldap_start_tls')) { - StatusMessage("ERROR", "Your PHP installation does not support TLS encryption!"); - echo "
"; - } + if (isset($useTLS) && ($useTLS == "yes") && !function_exists('ldap_start_tls')) { + StatusMessage("ERROR", "Your PHP installation does not support TLS encryption!"); + echo "
"; } } else { @@ -300,24 +298,22 @@ function display_LoginPage(?LAMLicenseValidator $licenseValidator, ?string $erro } $row->addField(new htmlDiv(null, $userSelect)); } + elseif ($config_object->getHttpAuthentication() == 'true') { + $httpAuth = new htmlDiv(null, new htmlOutputText($_SERVER['PHP_AUTH_USER'] . ' ', false)); + $httpAuth->setCSSClasses(['text-left', 'margin3']); + $row->addField($httpAuth); + } else { - if ($config_object->getHttpAuthentication() == 'true') { - $httpAuth = new htmlDiv(null, new htmlOutputText($_SERVER['PHP_AUTH_USER'] . ' ', false)); - $httpAuth->setCSSClasses(['text-left', 'margin3']); - $row->addField($httpAuth); + $user = ''; + if (isset($_COOKIE["lam_login_name"])) { + $user = $_COOKIE["lam_login_name"]; } - else { - $user = ''; - if (isset($_COOKIE["lam_login_name"])) { - $user = $_COOKIE["lam_login_name"]; - } - $userNameInput = new htmlInputField('username', $user); - if (empty($_COOKIE['lam_login_name'])) { - $userNameInput->setCSSClasses(['lam-initial-focus']); - } - $userInput = new htmlDiv(null, $userNameInput); - $row->addField($userInput); + $userNameInput = new htmlInputField('username', $user); + if (empty($_COOKIE['lam_login_name'])) { + $userNameInput->setCSSClasses(['lam-initial-focus']); } + $userInput = new htmlDiv(null, $userNameInput); + $row->addField($userInput); } // password $row->addLabel(new htmlLabel('passwd', _("Password"))); @@ -349,7 +345,7 @@ function display_LoginPage(?LAMLicenseValidator $licenseValidator, ?string $erro $languageSelect->setHasDescriptiveElements(true); $row->addField($languageSelect, true); // remember login user - if (($config_object->getLoginMethod() == LAMConfig::LOGIN_SEARCH) && !($config_object->getHttpAuthentication() == 'true')) { + if (($config_object->getLoginMethod() == LAMConfig::LOGIN_SEARCH) && ($config_object->getHttpAuthentication() != 'true')) { $row->add(new htmlOutputText(' ', false), 0, 6, 6); $rememberGroup = new htmlGroup(); $doRemember = false; @@ -516,7 +512,7 @@ if (isset($_POST['checklogin'])) { if (isset($_POST['rememberLogin']) && ($_POST['rememberLogin'] == 'on')) { setcookie('lam_login_name', (string) $_POST['username'], $cookieOptions); } - else if (isset($_COOKIE['lam_login_name']) && ($_SESSION['config']->getLoginMethod() == LAMConfig::LOGIN_SEARCH)) { + elseif (isset($_COOKIE['lam_login_name']) && ($_SESSION['config']->getLoginMethod() == LAMConfig::LOGIN_SEARCH)) { setcookie('lam_login_name', '', $cookieOptions); } if ($_POST['passwd'] == "") { @@ -562,7 +558,7 @@ if (isset($_POST['checklogin'])) { logNewMessage(LOG_ERR, 'User ' . $username . ' (' . $clientSource . ') failed to log in. Unable to find the user name in LDAP.'); header("HTTP/1.1 403 Forbidden"); } - elseif (sizeof($searchInfo) > 1) { + elseif (count($searchInfo) > 1) { $searchSuccess = false; if ($default_Config->isHideLoginErrorDetails()) { $searchError = _('Wrong password/user name combination. Please try again.'); From 57e78813e9193c26d525c025a5d57b1374ed83cc Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 12 Dec 2024 19:03:15 +0100 Subject: [PATCH 44/78] refactoring --- lam/lib/modules/windowsUser.inc | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lam/lib/modules/windowsUser.inc b/lam/lib/modules/windowsUser.inc index 8f7b5f426..212bcdaea 100644 --- a/lam/lib/modules/windowsUser.inc +++ b/lam/lib/modules/windowsUser.inc @@ -5082,12 +5082,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, + }; } /** From 40b39feb4e2b91981e6e1a3d3f8596c82310bdb8 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 12 Dec 2024 19:06:47 +0100 Subject: [PATCH 45/78] refactoring --- .../sambaSamAccount/sambaMungedDial.inc | 99 +++---------------- 1 file changed, 13 insertions(+), 86 deletions(-) diff --git a/lam/lib/modules/sambaSamAccount/sambaMungedDial.inc b/lam/lib/modules/sambaSamAccount/sambaMungedDial.inc index d607d953c..7c4764364 100644 --- a/lam/lib/modules/sambaSamAccount/sambaMungedDial.inc +++ b/lam/lib/modules/sambaSamAccount/sambaMungedDial.inc @@ -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,12 +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; - } + $result = isset($this->ctx['CtxMaxConnectionTime']) && ($this->ctx['CtxMaxConnectionTime'] != 0); return $result; } @@ -556,12 +493,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; - } + $result = isset($this->ctx['CtxMaxDisconnectionTime']) && ($this->ctx['CtxMaxDisconnectionTime'] != 0); return $result; } @@ -576,12 +508,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; - } + $result = isset($this->ctx['CtxMaxIdleTime']) && ($this->ctx['CtxMaxIdleTime'] != 0); return $result; } From a37c1a9a42f9ab7312722f9bf32d1cad3d8cfa54 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Fri, 13 Dec 2024 07:51:01 +0100 Subject: [PATCH 46/78] refactoring --- lam/lib/modules/courierMailAccount.inc | 2 +- lam/lib/modules/courierMailAlias.inc | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lam/lib/modules/courierMailAccount.inc b/lam/lib/modules/courierMailAccount.inc index 95eee1805..3db3a26d2 100644 --- a/lam/lib/modules/courierMailAccount.inc +++ b/lam/lib/modules/courierMailAccount.inc @@ -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"; diff --git a/lam/lib/modules/courierMailAlias.inc b/lam/lib/modules/courierMailAlias.inc index 097a993d9..f7753e48d 100644 --- a/lam/lib/modules/courierMailAlias.inc +++ b/lam/lib/modules/courierMailAlias.inc @@ -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(", ")); } From 4230c4c3edd22bc1805f8b7ebe5322a770980b86 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sat, 14 Dec 2024 10:32:15 +0100 Subject: [PATCH 47/78] refactoring --- lam/lib/modules/ddns.inc | 91 ++++++++++++++----------------- lam/lib/modules/dhcp_settings.inc | 40 +++++++------- 2 files changed, 60 insertions(+), 71 deletions(-) diff --git a/lam/lib/modules/ddns.inc b/lam/lib/modules/ddns.inc index e77e76448..f2e7e2d59 100644 --- a/lam/lib/modules/ddns.inc +++ b/lam/lib/modules/ddns.inc @@ -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]; diff --git a/lam/lib/modules/dhcp_settings.inc b/lam/lib/modules/dhcp_settings.inc index 68d832371..4a1094a07 100644 --- a/lam/lib/modules/dhcp_settings.inc +++ b/lam/lib/modules/dhcp_settings.inc @@ -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"; From c580a352f8ab0a858303ef749d739be080998d12 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Tue, 17 Dec 2024 07:39:46 +0100 Subject: [PATCH 48/78] 9.0 --- lam/templates/config/confmodules.php | 2 +- lam/templates/schema/schema.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lam/templates/config/confmodules.php b/lam/templates/config/confmodules.php index 2dd643f42..0de6413f9 100644 --- a/lam/templates/config/confmodules.php +++ b/lam/templates/config/confmodules.php @@ -85,7 +85,7 @@ $errorsToDisplay = checkInput(); if ((isset($_POST['saveSettings']) || isset($_POST['editmodules']) || isset($_POST['edittypes']) || isset($_POST['generalSettingsButton']) || isset($_POST['moduleSettings']) || isset($_POST['jobs'])) - && (count($errorsToDisplay) === 0)) { + && ($errorsToDisplay === [])) { // go to final page if (isset($_POST['saveSettings'])) { metaRefresh("confsave.php"); diff --git a/lam/templates/schema/schema.php b/lam/templates/schema/schema.php index a0f01e39a..0a286fbd8 100644 --- a/lam/templates/schema/schema.php +++ b/lam/templates/schema/schema.php @@ -196,7 +196,7 @@ function displayObjectClassList(htmlResponsiveRow &$row): void { if (isset($_GET['sel']) && (empty($_GET['sel']) || array_key_exists(strtolower($_GET['sel']), $objectClasses))) { $selectedClass[0] = $_GET['sel']; } - if (empty($selectedClass) && (sizeof($objectClasses) > 0)) { + if (empty($selectedClass) && (count($objectClasses) > 0)) { // select first class by default $selectedClassNames = array_keys($objectClasses); $selectedClass[0] = $selectedClassNames[0]; @@ -290,7 +290,7 @@ function displayAttributeList(htmlResponsiveRow $row): void { if (isset($_GET['sel']) && (empty($_GET['sel']) || array_key_exists(strtolower($_GET['sel']), $attributes))) { $selectedAttribute[0] = $_GET['sel']; } - if (empty($selectedAttribute) && (sizeof($availableAttributes) > 1)) { + if (empty($selectedAttribute) && (count($availableAttributes) > 1)) { // select first attribute by default $attributeNames = array_keys($availableAttributes); $selectedAttribute[0] = $attributeNames[1]; From a3fc8fe8f3345d1d58fb918fa3185ad58d20d928 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Tue, 17 Dec 2024 07:52:24 +0100 Subject: [PATCH 49/78] refactoring --- lam/tests/lib/2factorTest.php | 6 +-- lam/tests/lib/ImporterTest.php | 50 +++++++++---------- lam/tests/lib/LAMConfigTest.php | 16 +++--- lam/tests/lib/PdfStructTest.php | 14 +++--- ...eyCredentialSourceRepositorySQLiteTest.php | 4 +- lam/tests/lib/SecurityTest.php | 4 +- lam/tests/lib/TypesTest.php | 2 +- lam/tests/lib/modules/BindDLZTest.php | 8 +-- lam/tests/lib/modules/CustomFieldsTest.php | 8 +-- lam/tests/lib/modules/CustomScriptsTest.php | 10 ++-- .../PPolicyUserPasswordNotifyJobTest.php | 10 ++-- lam/tests/lib/modules/RequestAccessTest.php | 6 +-- lam/tests/lib/modules/SambaSamAccountTest.php | 6 +-- .../ShadowAccountPasswordNotifyJobTest.php | 12 ++--- lam/tests/lib/modules/ShadowAccountTest.php | 10 ++-- lam/tests/lib/modules/SudoRoleTest.php | 6 +-- 16 files changed, 86 insertions(+), 86 deletions(-) diff --git a/lam/tests/lib/2factorTest.php b/lam/tests/lib/2factorTest.php index 325063e5a..65f699e93 100644 --- a/lam/tests/lib/2factorTest.php +++ b/lam/tests/lib/2factorTest.php @@ -24,9 +24,9 @@ use PHPUnit\Framework\TestCase; */ -include_once 'lam/tests/utils/configuration.inc'; -include_once 'lam/tests/utils/2factorUtils.inc'; -require_once 'lam/lib/2factor.inc'; +include_once __DIR__ . '/../../tests/utils/configuration.inc'; +include_once __DIR__ . '/../../tests/utils/2factorUtils.inc'; +require_once __DIR__ . '/../../lib/2factor.inc'; /** * Checks code in 2factor.inc. diff --git a/lam/tests/lib/ImporterTest.php b/lam/tests/lib/ImporterTest.php index d42b407a1..dd2ecc07f 100644 --- a/lam/tests/lib/ImporterTest.php +++ b/lam/tests/lib/ImporterTest.php @@ -29,7 +29,7 @@ use PHPUnit\Framework\TestCase; */ -require_once 'lam/lib/import.inc'; +require_once __DIR__ . '/../../lib/import.inc'; /** * Checks the LDIF importer. @@ -127,7 +127,7 @@ class ImporterTest extends TestCase { $importer = new Importer(); $tasks = $importer->getTasks($lines); - $this->assertEquals(1, sizeof($tasks)); + $this->assertEquals(1, count($tasks)); } /** @@ -162,7 +162,7 @@ class ImporterTest extends TestCase { $importer = new Importer(); $tasks = $importer->getTasks($lines); - $this->assertEquals(1, sizeof($tasks)); + $this->assertEquals(1, count($tasks)); $task = $tasks[0]; $this->assertEquals(AddEntryTask::class, $task::class); } @@ -219,7 +219,7 @@ class ImporterTest extends TestCase { $importer = new Importer(); $tasks = $importer->getTasks($lines); - $this->assertEquals(1, sizeof($tasks)); + $this->assertEquals(1, count($tasks)); $task = $tasks[0]; $this->assertEquals(RenameEntryTask::class, $task::class); } @@ -255,7 +255,7 @@ class ImporterTest extends TestCase { $importer = new Importer(); $tasks = $importer->getTasks($lines); - $this->assertEquals(1, sizeof($tasks)); + $this->assertEquals(1, count($tasks)); $task = $tasks[0]; $this->assertEquals(DeleteEntryTask::class, $task::class); } @@ -314,17 +314,17 @@ class ImporterTest extends TestCase { $importer = new Importer(); $tasks = $importer->getTasks($lines); - $this->assertEquals(1, sizeof($tasks)); + $this->assertEquals(1, count($tasks)); $task = $tasks[0]; $this->assertEquals(MultiTask::class, $task::class); $subtasks = $task->getTasks(); - $this->assertEquals(1, sizeof($subtasks)); + $this->assertEquals(1, count($subtasks)); $subTask = $subtasks[0]; $this->assertEquals(AddAttributesTask::class, $subTask::class); $this->assertEquals($subTask->getDn(), 'uid=test,dc=example,dc=com'); $attributes = $subTask->getAttributes(); - $this->assertEquals(1, sizeof($attributes)); - $this->assertEquals(2, sizeof($attributes['uid'])); + $this->assertEquals(1, count($attributes)); + $this->assertEquals(2, count($attributes['uid'])); $this->assertTrue(in_array('uid1', $attributes['uid'])); $this->assertTrue(in_array('uid2', $attributes['uid'])); } @@ -349,25 +349,25 @@ class ImporterTest extends TestCase { $importer = new Importer(); $tasks = $importer->getTasks($lines); - $this->assertEquals(1, sizeof($tasks)); + $this->assertEquals(1, count($tasks)); $task = $tasks[0]; $this->assertEquals(MultiTask::class, $task::class); $subtasks = $task->getTasks(); - $this->assertEquals(2, sizeof($subtasks)); + $this->assertEquals(2, count($subtasks)); $subTask = $subtasks[0]; $this->assertEquals(AddAttributesTask::class, $subTask::class); $this->assertEquals($subTask->getDn(), 'uid=test,dc=example,dc=com'); $attributes = $subTask->getAttributes(); - $this->assertEquals(1, sizeof($attributes)); - $this->assertEquals(2, sizeof($attributes['uid'])); + $this->assertEquals(1, count($attributes)); + $this->assertEquals(2, count($attributes['uid'])); $this->assertTrue(in_array('uid1', $attributes['uid'])); $this->assertTrue(in_array('uid2', $attributes['uid'])); $subTask = $subtasks[1]; $this->assertEquals(AddAttributesTask::class, $subTask::class); $this->assertEquals($subTask->getDn(), 'uid=test,dc=example,dc=com'); $attributes = $subTask->getAttributes(); - $this->assertEquals(1, sizeof($attributes)); - $this->assertEquals(2, sizeof($attributes['gn'])); + $this->assertEquals(1, count($attributes)); + $this->assertEquals(2, count($attributes['gn'])); $this->assertTrue(in_array('name1', $attributes['gn'])); $this->assertTrue(in_array('name2', $attributes['gn'])); } @@ -388,17 +388,17 @@ class ImporterTest extends TestCase { $importer = new Importer(); $tasks = $importer->getTasks($lines); - $this->assertEquals(1, sizeof($tasks)); + $this->assertEquals(1, count($tasks)); $task = $tasks[0]; $this->assertEquals(MultiTask::class, $task::class); $subtasks = $task->getTasks(); - $this->assertEquals(1, sizeof($subtasks)); + $this->assertEquals(1, count($subtasks)); $subTask = $subtasks[0]; $this->assertEquals(DeleteAttributesTask::class, $subTask::class); $this->assertEquals($subTask->getDn(), 'uid=test,dc=example,dc=com'); $attributes = $subTask->getAttributes(); - $this->assertEquals(1, sizeof($attributes)); - $this->assertEquals(2, sizeof($attributes['uid'])); + $this->assertEquals(1, count($attributes)); + $this->assertEquals(2, count($attributes['uid'])); $this->assertTrue(in_array('uid1', $attributes['uid'])); $this->assertTrue(in_array('uid2', $attributes['uid'])); } @@ -417,11 +417,11 @@ class ImporterTest extends TestCase { $importer = new Importer(); $tasks = $importer->getTasks($lines); - $this->assertEquals(1, sizeof($tasks)); + $this->assertEquals(1, count($tasks)); $task = $tasks[0]; $this->assertEquals(MultiTask::class, $task::class); $subtasks = $task->getTasks(); - $this->assertEquals(1, sizeof($subtasks)); + $this->assertEquals(1, count($subtasks)); $subTask = $subtasks[0]; $this->assertEquals(DeleteAttributesTask::class, $subTask::class); $this->assertEquals($subTask->getDn(), 'uid=test,dc=example,dc=com'); @@ -445,17 +445,17 @@ class ImporterTest extends TestCase { $importer = new Importer(); $tasks = $importer->getTasks($lines); - $this->assertEquals(1, sizeof($tasks)); + $this->assertEquals(1, count($tasks)); $task = $tasks[0]; $this->assertEquals(MultiTask::class, $task::class); $subtasks = $task->getTasks(); - $this->assertEquals(1, sizeof($subtasks)); + $this->assertEquals(1, count($subtasks)); $subTask = $subtasks[0]; $this->assertEquals(ReplaceAttributesTask::class, $subTask::class); $this->assertEquals($subTask->getDn(), 'uid=test,dc=example,dc=com'); $attributes = $subTask->getAttributes(); - $this->assertEquals(1, sizeof($attributes)); - $this->assertEquals(2, sizeof($attributes['uid'])); + $this->assertEquals(1, count($attributes)); + $this->assertEquals(2, count($attributes['uid'])); $this->assertTrue(in_array('uid1', $attributes['uid'])); $this->assertTrue(in_array('uid2', $attributes['uid'])); } diff --git a/lam/tests/lib/LAMConfigTest.php b/lam/tests/lib/LAMConfigTest.php index 74b0d63e0..185ed8b4f 100644 --- a/lam/tests/lib/LAMConfigTest.php +++ b/lam/tests/lib/LAMConfigTest.php @@ -302,10 +302,10 @@ class LAMConfigTest extends TestCase { $val = 'server1;server2:label2;server3:label3:/prefix'; $this->assertTrue($this->lAMConfig->set_scriptServers($val)); $servers = $this->lAMConfig->getConfiguredScriptServers(); - $this->assertEquals(3, sizeof($servers)); + $this->assertEquals(3, count($servers)); $this->doSave(); $servers = $this->lAMConfig->getConfiguredScriptServers(); - $this->assertEquals(3, sizeof($servers)); + $this->assertEquals(3, count($servers)); $this->assertEquals('server1', $servers[0]->getServer()); $this->assertEquals('server2', $servers[1]->getServer()); $this->assertEquals('server3', $servers[2]->getServer()); @@ -920,14 +920,14 @@ class LAMConfigTest extends TestCase { * Checks that number of settings stays constant over multiple saves. */ public function testMultiSave() { - $sizeModSettings = sizeof($this->lAMConfig->get_moduleSettings()); - $sizeTypeSettings = sizeof($this->lAMConfig->get_typeSettings()); + $sizeModSettings = count($this->lAMConfig->get_moduleSettings()); + $sizeTypeSettings = count($this->lAMConfig->get_typeSettings()); $this->doSave(); - $this->assertEquals($sizeModSettings, sizeof($this->lAMConfig->get_moduleSettings())); - $this->assertEquals($sizeTypeSettings, sizeof($this->lAMConfig->get_typeSettings())); + $this->assertEquals($sizeModSettings, count($this->lAMConfig->get_moduleSettings())); + $this->assertEquals($sizeTypeSettings, count($this->lAMConfig->get_typeSettings())); $this->doSave(); - $this->assertEquals($sizeModSettings, sizeof($this->lAMConfig->get_moduleSettings())); - $this->assertEquals($sizeTypeSettings, sizeof($this->lAMConfig->get_typeSettings())); + $this->assertEquals($sizeModSettings, count($this->lAMConfig->get_moduleSettings())); + $this->assertEquals($sizeTypeSettings, count($this->lAMConfig->get_typeSettings())); } /** diff --git a/lam/tests/lib/PdfStructTest.php b/lam/tests/lib/PdfStructTest.php index f6f16b198..53c7e166e 100644 --- a/lam/tests/lib/PdfStructTest.php +++ b/lam/tests/lib/PdfStructTest.php @@ -50,13 +50,13 @@ class PdfStructTest extends TestCase { $this->assertEquals('User information', $structure->getTitle()); $this->assertEquals(PDFStructure::FOLDING_STANDARD, $structure->getFoldingMarks()); $sections = $structure->getSections(); - $this->assertEquals(4, sizeof($sections)); + $this->assertEquals(4, count($sections)); // check first section $this->assertInstanceOf(PDFEntrySection::class, $sections[0]); $this->assertFalse($sections[0]->isAttributeTitle()); $this->assertEquals('Personal user information', $sections[0]->getTitle()); $entries = $sections[0]->getEntries(); - $this->assertEquals(3, sizeof($entries)); + $this->assertEquals(3, count($entries)); $this->assertEquals('inetOrgPerson_givenName', $entries[0]->getKey()); $this->assertEquals('inetOrgPerson_sn', $entries[1]->getKey()); $this->assertEquals('inetOrgPerson_street', $entries[2]->getKey()); @@ -68,7 +68,7 @@ class PdfStructTest extends TestCase { $this->assertTrue($sections[2]->isAttributeTitle()); $this->assertEquals('posixAccount_uid', $sections[2]->getPdfKey()); $entries = $sections[2]->getEntries(); - $this->assertEquals(2, sizeof($entries)); + $this->assertEquals(2, count($entries)); $this->assertEquals('posixAccount_homeDirectory', $entries[0]->getKey()); $this->assertEquals('posixAccount_loginShell', $entries[1]->getKey()); // check fourth section @@ -76,7 +76,7 @@ class PdfStructTest extends TestCase { $this->assertFalse($sections[3]->isAttributeTitle()); $this->assertEquals('No entries', $sections[3]->getTitle()); $entries = $sections[3]->getEntries(); - $this->assertEquals(0, sizeof($entries)); + $this->assertEquals(0, count($entries)); } /** @@ -190,7 +190,7 @@ class PdfStructTest extends TestCase { $this->assertEquals('mytitle', $section->getTitle()); $entries = $section->getEntries(); - $this->assertEquals(2, sizeof($entries)); + $this->assertEquals(2, count($entries)); $this->assertEquals('e1', ($entries[0]->getKey())); $this->assertEquals('e2', ($entries[1]->getKey())); } @@ -225,12 +225,12 @@ class PdfStructTest extends TestCase { $this->assertEquals(PDFStructure::FOLDING_STANDARD, $structure->getFoldingMarks()); $this->assertEquals('logo', $structure->getLogo()); $sections = $structure->getSections(); - $this->assertEquals(2, sizeof($sections)); + $this->assertEquals(2, count($sections)); $this->assertTrue($sections[0] instanceof PDFTextSection); $this->assertEquals('textvalue', $sections[0]->getText()); $this->assertTrue($sections[1] instanceof PDFEntrySection); $entries = $sections[1]->getEntries(); - $this->assertEquals(2, sizeof($entries)); + $this->assertEquals(2, count($entries)); $this->assertEquals('e1', $entries[0]->getKey()); $this->assertEquals('e2', $entries[1]->getKey()); } diff --git a/lam/tests/lib/PublicKeyCredentialSourceRepositorySQLiteTest.php b/lam/tests/lib/PublicKeyCredentialSourceRepositorySQLiteTest.php index 7b4cbb09b..b55aa94b7 100644 --- a/lam/tests/lib/PublicKeyCredentialSourceRepositorySQLiteTest.php +++ b/lam/tests/lib/PublicKeyCredentialSourceRepositorySQLiteTest.php @@ -109,10 +109,10 @@ class PublicKeyCredentialSourceRepositorySQLiteTest extends TestCase { $this->assertNotNull($this->database->findOneByCredentialId("id1")); $this->assertNotNull($this->database->findOneByCredentialId("id2")); $this->assertNotNull($this->database->findOneByCredentialId("id3")); - $this->assertEquals(2, sizeof( + $this->assertEquals(2, count( $this->database->findAllForUserDn("cn=user1") )); - $this->assertEquals(1, sizeof( + $this->assertEquals(1, count( $this->database->findAllForUserDn("cn=user2") )); } diff --git a/lam/tests/lib/SecurityTest.php b/lam/tests/lib/SecurityTest.php index 2dfe2fc2a..835eb766c 100644 --- a/lam/tests/lib/SecurityTest.php +++ b/lam/tests/lib/SecurityTest.php @@ -23,8 +23,8 @@ use PHPUnit\Framework\TestCase; $_SERVER ['REMOTE_ADDR'] = '127.0.0.1'; -include_once 'lam/tests/utils/configuration.inc'; -include_once 'lam/lib/security.inc'; +include_once __DIR__ . '/../../tests/utils/configuration.inc'; +include_once __DIR__ . '/../../lib/security.inc'; /** * Checks password checking functions. diff --git a/lam/tests/lib/TypesTest.php b/lam/tests/lib/TypesTest.php index 3ffedf0cf..bd2cafee8 100644 --- a/lam/tests/lib/TypesTest.php +++ b/lam/tests/lib/TypesTest.php @@ -24,7 +24,7 @@ use user; */ -require_once 'lam/lib/types.inc'; +require_once __DIR__ . '/../../lib/types.inc'; /** * Checks code in types.inc. diff --git a/lam/tests/lib/modules/BindDLZTest.php b/lam/tests/lib/modules/BindDLZTest.php index 24be1ab54..b280115c8 100644 --- a/lam/tests/lib/modules/BindDLZTest.php +++ b/lam/tests/lib/modules/BindDLZTest.php @@ -5,11 +5,11 @@ use PHPUnit\Framework\TestCase; Copyright (C) 2018 - 2019 Roland Gruber */ -if (is_readable('lam/lib/modules/bindDLZ.inc')) { +if (is_readable(__DIR__ . '/../../../lib/modules/bindDLZ.inc')) { - include_once 'lam/lib/baseModule.inc'; - include_once 'lam/lib/modules.inc'; - include_once 'lam/lib/modules/bindDLZ.inc'; + include_once __DIR__ . '/../../../lib/baseModule.inc'; + include_once __DIR__ . '/../../../lib/modules.inc'; + include_once __DIR__ . '/../../../lib/modules/bindDLZ.inc'; /** * Checks the bindDLZ module. diff --git a/lam/tests/lib/modules/CustomFieldsTest.php b/lam/tests/lib/modules/CustomFieldsTest.php index 2ac068016..7430109ed 100644 --- a/lam/tests/lib/modules/CustomFieldsTest.php +++ b/lam/tests/lib/modules/CustomFieldsTest.php @@ -5,11 +5,11 @@ use PHPUnit\Framework\TestCase; Copyright (C) 2017 - 2023 Roland Gruber */ -if (is_readable('lam/lib/modules/customFields.inc')) { +if (is_readable(__DIR__ . '/../../../lib/modules/customFields.inc')) { - include_once 'lam/lib/baseModule.inc'; - include_once 'lam/lib/modules.inc'; - include_once 'lam/lib/modules/customFields.inc'; + include_once __DIR__ . '/../../../lib/baseModule.inc'; + include_once __DIR__ . '/../../../lib/modules.inc'; + include_once __DIR__ . '/../../../lib/modules/customFields.inc'; /** * Checks the ppolicy expire job. diff --git a/lam/tests/lib/modules/CustomScriptsTest.php b/lam/tests/lib/modules/CustomScriptsTest.php index 4a70fc4fc..cdb0e4d9d 100644 --- a/lam/tests/lib/modules/CustomScriptsTest.php +++ b/lam/tests/lib/modules/CustomScriptsTest.php @@ -27,11 +27,11 @@ use PHPUnit\Framework\TestCase; */ -if (is_readable('lam/lib/modules/customScripts.inc')) { +if (is_readable(__DIR__ . '/../../../lib/modules/customScripts.inc')) { - include_once 'lam/lib/baseModule.inc'; - include_once 'lam/lib/modules.inc'; - include_once 'lam/lib/modules/customScripts.inc'; + include_once __DIR__ . '/../../../lib/baseModule.inc'; + include_once __DIR__ . '/../../../lib/modules.inc'; + include_once __DIR__ . '/../../../lib/modules/customScripts.inc'; /** * Checks the custom scripts. @@ -152,7 +152,7 @@ if (is_readable('lam/lib/modules/customScripts.inc')) { $this->assertNull($script->getLabel()); $this->assertEquals(_('Pre-create'), $script->getTypeLabel()); - $this->assertEquals(4, sizeof($parser->getManualOptions())); + $this->assertEquals(4, count($parser->getManualOptions())); $this->assertEquals('select', $parser->getManualOptions()[0]['type']); $this->assertEquals('select', $parser->getManualOptions()[1]['type']); $this->assertEquals('LAM_SELECTION_ENV', $parser->getManualOptions()[0]['name']); diff --git a/lam/tests/lib/modules/PPolicyUserPasswordNotifyJobTest.php b/lam/tests/lib/modules/PPolicyUserPasswordNotifyJobTest.php index 9ac4038e6..186538b42 100644 --- a/lam/tests/lib/modules/PPolicyUserPasswordNotifyJobTest.php +++ b/lam/tests/lib/modules/PPolicyUserPasswordNotifyJobTest.php @@ -23,12 +23,12 @@ use PHPUnit\Framework\TestCase; */ -if (is_readable('lam/lib/modules/ppolicyUser.inc')) { +if (is_readable(__DIR__ . '/../../../lib/modules/ppolicyUser.inc')) { - include_once 'lam/lib/baseModule.inc'; - include_once 'lam/lib/modules.inc'; - include_once 'lam/lib/passwordExpirationJob.inc'; - include_once 'lam/lib/modules/ppolicyUser.inc'; + include_once __DIR__ . '/../../../lib/baseModule.inc'; + include_once __DIR__ . '/../../../lib/modules.inc'; + include_once __DIR__ . '/../../../lib/passwordExpirationJob.inc'; + include_once __DIR__ . '/../../../lib/modules/ppolicyUser.inc'; /** * Checks the ppolicy expire job. diff --git a/lam/tests/lib/modules/RequestAccessTest.php b/lam/tests/lib/modules/RequestAccessTest.php index 78c1e0d1b..c321a9439 100644 --- a/lam/tests/lib/modules/RequestAccessTest.php +++ b/lam/tests/lib/modules/RequestAccessTest.php @@ -21,10 +21,10 @@ use PHPUnit\Framework\TestCase; */ -if (is_readable('lam/lib/modules/requestAccess.inc')) { +if (is_readable(__DIR__ . '/../../../lib/modules/requestAccess.inc')) { - include_once 'lam/lib/baseModule.inc'; - include_once 'lam/lib/modules/requestAccess.inc'; + include_once __DIR__ . '/../../../lib/baseModule.inc'; + include_once __DIR__ . '/../../../lib/modules/requestAccess.inc'; /** * Checks sudo role functions. diff --git a/lam/tests/lib/modules/SambaSamAccountTest.php b/lam/tests/lib/modules/SambaSamAccountTest.php index f6ea43081..164bcc496 100644 --- a/lam/tests/lib/modules/SambaSamAccountTest.php +++ b/lam/tests/lib/modules/SambaSamAccountTest.php @@ -21,9 +21,9 @@ use PHPUnit\Framework\TestCase; */ -include_once 'lam/lib/baseModule.inc'; -include_once 'lam/lib/modules.inc'; -include_once 'lam/lib/modules/sambaSamAccount.inc'; +include_once __DIR__ . '/../../../lib/baseModule.inc'; +include_once __DIR__ . '/../../../lib/modules.inc'; +include_once __DIR__ . '/../../../lib/modules/sambaSamAccount.inc'; /** * Checks the shadow expire job. diff --git a/lam/tests/lib/modules/ShadowAccountPasswordNotifyJobTest.php b/lam/tests/lib/modules/ShadowAccountPasswordNotifyJobTest.php index db11e918b..d77a5bb36 100644 --- a/lam/tests/lib/modules/ShadowAccountPasswordNotifyJobTest.php +++ b/lam/tests/lib/modules/ShadowAccountPasswordNotifyJobTest.php @@ -23,14 +23,14 @@ use PHPUnit\Framework\TestCase; */ -include_once 'lam/lib/baseModule.inc'; -include_once 'lam/lib/modules.inc'; -if (is_readable('lam/lib/passwordExpirationJob.inc')) { - include_once 'lam/lib/passwordExpirationJob.inc'; +include_once __DIR__ . '/../../../lib/baseModule.inc'; +include_once __DIR__ . '/../../../lib/modules.inc'; +if (is_readable(__DIR__ . '/../../../lib/passwordExpirationJob.inc')) { + include_once __DIR__ . '/../../../lib/passwordExpirationJob.inc'; } -include_once 'lam/lib/modules/shadowAccount.inc'; +include_once __DIR__ . '/../../../lib/modules/shadowAccount.inc'; -if (is_readable('lam/lib/passwordExpirationJob.inc')) { +if (is_readable(__DIR__ . '/../../../lib/passwordExpirationJob.inc')) { /** * Checks the shadow expire job. diff --git a/lam/tests/lib/modules/ShadowAccountTest.php b/lam/tests/lib/modules/ShadowAccountTest.php index 31d266f18..69454644f 100644 --- a/lam/tests/lib/modules/ShadowAccountTest.php +++ b/lam/tests/lib/modules/ShadowAccountTest.php @@ -23,12 +23,12 @@ use PHPUnit\Framework\TestCase; */ - include_once 'lam/lib/baseModule.inc'; - include_once 'lam/lib/modules.inc'; - if (is_readable('lam/lib/passwordExpirationJob.inc')) { - include_once 'lam/lib/passwordExpirationJob.inc'; + include_once __DIR__ . '/../../../lib/baseModule.inc'; + include_once __DIR__ . '/../../../lib/modules.inc'; + if (is_readable(__DIR__ . '/../../../lib/passwordExpirationJob.inc')) { + include_once __DIR__ . '/../../../lib/passwordExpirationJob.inc'; } - include_once 'lam/lib/modules/shadowAccount.inc'; + include_once __DIR__ . '/../../../lib/modules/shadowAccount.inc'; /** * Checks the shadowAccount class. diff --git a/lam/tests/lib/modules/SudoRoleTest.php b/lam/tests/lib/modules/SudoRoleTest.php index 2d09d0f2c..106fb846d 100644 --- a/lam/tests/lib/modules/SudoRoleTest.php +++ b/lam/tests/lib/modules/SudoRoleTest.php @@ -21,10 +21,10 @@ use PHPUnit\Framework\TestCase; */ -if (is_readable('lam/lib/modules/sudoRole.inc')) { +if (is_readable(__DIR__ . '/../../../lib/modules/sudoRole.inc')) { - include_once 'lam/lib/baseModule.inc'; - include_once 'lam/lib/modules/sudoRole.inc'; + include_once __DIR__ . '/../../../lib/baseModule.inc'; + include_once __DIR__ . '/../../../lib/modules/sudoRole.inc'; /** * Checks sudo role functions. From 9d3dbd78ffb820244d27c558a238be55b12bdc07 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Tue, 17 Dec 2024 07:57:33 +0100 Subject: [PATCH 50/78] refactoring --- lam/lib/modules/eduPerson.inc | 37 ++++++++++++++++------------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/lam/lib/modules/eduPerson.inc b/lam/lib/modules/eduPerson.inc index ef666eea8..cc632ec08 100644 --- a/lam/lib/modules/eduPerson.inc +++ b/lam/lib/modules/eduPerson.inc @@ -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; } From 4957e7193efec442d3b9d157e4a85d39d285a1de Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Tue, 17 Dec 2024 07:59:41 +0100 Subject: [PATCH 51/78] refactoring --- rector.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rector.php b/rector.php index b9e7aa28c..7f70634b1 100644 --- a/rector.php +++ b/rector.php @@ -5,6 +5,7 @@ use Rector\CodeQuality\Rector\Empty_\SimplifyEmptyCheckOnEmptyArrayRector; use Rector\CodeQuality\Rector\For_\ForRepeatedCountToOwnVariableRector; use Rector\CodeQuality\Rector\Identical\FlipTypeControlToUseExclusiveTypeRector; use Rector\Config\RectorConfig; +use Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPrivateMethodRector; use Rector\Php70\Rector\StaticCall\StaticCallOnNonStaticToInstanceCallRector; use Rector\Php73\Rector\FuncCall\StringifyStrNeedlesRector; use Rector\Php74\Rector\Property\RestoreDefaultNullToNullableTypePropertyRector; @@ -41,6 +42,8 @@ return RectorConfig::configure() DisallowedEmptyRuleFixerRector::class, FlipTypeControlToUseExclusiveTypeRector::class, InlineArrayReturnAssignRector::class, + // TODO private method check is unreliable, recheck with newer rector version + RemoveUnusedPrivateMethodRector::class ]) ->withFileExtensions([ 'php', From 468fad0ffa6cc3af0061b994ddd3c2943e652d53 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Wed, 18 Dec 2024 09:00:37 +0100 Subject: [PATCH 52/78] refactoring --- lam/lib/modules/freeRadius.inc | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/lam/lib/modules/freeRadius.inc b/lam/lib/modules/freeRadius.inc index 64a93c088..3625c6477 100644 --- a/lam/lib/modules/freeRadius.inc +++ b/lam/lib/modules/freeRadius.inc @@ -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') From cb2953f5a2d36162c2091d362da5ebd0b0f944b8 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Wed, 18 Dec 2024 09:13:33 +0100 Subject: [PATCH 53/78] refactoring --- lam/lib/modules/fixed_ip.inc | 93 +++++++++++++++++------------------- 1 file changed, 44 insertions(+), 49 deletions(-) diff --git a/lam/lib/modules/fixed_ip.inc b/lam/lib/modules/fixed_ip.inc index 2aa5af725..abeaa41f8 100644 --- a/lam/lib/modules/fixed_ip.inc +++ b/lam/lib/modules/fixed_ip.inc @@ -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('
', false)); - if ($i < (sizeof($order) - 1)) { + if ($i < (count($order) - 1)) { $group->addElement(new htmlOutputText('
', false)); } } From a4b413a7b9c663b2d9bf4de7640e1f9f55ce562c Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Wed, 18 Dec 2024 09:20:44 +0100 Subject: [PATCH 54/78] refactoring --- rector.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/rector.php b/rector.php index 7f70634b1..4d104cc6e 100644 --- a/rector.php +++ b/rector.php @@ -1,11 +1,13 @@ withFileExtensions([ 'php', From 30b5f92658bbf82335d3dc76bf04b32f9af7a942 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Wed, 18 Dec 2024 10:02:41 +0100 Subject: [PATCH 55/78] refactoring --- lam/lib/modules/hostObject.inc | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/lam/lib/modules/hostObject.inc b/lam/lib/modules/hostObject.inc index 21ea26e5d..ae1fe32f7 100644 --- a/lam/lib/modules/hostObject.inc +++ b/lam/lib/modules/hostObject.inc @@ -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; - } /** From da91a73104e9879fbac205c3b3d78f8b855e4e96 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Wed, 18 Dec 2024 10:27:54 +0100 Subject: [PATCH 56/78] refactoring --- lam/lib/modules/ieee802device.inc | 4 +- lam/lib/modules/imapAccess.inc | 65 ++--- lam/lib/modules/inetLocalMailRecipient.inc | 12 +- lam/lib/modules/inetOrgPerson.inc | 294 ++++++++++----------- 4 files changed, 176 insertions(+), 199 deletions(-) diff --git a/lam/lib/modules/ieee802device.inc b/lam/lib/modules/ieee802device.inc index ad0395d12..b9416cac2 100644 --- a/lam/lib/modules/ieee802device.inc +++ b/lam/lib/modules/ieee802device.inc @@ -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"; diff --git a/lam/lib/modules/imapAccess.inc b/lam/lib/modules/imapAccess.inc index cee100471..a8ca6f38d 100644 --- a/lam/lib/modules/imapAccess.inc +++ b/lam/lib/modules/imapAccess.inc @@ -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); } /** diff --git a/lam/lib/modules/inetLocalMailRecipient.inc b/lam/lib/modules/inetLocalMailRecipient.inc index ce869525e..68229c8aa 100644 --- a/lam/lib/modules/inetLocalMailRecipient.inc +++ b/lam/lib/modules/inetLocalMailRecipient.inc @@ -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"; diff --git a/lam/lib/modules/inetOrgPerson.inc b/lam/lib/modules/inetOrgPerson.inc index 1463d564e..7aa3d2832 100644 --- a/lam/lib/modules/inetOrgPerson.inc +++ b/lam/lib/modules/inetOrgPerson.inc @@ -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", '
', htmlspecialchars($postalAddresses[$i])); $addressContainer->addElement(new htmlOutputText($val, false)); - if ($i < (sizeof($postalAddresses) - 1)) { + if ($i < (count($postalAddresses) - 1)) { $addressContainer->addElement(new htmlOutputText('
', 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('
', 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", '
', htmlspecialchars($registeredAddresses[$i])); $registeredAddressContainer->addElement(new htmlOutputText($val, false)); - if ($i < (sizeof($registeredAddresses) - 1)) { + if ($i < (count($registeredAddresses) - 1)) { $registeredAddressContainer->addElement(new htmlOutputText('
', 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('
', 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 . '
' . 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 . '
' . 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(", ")); } From f802edbe4a6da5535b5c44fb0268c94acbea3f52 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Wed, 18 Dec 2024 10:46:56 +0100 Subject: [PATCH 57/78] refactoring --- lam/lib/modules/kolabGroup.inc | 8 ++--- lam/lib/modules/kolabSharedFolder.inc | 16 ++++----- lam/lib/modules/kolabUser.inc | 52 +++++++++++++-------------- 3 files changed, 38 insertions(+), 38 deletions(-) diff --git a/lam/lib/modules/kolabGroup.inc b/lam/lib/modules/kolabGroup.inc index 8f263b294..e2adc21ef 100644 --- a/lam/lib/modules/kolabGroup.inc +++ b/lam/lib/modules/kolabGroup.inc @@ -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; } } diff --git a/lam/lib/modules/kolabSharedFolder.inc b/lam/lib/modules/kolabSharedFolder.inc index 0332fdae6..f0db7ea6c 100644 --- a/lam/lib/modules/kolabSharedFolder.inc +++ b/lam/lib/modules/kolabSharedFolder.inc @@ -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(", ")); } diff --git a/lam/lib/modules/kolabUser.inc b/lam/lib/modules/kolabUser.inc index e19ace070..bdb4547fd 100644 --- a/lam/lib/modules/kolabUser.inc +++ b/lam/lib/modules/kolabUser.inc @@ -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; From 7cf80b57a49e397ef75a24e7891ca5775b7724c0 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Wed, 18 Dec 2024 11:02:38 +0100 Subject: [PATCH 58/78] refactoring --- lam/lib/modules/ldapPublicKey.inc | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/lam/lib/modules/ldapPublicKey.inc b/lam/lib/modules/ldapPublicKey.inc index 90fb67226..1cff4b4e7 100644 --- a/lam/lib/modules/ldapPublicKey.inc +++ b/lam/lib/modules/ldapPublicKey.inc @@ -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 { From 0694ed552fc4c7e0cba6924567b5782813d8c465 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Wed, 18 Dec 2024 12:44:24 +0100 Subject: [PATCH 59/78] refactoring --- lam/lib/modules/nisMailAlias.inc | 26 +++++++-------- lam/lib/modules/nisMailAliasUser.inc | 50 ++++++++++++++-------------- lam/lib/modules/nisNetGroupHost.inc | 6 ++-- lam/lib/modules/nisNetGroupUser.inc | 18 +++++----- lam/lib/modules/nisnetgroup.inc | 24 ++++++------- 5 files changed, 62 insertions(+), 62 deletions(-) diff --git a/lam/lib/modules/nisMailAlias.inc b/lam/lib/modules/nisMailAlias.inc index 7b1edcf41..d21962cdd 100644 --- a/lam/lib/modules/nisMailAlias.inc +++ b/lam/lib/modules/nisMailAlias.inc @@ -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(' ', 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]); diff --git a/lam/lib/modules/nisMailAliasUser.inc b/lam/lib/modules/nisMailAliasUser.inc index 576fc2ed9..e328839be 100644 --- a/lam/lib/modules/nisMailAliasUser.inc +++ b/lam/lib/modules/nisMailAliasUser.inc @@ -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; diff --git a/lam/lib/modules/nisNetGroupHost.inc b/lam/lib/modules/nisNetGroupHost.inc index 3e6d052df..43ab9ecf9 100644 --- a/lam/lib/modules/nisNetGroupHost.inc +++ b/lam/lib/modules/nisNetGroupHost.inc @@ -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'); diff --git a/lam/lib/modules/nisNetGroupUser.inc b/lam/lib/modules/nisNetGroupUser.inc index 2a0803b25..dd9f550a1 100644 --- a/lam/lib/modules/nisNetGroupUser.inc +++ b/lam/lib/modules/nisNetGroupUser.inc @@ -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]; } diff --git a/lam/lib/modules/nisnetgroup.inc b/lam/lib/modules/nisnetgroup.inc index 15991c95a..66d3b45ed 100644 --- a/lam/lib/modules/nisnetgroup.inc +++ b/lam/lib/modules/nisnetgroup.inc @@ -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; From b6d8b937334c36d1c0c69ad1231c8a1cf407e63f Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 19 Dec 2024 10:01:04 +0100 Subject: [PATCH 60/78] refactoring --- lam/lib/modules/puppetClient.inc | 26 ++++++++++---------- lam/lib/modules/pykotaGroup.inc | 14 +++++------ lam/lib/modules/pykotaPrinter.inc | 41 ++++++++++--------------------- lam/lib/modules/pykotaUser.inc | 19 ++++++-------- 4 files changed, 40 insertions(+), 60 deletions(-) diff --git a/lam/lib/modules/puppetClient.inc b/lam/lib/modules/puppetClient.inc index 94f633f86..2d2106f0b 100644 --- a/lam/lib/modules/puppetClient.inc +++ b/lam/lib/modules/puppetClient.inc @@ -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('
', 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; } diff --git a/lam/lib/modules/pykotaGroup.inc b/lam/lib/modules/pykotaGroup.inc index cdc3ea32c..d1d657afe 100644 --- a/lam/lib/modules/pykotaGroup.inc +++ b/lam/lib/modules/pykotaGroup.inc @@ -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; } } diff --git a/lam/lib/modules/pykotaPrinter.inc b/lam/lib/modules/pykotaPrinter.inc index 1f05e8d37..4a1b5d330 100644 --- a/lam/lib/modules/pykotaPrinter.inc +++ b/lam/lib/modules/pykotaPrinter.inc @@ -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; diff --git a/lam/lib/modules/pykotaUser.inc b/lam/lib/modules/pykotaUser.inc index 851080a13..5f4032645 100644 --- a/lam/lib/modules/pykotaUser.inc +++ b/lam/lib/modules/pykotaUser.inc @@ -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(", ")); } From 4cc3f0128e30c5b24a241af173df2642bd82707e Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 19 Dec 2024 10:17:38 +0100 Subject: [PATCH 61/78] refactoring --- lam/lib/modules/posixAccount.inc | 419 +++++++++++++++---------------- 1 file changed, 200 insertions(+), 219 deletions(-) diff --git a/lam/lib/modules/posixAccount.inc b/lam/lib/modules/posixAccount.inc index 59d03bb1f..e1041c83f 100644 --- a/lam/lib/modules/posixAccount.inc +++ b/lam/lib/modules/posixAccount.inc @@ -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; } From c9cacdece60d04d14799f5682d116ecf7f96d296 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 19 Dec 2024 10:52:41 +0100 Subject: [PATCH 62/78] refactoring --- lam/lib/modules/posixGroup.inc | 61 +++++++++++++--------------------- 1 file changed, 24 insertions(+), 37 deletions(-) diff --git a/lam/lib/modules/posixGroup.inc b/lam/lib/modules/posixGroup.inc index 9b24d4569..2e610d498 100644 --- a/lam/lib/modules/posixGroup.inc +++ b/lam/lib/modules/posixGroup.inc @@ -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; From 8a204a028b1d67f559d3cdee7bf9e59308f69351 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Fri, 20 Dec 2024 14:42:56 +0100 Subject: [PATCH 63/78] refactoring --- lam/lib/modules/quota.inc | 70 +++++++++++++++++++-------------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/lam/lib/modules/quota.inc b/lam/lib/modules/quota.inc index b8498b2c7..10c2a7541 100644 --- a/lam/lib/modules/quota.inc +++ b/lam/lib/modules/quota.inc @@ -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']; From e7953f25d7ae3a7273635755a21982ea94b381e7 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Fri, 20 Dec 2024 14:49:46 +0100 Subject: [PATCH 64/78] refactoring --- lam/lib/modules/range.inc | 62 +++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/lam/lib/modules/range.inc b/lam/lib/modules/range.inc index 9ece0ff86..ff484b195 100644 --- a/lam/lib/modules/range.inc +++ b/lam/lib/modules/range.inc @@ -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; From ec0782a502aad33529cad1aa5436a68c3eab59d6 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Fri, 20 Dec 2024 14:59:02 +0100 Subject: [PATCH 65/78] refactoring --- lam/help/help.inc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lam/help/help.inc b/lam/help/help.inc index e1f80e89f..caf6ef044 100644 --- a/lam/help/help.inc +++ b/lam/help/help.inc @@ -42,9 +42,9 @@ if (isset($_SESSION['conf_config'])) { $entry206Example .= "" . $type->getAlias() . ":
\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 .= ", "; } } From a5b558e94bd107ba1bccde320173101591c1cc9a Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Fri, 20 Dec 2024 19:54:40 +0100 Subject: [PATCH 66/78] refactoring --- lam/lib/modules/systemQuotas.inc | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lam/lib/modules/systemQuotas.inc b/lam/lib/modules/systemQuotas.inc index 0debcce0b..99a4dd152 100644 --- a/lam/lib/modules/systemQuotas.inc +++ b/lam/lib/modules/systemQuotas.inc @@ -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%'); From b9015905b6f956d562b650d02ea35f8521f49ba9 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Fri, 20 Dec 2024 19:55:37 +0100 Subject: [PATCH 67/78] refactoring --- lam/lib/modules/shadowAccount.inc | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lam/lib/modules/shadowAccount.inc b/lam/lib/modules/shadowAccount.inc index 612c759cb..11d4e0a8b 100644 --- a/lam/lib/modules/shadowAccount.inc +++ b/lam/lib/modules/shadowAccount.inc @@ -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'; From f0b7ccc6e85c84175a243553b18a6b43c4f4664f Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sun, 22 Dec 2024 09:51:13 +0100 Subject: [PATCH 68/78] refactoring --- lam/lib/modules/sambaSamAccount.inc | 372 ++++++++++++---------------- 1 file changed, 159 insertions(+), 213 deletions(-) diff --git a/lam/lib/modules/sambaSamAccount.inc b/lam/lib/modules/sambaSamAccount.inc index 238fc85e6..fda988fa7 100644 --- a/lam/lib/modules/sambaSamAccount.inc +++ b/lam/lib/modules/sambaSamAccount.inc @@ -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'; From f327b71fa9773a8c16205046748de725a3dae0dd Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Wed, 25 Dec 2024 09:04:00 +0100 Subject: [PATCH 69/78] refactoring --- lam/lib/modules/sambaDomain.inc | 64 ++++++++++++++------------------- 1 file changed, 27 insertions(+), 37 deletions(-) diff --git a/lam/lib/modules/sambaDomain.inc b/lam/lib/modules/sambaDomain.inc index 278618d9b..c4b375e22 100644 --- a/lam/lib/modules/sambaDomain.inc +++ b/lam/lib/modules/sambaDomain.inc @@ -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"; From 9143c8ab452a6b5ac5d5405f1cc35fc316fd25e2 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Wed, 25 Dec 2024 09:07:52 +0100 Subject: [PATCH 70/78] refactoring --- lam/lib/modules/sambaGroupMapping.inc | 62 ++++++++++----------------- 1 file changed, 23 insertions(+), 39 deletions(-) diff --git a/lam/lib/modules/sambaGroupMapping.inc b/lam/lib/modules/sambaGroupMapping.inc index 86212692f..338279444 100644 --- a/lam/lib/modules/sambaGroupMapping.inc +++ b/lam/lib/modules/sambaGroupMapping.inc @@ -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]); From 90cccc2c2dd0aecd698daf0e742504432ca79bf4 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 26 Dec 2024 20:30:27 +0100 Subject: [PATCH 71/78] refactoring --- lam/lib/modules/yubiKeyUser.inc | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/lam/lib/modules/yubiKeyUser.inc b/lam/lib/modules/yubiKeyUser.inc index 407d480b6..f5f69ff79 100644 --- a/lam/lib/modules/yubiKeyUser.inc +++ b/lam/lib/modules/yubiKeyUser.inc @@ -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 { From 6a17b54e9d73d9d785ff86cf2f67cc7bac289424 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Thu, 26 Dec 2024 20:31:40 +0100 Subject: [PATCH 72/78] refactoring --- lam/lib/modules/windowsHost.inc | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lam/lib/modules/windowsHost.inc b/lam/lib/modules/windowsHost.inc index 9e0079ea7..0b0e9892d 100644 --- a/lam/lib/modules/windowsHost.inc +++ b/lam/lib/modules/windowsHost.inc @@ -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; } } From 61036d8f2c4c54cd97f693976a1cdd3dba99f3f0 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sun, 29 Dec 2024 10:55:08 +0100 Subject: [PATCH 73/78] refactoring --- lam/lib/modules/windowsGroup.inc | 88 ++++++++++++++++---------------- 1 file changed, 43 insertions(+), 45 deletions(-) diff --git a/lam/lib/modules/windowsGroup.inc b/lam/lib/modules/windowsGroup.inc index 68532bbd5..d93f4b597 100644 --- a/lam/lib/modules/windowsGroup.inc +++ b/lam/lib/modules/windowsGroup.inc @@ -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) { From a6f93a87f47e9f29fce28318a2b4cf59fa357c41 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sun, 29 Dec 2024 11:00:17 +0100 Subject: [PATCH 74/78] refactoring --- lam/lib/modules/windowsUser.inc | 141 ++++++++++++++------------------ 1 file changed, 61 insertions(+), 80 deletions(-) diff --git a/lam/lib/modules/windowsUser.inc b/lam/lib/modules/windowsUser.inc index 212bcdaea..2142a4c39 100644 --- a/lam/lib/modules/windowsUser.inc +++ b/lam/lib/modules/windowsUser.inc @@ -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!') . '
' . 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) { + $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) { + $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) { + $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)])) { From 104dabc82d14f5a1ba6e3ed88e7df9c4347ef87d Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sun, 29 Dec 2024 11:02:57 +0100 Subject: [PATCH 75/78] refactoring --- lam/lib/modules/windowsUser.inc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lam/lib/modules/windowsUser.inc b/lam/lib/modules/windowsUser.inc index 2142a4c39..36d991554 100644 --- a/lam/lib/modules/windowsUser.inc +++ b/lam/lib/modules/windowsUser.inc @@ -3896,7 +3896,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr if ($deactivated) { $attrs[$key][0] = intval($value[0]) | self::AC_ACCOUNT_DISABLED; } - elseif (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; } } @@ -3928,7 +3928,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr if ($requireCard) { $attrs[$key][0] = intval($value[0]) | self::AC_SMARTCARD_REQUIRED; } - elseif (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; } } @@ -3960,7 +3960,7 @@ class windowsUser extends baseModule implements passwordService, AccountStatusPr if ($neverExpires) { $attrs[$key][0] = (string) (intval($value[0]) | self::AC_PWD_NEVER_EXPIRES); } - elseif (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); } } From 6b4e59bc323533ea5f376ed6991ee47feeb24de4 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sun, 29 Dec 2024 11:22:06 +0100 Subject: [PATCH 76/78] refactoring --- rector.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/rector.php b/rector.php index 4d104cc6e..f80acaacc 100644 --- a/rector.php +++ b/rector.php @@ -1,6 +1,7 @@ withFileExtensions([ 'php', From 097a46a86191964e03cb982d1b7d70ab3b77e54f Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sun, 29 Dec 2024 11:31:56 +0100 Subject: [PATCH 77/78] refactoring --- phpstan.neon | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/phpstan.neon b/phpstan.neon index 970f5a3fe..5422d7e42 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -38,7 +38,7 @@ parameters: - '#Parameter \#1 \$array of function array_keys expects array, mixed given.#' - '#Argument of an invalid type mixed supplied for foreach, only iterables are supported.#' - '#Parameter \#2 \$args of function call_user_func_array expects array, mixed given.#' - - '#Parameter \#1 \$input of static method LAM\\AJAX\\Ajax::managePasswordChange\(\) expects array, mixed given.#' + - '#Parameter \#1 \$input of method LAM\\AJAX\\Ajax::managePasswordChange\(\) expects array, mixed given.#' - '#Parameter \#1 \$input of method LAM\\AJAX\\Ajax::checkPasswordStrength\(\) expects array, mixed given.#' - - '#Cannot access offset non-falsy-string on array\|object.#' + - '#Cannot access offset non-falsy-string on array\|object.#' - '#Unable to resolve the template type T in call to function array_values#' From 10e18741b5463f6103d963ec9b08b0110e03eb06 Mon Sep 17 00:00:00 2001 From: Roland Gruber Date: Sun, 29 Dec 2024 11:35:50 +0100 Subject: [PATCH 78/78] refactoring --- lam/lib/modules/sambaSamAccount/sambaMungedDial.inc | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/lam/lib/modules/sambaSamAccount/sambaMungedDial.inc b/lam/lib/modules/sambaSamAccount/sambaMungedDial.inc index 7c4764364..18310e46d 100644 --- a/lam/lib/modules/sambaSamAccount/sambaMungedDial.inc +++ b/lam/lib/modules/sambaSamAccount/sambaMungedDial.inc @@ -478,9 +478,7 @@ class sambaMungedDial { /** SMARTY: gets the checkbox state of "Connection" */ function getCtxMaxConnectionTimeF() { // Connection Time is 0 if disabled - $result = isset($this->ctx['CtxMaxConnectionTime']) && ($this->ctx['CtxMaxConnectionTime'] != 0); - - return $result; + return isset($this->ctx['CtxMaxConnectionTime']) && ($this->ctx['CtxMaxConnectionTime'] != 0); } /** SMARTY: sets the checkbox "Connection" to unchecked */ @@ -493,9 +491,7 @@ class sambaMungedDial { /** SMARTY: gets the checkbox state of "Disconnection" */ function getCtxMaxDisconnectionTimeF() { // Connection Time is 0 if disabled - $result = isset($this->ctx['CtxMaxDisconnectionTime']) && ($this->ctx['CtxMaxDisconnectionTime'] != 0); - - return $result; + return isset($this->ctx['CtxMaxDisconnectionTime']) && ($this->ctx['CtxMaxDisconnectionTime'] != 0); } /** SMARTY: sets the checkbox "Disconnection" to unchecked */ @@ -508,9 +504,7 @@ class sambaMungedDial { /** SMARTY: gets the checkbox state of "Idle" */ function getCtxMaxIdleTimeF() { // Connection Time is 0 if disabled - $result = isset($this->ctx['CtxMaxIdleTime']) && ($this->ctx['CtxMaxIdleTime'] != 0); - - return $result; + return isset($this->ctx['CtxMaxIdleTime']) && ($this->ctx['CtxMaxIdleTime'] != 0); } /** SMARTY: sets the checkbox "Idle" to unchecked */