diff --git a/app/availableplugins/UnixCluster/README.md b/app/availableplugins/UnixCluster/README.md
new file mode 100644
index 000000000..571f6fea4
--- /dev/null
+++ b/app/availableplugins/UnixCluster/README.md
@@ -0,0 +1,18 @@
+# UnixCluster plugin for COmanage Registry
+
+The Unix Cluster plugin manages Unix Accounts for People. Each instance represents
+a single (logical) Unix Cluster, configured via a Cluster of type
+`UnixCluster.UnixClusters`.
+
+This is a non-core plugin. To enable it:
+
+```
+bin/cake plugin --action activate --plugin UnixCluster
+```
+
+## Usernames
+
+Unix Cluster Account usernames are copied from the Person Identifier of the cluster's Username Type and may be at most 32 characters. The plugin does not restrict which characters a username contains, so formats such as `user@domain` can be used where the target systems support them. For portable usernames, generate the Username Identifier with an Identifier Assignment whose Permitted Characters setting is *AlphaNumeric Only*. Characters such as `:`, `/`, `\`, whitespace, control characters or a leading `-` can break `/etc/passwd`, home directory paths, terminals and scripts on many systems.
+
+See the [Unix Cluster Plugin documentation](https://spaces.at.internet2.edu/display/COmanage/Unix+Cluster+Plugin)
+for more information.
diff --git a/app/availableplugins/UnixCluster/composer.json b/app/availableplugins/UnixCluster/composer.json
new file mode 100644
index 000000000..f8ab70bea
--- /dev/null
+++ b/app/availableplugins/UnixCluster/composer.json
@@ -0,0 +1,24 @@
+{
+ "name": "comanage-registry/unix-cluster",
+ "description": "UnixCluster plugin for COmanage Registry",
+ "type": "cakephp-plugin",
+ "license": "MIT",
+ "require": {
+ "php": ">=7.2",
+ "cakephp/cakephp": "4.4.*"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^8.5 || ^9.3"
+ },
+ "autoload": {
+ "psr-4": {
+ "UnixCluster\\": "src/"
+ }
+ },
+ "autoload-dev": {
+ "psr-4": {
+ "UnixCluster\\Test\\": "tests/",
+ "Cake\\Test\\": "vendor/cakephp/cakephp/tests/"
+ }
+ }
+}
diff --git a/app/availableplugins/UnixCluster/config/plugin.json b/app/availableplugins/UnixCluster/config/plugin.json
new file mode 100644
index 000000000..6c9426534
--- /dev/null
+++ b/app/availableplugins/UnixCluster/config/plugin.json
@@ -0,0 +1,76 @@
+{
+ "types": {
+ "cluster": [
+ "UnixClusters"
+ ]
+ },
+ "schema": {
+ "tables": {
+ "unix_clusters": {
+ "columns": {
+ "id": {},
+ "cluster_id": {},
+ "sync_mode": { "type": "enum" },
+ "username_type_id": { "type": "integer", "foreignkey": { "table": "types", "column": "id" } },
+ "uid_type_id": { "type": "integer", "foreignkey": { "table": "types", "column": "id" } },
+ "default_shell": { "type": "string", "size": 64 },
+ "homedir_prefix": { "type": "string", "size": 64 },
+ "homedir_subdivisions": { "type": "integer" },
+ "groupname_type_id": { "type": "integer", "foreignkey": { "table": "types", "column": "id" } },
+ "gid_type_id": { "type": "integer", "foreignkey": { "table": "types", "column": "id" } },
+ "default_group_mode": {
+ "type": "enum",
+ "comment": "Explicit Existing/Personal mode, so that an empty default_group_id never implicitly means create a personal group per account"
+ },
+ "default_group_id": { "type": "integer", "foreignkey": { "table": "groups", "column": "id" }, "notnull": false }
+ },
+ "indexes": {
+ "unix_clusters_i1": { "columns": [ "cluster_id" ]},
+ "unix_clusters_i2": { "needed": false, "columns": [ "username_type_id" ]},
+ "unix_clusters_i3": { "needed": false, "columns": [ "uid_type_id" ]},
+ "unix_clusters_i4": { "needed": false, "columns": [ "groupname_type_id" ]},
+ "unix_clusters_i5": { "needed": false, "columns": [ "gid_type_id" ]},
+ "unix_clusters_i6": { "needed": false, "columns": [ "default_group_id" ]}
+ }
+ },
+ "unix_cluster_groups": {
+ "columns": {
+ "id": {},
+ "unix_cluster_id": { "type": "integer", "foreignkey": { "table": "unix_clusters", "column": "id" }, "notnull": true },
+ "group_id": { "notnull": true },
+ "origin": { "type": "enum" },
+ "person_id": { "notnull": false }
+ },
+ "indexes": {
+ "unix_cluster_groups_i1": { "columns": [ "unix_cluster_id" ]},
+ "unix_cluster_groups_i2": { "columns": [ "group_id" ]},
+ "unix_cluster_groups_i3": { "columns": [ "person_id" ]}
+ }
+ },
+ "unix_cluster_accounts": {
+ "columns": {
+ "id": {},
+ "unix_cluster_id": { "type": "integer", "foreignkey": { "table": "unix_clusters", "column": "id" }, "notnull": true },
+ "person_id": { "notnull": true },
+ "sync_mode": { "type": "enum" },
+ "status": {},
+ "username": { "size": 32 },
+ "uid": { "type": "integer" },
+ "gecos": { "type": "string", "size": 80 },
+ "login_shell": { "type": "string", "size": 64 },
+ "home_directory": { "type": "path" },
+ "primary_group_id": { "type": "integer", "foreignkey": { "table": "groups", "column": "id" } },
+ "valid_from": {},
+ "valid_through": {}
+ },
+ "indexes": {
+ "unix_cluster_accounts_i1": { "columns": [ "unix_cluster_id" ]},
+ "unix_cluster_accounts_i2": { "columns": [ "person_id" ]},
+ "unix_cluster_accounts_i3": { "columns": [ "unix_cluster_id", "username" ]},
+ "unix_cluster_accounts_i4": { "columns": [ "unix_cluster_id", "uid" ]},
+ "unix_cluster_accounts_i5": { "columns": [ "primary_group_id" ]}
+ }
+ }
+ }
+ }
+}
diff --git a/app/availableplugins/UnixCluster/phpunit.xml.dist b/app/availableplugins/UnixCluster/phpunit.xml.dist
new file mode 100644
index 000000000..7d5be1672
--- /dev/null
+++ b/app/availableplugins/UnixCluster/phpunit.xml.dist
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+ tests/TestCase/
+
+
+
+
+
+
+
+
+
+
+ src/
+
+
+
diff --git a/app/availableplugins/UnixCluster/resources/locales/en_US/unix_cluster.po b/app/availableplugins/UnixCluster/resources/locales/en_US/unix_cluster.po
new file mode 100644
index 000000000..0eb7c3428
--- /dev/null
+++ b/app/availableplugins/UnixCluster/resources/locales/en_US/unix_cluster.po
@@ -0,0 +1,473 @@
+# COmanage Registry Localizations (unix_cluster domain)
+#
+# Portions licensed to the University Corporation for Advanced Internet
+# Development, Inc. ("UCAID") under one or more contributor license agreements.
+# See the NOTICE file distributed with this work for additional information
+# regarding copyright ownership.
+#
+# UCAID licenses this file to you under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with the
+# License. You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# @link https://www.internet2.edu/comanage COmanage Project
+# @package registry
+# @since COmanage Registry v5.4.0
+# @license Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
+
+msgid "controller.UnixClusterAccounts"
+msgstr "{0,plural,=1{Unix Cluster Account} other{Unix Cluster Accounts}}"
+
+msgid "controller.UnixClusterGroups"
+msgstr "{0,plural,=1{Unix Cluster Group} other{Unix Cluster Groups}}"
+
+msgid "controller.UnixClusters"
+msgstr "{0,plural,=1{Unix Cluster} other{Unix Clusters}}"
+
+msgid "enumeration.DefaultGroupModeEnum.EG"
+msgstr "Use an Existing Group"
+
+msgid "enumeration.DefaultGroupModeEnum.PG"
+msgstr "Create a New Group For Each Account"
+
+msgid "enumeration.UnixClusterAccountStatusEnum.A"
+msgstr "Active"
+
+msgid "enumeration.UnixClusterAccountStatusEnum.D"
+msgstr "Deleted"
+
+msgid "enumeration.UnixClusterAccountStatusEnum.GP"
+msgstr "Grace Period"
+
+msgid "enumeration.UnixClusterAccountStatusEnum.S"
+msgstr "Suspended"
+
+msgid "enumeration.UnixClusterGroupOriginEnum.M"
+msgstr "Manually Linked"
+
+msgid "enumeration.UnixClusterGroupOriginEnum.P"
+msgstr "Personal Group"
+
+msgid "enumeration.UnixClusterSyncModeEnum.F"
+msgstr "Track CO Person Attributes"
+
+msgid "enumeration.UnixClusterSyncModeEnum.M"
+msgstr "Manual"
+
+msgid "enumeration.UnixShellEnum./bin/bash"
+msgstr "/bin/bash"
+
+msgid "enumeration.UnixShellEnum./bin/csh"
+msgstr "/bin/csh"
+
+msgid "enumeration.UnixShellEnum./bin/dash"
+msgstr "/bin/dash"
+
+msgid "enumeration.UnixShellEnum./bin/ksh"
+msgstr "/bin/ksh"
+
+msgid "enumeration.UnixShellEnum./bin/sh"
+msgstr "/bin/sh"
+
+msgid "enumeration.UnixShellEnum./bin/tcsh"
+msgstr "/bin/tcsh"
+
+msgid "enumeration.UnixShellEnum./bin/zsh"
+msgstr "/bin/zsh"
+
+msgid "error.UnixClusterAccounts.delete.group"
+msgstr "This Unix Cluster Account's Primary Group is not an unshared personal Group of its Person, so it cannot be deleted with the Account"
+
+msgid "error.UnixClusterAccounts.sync"
+msgstr "Unix Cluster Account {0} in Unix Cluster {1} was not updated from the Person record: {2}"
+
+msgid "error.UnixClusterAccounts.person_id.required"
+msgstr "Unix Cluster Accounts are added for a specific Person, via Manage on the Person's Cluster Status page"
+
+msgid "error.UnixClusterAccounts.uid.exists"
+msgstr "The UID {0} is already used by another Unix Cluster Account in this Unix Cluster"
+
+msgid "error.UnixClusterAccounts.uid.invalid"
+msgstr "The UID must be a positive integer"
+
+msgid "error.UnixClusterAccounts.username.exists"
+msgstr "The username {0} is already used by another Unix Cluster Account in this Unix Cluster"
+
+msgid "error.UnixClusterAccounts.username.length"
+msgstr "The username {0} is longer than {1} characters"
+
+msgid "error.UnixClusterGroups.already"
+msgstr "The specified Group is already attached to this Unix Cluster"
+
+msgid "error.UnixClusterGroups.default"
+msgstr "This Unix Cluster Group is the Default Group of its Unix Cluster. Select a different Default Group before removing it."
+
+msgid "error.UnixClusterGroups.gid.exists"
+msgstr "The GID {0} is already used by another Group"
+
+msgid "error.UnixClusterGroups.personal"
+msgstr "A personal Unix Cluster Group cannot be changed to a different Group"
+
+msgid "error.UnixClusterGroups.sync"
+msgstr "The personal Group of Unix Cluster Account {0} in Unix Cluster {1} was not fully updated: {2}"
+
+msgid "error.UnixClusters.assign.default_group.mapped"
+msgstr "The Default Group {0} is not a Unix Cluster Group of this Unix Cluster"
+
+msgid "error.UnixClusters.assign.default_group.member"
+msgstr "The Person is not a member of the Default Group {0}"
+
+msgid "error.UnixClusters.assign.default_group.none"
+msgstr "No Default Group is set for this Unix Cluster"
+
+msgid "error.UnixClusters.assign.gid.exists"
+msgstr "A personal Group cannot be created with GID {0}, since it is already used by the Group {1}"
+
+msgid "error.UnixClusters.assign.mode"
+msgstr "No Default Group Mode is set for this Unix Cluster"
+
+msgid "error.UnixClusters.assign.personal_group"
+msgstr "The personal Group could not be created: {0}"
+
+msgid "error.UnixClusters.assign.uid.invalid"
+msgstr "The UID {0} is not a positive integer"
+
+msgid "error.UnixClusters.assign.uid.missing"
+msgstr "The Person has no active Identifier of type {0} to use as the UID"
+
+msgid "error.UnixClusters.assign.username.missing"
+msgstr "The Person has no active Identifier of type {0} to use as the username"
+
+msgid "error.UnixClusters.assign.username.length"
+msgstr "The username {0} is longer than {1} characters, the maximum for a Unix Cluster Account"
+
+msgid "error.UnixClusters.default_group_id.mapped"
+msgstr "The Default Group must first be added as a Unix Cluster Group of this Unix Cluster"
+
+msgid "error.UnixClusters.default_group_id.mode"
+msgstr "A Default Group may only be set when Default Group Mode is \"Use an Existing Group\""
+
+msgid "error.UnixClusters.gecos.name"
+msgstr "Primary Name not found for GECOS field"
+
+msgid "error.UnixClusters.homedir_prefix"
+msgstr "Home Directory Prefix must begin with a slash (/)"
+
+msgid "error.UnixClusters.homedir_subdivisions"
+msgstr "Home Directory Subdivisions must be a non-negative integer"
+
+msgid "error.UnixClusters.type_id"
+msgstr "The selected Type must be an active Identifier Type"
+
+msgid "field.UnixClusterAccounts.gecos"
+msgstr "GECOS"
+
+msgid "field.UnixClusterAccounts.home_directory"
+msgstr "Home Directory"
+
+msgid "field.UnixClusterAccounts.login_shell"
+msgstr "Login Shell"
+
+msgid "field.UnixClusterAccounts.primary_group_id"
+msgstr "Primary Group"
+
+msgid "field.UnixClusterAccounts.status"
+msgstr "Status"
+
+msgid "field.UnixClusterAccounts.sync_mode"
+msgstr "Sync Mode"
+
+msgid "field.UnixClusterAccounts.sync_mode.desc"
+msgstr "How updates to Person attributes used to generate this Account are handled. Copied from the Unix Cluster when the Account is created."
+
+msgid "field.UnixClusterAccounts.uid"
+msgstr "User ID (UID) Number"
+
+msgid "field.UnixClusterAccounts.username"
+msgstr "Username"
+
+msgid "field.UnixClusterAccounts.username.desc"
+msgstr "At most 32 characters. Characters are not checked; short alphanumeric usernames are recommended, although other formats such as user@domain are allowed"
+
+msgid "field.UnixClusterGroups.gid"
+msgstr "GID"
+
+msgid "field.UnixClusterGroups.gid.col"
+msgstr "GID (Identifier of type {0})"
+
+msgid "field.UnixClusterGroups.group_id"
+msgstr "Group"
+
+msgid "field.UnixClusterGroups.group_id.desc"
+msgstr "The Group's Identifiers of the configured Group Name Type and GID Type become the Unix group name and GID"
+
+msgid "field.UnixClusterGroups.groupname"
+msgstr "Group Name"
+
+msgid "field.UnixClusterGroups.groupname.col"
+msgstr "Group Name (Identifier of type {0})"
+
+msgid "field.UnixClusterGroups.members"
+msgstr "CO Group Members"
+
+msgid "field.UnixClusterGroups.origin"
+msgstr "Origin"
+
+msgid "field.UnixClusterGroups.person_id"
+msgstr "Personal Group For"
+
+msgid "field.UnixClusterGroups.usable"
+msgstr "Provisioning Status"
+
+msgid "field.UnixClusters.default_group_id"
+msgstr "Default Group"
+
+msgid "field.UnixClusters.default_group_id.desc"
+msgstr "Unix Cluster Accounts will be placed into this group by default. The Group must first be added as a Unix Cluster Group of this Unix Cluster."
+
+msgid "field.UnixClusters.default_group_mode"
+msgstr "Default Group Mode"
+
+msgid "field.UnixClusters.default_group_mode.desc"
+msgstr "Whether new Unix Cluster Accounts use an existing Unix Cluster Group as their default group, or have a personal Group found or created for each Account"
+
+msgid "field.UnixClusters.default_shell"
+msgstr "Default Login Shell"
+
+msgid "field.UnixClusters.default_shell.desc"
+msgstr "Login shell given to new Unix Cluster Accounts, also used as the default for manually created Accounts"
+
+msgid "field.UnixClusters.gid_type_id"
+msgstr "GID Type"
+
+msgid "field.UnixClusters.gid_type_id.desc"
+msgstr "Group Identifier type used as the numeric Unix GID. Must be a positive integer, a minimum of 1000 is recommended. Clusters that reuse a GID number with different names need different GID Types."
+
+msgid "field.UnixClusters.groupname_type_id"
+msgstr "Group Name Type"
+
+msgid "field.UnixClusters.groupname_type_id.desc"
+msgstr "Group Identifier type used as the Unix group name (this Identifier, not the Group's name, is provisioned)"
+
+msgid "field.UnixClusters.homedir_prefix"
+msgstr "Home Directory Prefix"
+
+msgid "field.UnixClusters.homedir_prefix.desc"
+msgstr "Home directories are constructed as this prefix, a slash, and the username, eg \"/home\" generates \"/home/jsmith\". Home directories are not created by this plugin."
+
+msgid "field.UnixClusters.homedir_subdivisions"
+msgstr "Home Directory Subdivisions"
+
+msgid "field.UnixClusters.homedir_subdivisions.desc"
+msgstr "Subdivide the home directory tree by this many leading characters of the username, eg at level 2 \"/home/j/s/jsmith\""
+
+msgid "field.UnixClusters.sync_mode"
+msgstr "Sync Mode"
+
+msgid "field.UnixClusters.sync_mode.desc"
+msgstr "Whether updates to Person attributes propagate to Unix Cluster Accounts. Copied onto each Account when it is created, so changing this does not affect existing Accounts."
+
+msgid "field.UnixClusters.uid_type_id"
+msgstr "UID Type"
+
+msgid "field.UnixClusters.uid_type_id.desc"
+msgstr "Person Identifier type used as the numeric Unix UID. Must be a positive integer, a minimum of 1000 is recommended (eg: the UID type)."
+
+msgid "field.UnixClusters.username_type_id"
+msgstr "Username Type"
+
+msgid "field.UnixClusters.username_type_id.desc"
+msgstr "Person Identifier type used as the Unix username (eg: the Network ID type). Usernames may be at most 32 characters. Characters are not checked; generating this Identifier with an Identifier Assignment set to AlphaNumeric Only is recommended, although other formats such as user@domain are allowed"
+
+msgid "information.notImplemented"
+msgstr "This functionality is not implemented yet"
+
+msgid "information.UnixClusterAccounts.derivation"
+msgstr "When an Account is created automatically, its username is the Person's {0} Identifier, its UID is the Person's {1} Identifier, its home directory is calculated from the username and the Unix Cluster's Home Directory settings, and its GECOS is the Person's Primary Name. Values entered here are not checked against the Person's Identifiers, so a username or UID assigned manually can later cause the automatic creation of an Account for another Person to fail."
+
+msgid "information.UnixClusterAccounts.gid"
+msgstr "GID {0}"
+
+msgid "information.UnixClusterAccounts.gid.missing"
+msgstr "GID missing"
+
+msgid "information.UnixClusterAccounts.none"
+msgstr "No Unix Cluster Accounts"
+
+msgid "information.UnixClusterAccounts.primary_group.unmapped"
+msgstr "not a Unix Cluster Group of this Unix Cluster"
+
+msgid "information.UnixClusterAccounts.registered"
+msgstr "{0,plural,=1{1 Unix Cluster Account} other{# Unix Cluster Accounts}}: {1}"
+
+msgid "information.UnixClusterAccounts.source.differs"
+msgstr "the Person's {0} Identifier is {1}"
+
+msgid "information.UnixClusterAccounts.source.missing"
+msgstr "the Person has no {0} Identifier"
+
+msgid "information.UnixClusterAccounts.title.person"
+msgstr "Unix Cluster Accounts for {0}"
+
+msgid "information.UnixClusterGroups.accounts"
+msgstr "Account {0}"
+
+msgid "information.UnixClusterGroups.invalid"
+msgstr "not a positive integer"
+
+msgid "information.UnixClusterGroups.missing"
+msgstr "missing"
+
+msgid "information.UnixClusterGroups.name_differs"
+msgstr "Unix group name: {0}. The CO Group name is not used."
+
+msgid "information.UnixClusterGroups.person_missing"
+msgstr "Person not found"
+
+msgid "information.UnixClusterGroups.personal"
+msgstr "This Unix Cluster Group was created automatically as the personal Default Group of a Unix Cluster Account, and its CO Group cannot be changed."
+
+msgid "information.UnixClusterGroups.personal_for"
+msgstr "for {0}"
+
+msgid "information.UnixClusterGroups.unusable"
+msgstr "Not Provisionable"
+
+msgid "information.UnixClusterGroups.usable"
+msgstr "Usable"
+
+msgid "information.UnixClusters.default_group.manage"
+msgstr "Manage Unix Cluster Groups"
+
+msgid "information.UnixClusters.default_group.none"
+msgstr "No Default Group is set. Automatic creation of Unix Cluster Accounts will fail until a Unix Cluster Group is selected as the Default Group."
+
+msgid "information.UnixClusters.derivation.col.attribute"
+msgstr "Attribute"
+
+msgid "information.UnixClusters.derivation.col.example"
+msgstr "Example"
+
+msgid "information.UnixClusters.derivation.col.source"
+msgstr "Derived From"
+
+msgid "information.UnixClusters.derivation.existing"
+msgstr "New Unix Cluster Accounts are placed into the Unix Cluster Group {0}. The Person must be a member of this Group, or automatic creation of the Account will fail."
+
+msgid "information.UnixClusters.derivation.existing.none"
+msgstr "No Default Group is set."
+
+msgid "information.UnixClusters.derivation.gecos"
+msgstr "The Person's Primary Name"
+
+msgid "information.UnixClusters.derivation.gecos.example"
+msgstr "Primary Name"
+
+msgid "information.UnixClusters.derivation.group.intro"
+msgstr "Applies to each CO Group mapped as a Unix Cluster Group. The CO Group's name is not provisioned, only its Identifiers are."
+
+msgid "information.UnixClusters.derivation.group_identifier"
+msgstr "CO Group Identifier of type {0}"
+
+msgid "information.UnixClusters.derivation.home_directory"
+msgstr "Home Directory Prefix {0}, then the first {1} characters of the username as subdirectories, then the username"
+
+msgid "information.UnixClusters.derivation.intro"
+msgstr "This is how the current configuration generates a Unix Cluster Account for a Person with username {0} and UID {1}. Changes take effect once saved."
+
+msgid "information.UnixClusters.derivation.login_shell"
+msgstr "Default Login Shell"
+
+msgid "information.UnixClusters.derivation.person_identifier"
+msgstr "Person Identifier of type {0}"
+
+msgid "information.UnixClusters.derivation.username_limit"
+msgstr "{0} (at most {1} characters)"
+
+msgid "information.UnixClusters.derivation.personal.assign"
+msgstr "The Group found or created is used as the Account's Default Group."
+
+msgid "information.UnixClusters.derivation.personal.create"
+msgstr "If no such CO Group exists, a new CO Group named {0} is created, with the description \"{1}\":"
+
+msgid "information.UnixClusters.derivation.personal.identifier"
+msgstr "Identifier of type {0} with value {1}"
+
+msgid "information.UnixClusters.derivation.personal.lookup"
+msgstr "Look for a CO Group with an Identifier of type {0} and value {1}. This is an Identifier attached to the CO Group, not the name of the CO Group."
+
+msgid "information.UnixClusters.derivation.personal.mapped"
+msgstr "The CO Group is added as a Unix Cluster Group of this Unix Cluster"
+
+msgid "information.UnixClusters.derivation.personal.member"
+msgstr "The Person is added as both a member and an owner of the CO Group"
+
+msgid "information.UnixClusters.derivation.sync_mode"
+msgstr "Copied from this configuration when the Account is created"
+
+msgid "information.UnixClusters.derivation.notice"
+msgstr "Want to know where usernames, UIDs, home directories and groups come from?"
+
+msgid "information.UnixClusters.derivation.open"
+msgstr "See how this configuration builds them"
+
+msgid "information.UnixClusters.derivation.title"
+msgstr "How Values Are Derived"
+
+msgid "information.UnixClusters.derivation.unset"
+msgstr "not configured"
+
+msgid "information.UnixClusters.unconfigured"
+msgstr "This Unix Cluster has not been configured"
+
+msgid "information.UnixClusters.gid_space"
+msgstr "Personal Groups use the Account's UID as their GID. GIDs for other Groups should be assigned in a different numeric range, or automatic GID assignment will fail when a GID is already in use."
+
+msgid "information.UnixClusters.header.account"
+msgstr "Account Attributes"
+
+msgid "information.UnixClusters.header.default_group"
+msgstr "Default Group"
+
+msgid "information.UnixClusters.header.group"
+msgstr "Group Attributes"
+
+msgid "information.UnixClusters.personal_group.desc"
+msgstr "Group created for {0} automatically by Unix Cluster {1}"
+
+msgid "information.UnixClusters.personal_group.name"
+msgstr "{0} UnixCluster Group"
+
+msgid "operation.UnixClusterAccounts.delete.group"
+msgstr "Delete with Personal Group"
+
+msgid "operation.UnixClusterAccounts.delete.group.confirm"
+msgstr "Are you sure you wish to delete the Unix Cluster Account {0} together with its personal Group {1}? The Group and its memberships are deleted as well."
+
+msgid "result.UnixClusterAccounts.added"
+msgstr "Unix Cluster Account {0} (UID {1}) added in Unix Cluster {2}"
+
+msgid "result.UnixClusterAccounts.assigned"
+msgstr "Unix Cluster Account {0} (UID {1}) created in Unix Cluster {2}"
+
+msgid "result.UnixClusterAccounts.deleted"
+msgstr "Unix Cluster Account {0} (UID {1}) deleted from Unix Cluster {2}"
+
+msgid "result.UnixClusterAccounts.deleted.group"
+msgstr "Unix Cluster Account {0} and its personal Group deleted"
+
+msgid "result.UnixClusterAccounts.edited"
+msgstr "Unix Cluster Account {0} (UID {1}) edited in Unix Cluster {2}"
+
+msgid "result.UnixClusterAccounts.synced"
+msgstr "Unix Cluster Account {0} in Unix Cluster {1} updated from the Person record ({2})"
+
+msgid "result.UnixClusterGroups.synced"
+msgstr "Personal Group of Unix Cluster Account {0} in Unix Cluster {1} updated from the Person record ({2})"
diff --git a/app/availableplugins/UnixCluster/src/Controller/AppController.php b/app/availableplugins/UnixCluster/src/Controller/AppController.php
new file mode 100644
index 000000000..f2e7ff3f9
--- /dev/null
+++ b/app/availableplugins/UnixCluster/src/Controller/AppController.php
@@ -0,0 +1,10 @@
+ [
+ 'UnixClusterAccounts.username' => 'asc'
+ ]
+ ];
+
+ // The Person of an Account being deleted, since StandardController::delete()
+ // does not pass the deleted entity to calculateRedirectTarget()
+ protected ?int $redirectPersonId = null;
+
+ /**
+ * Callback run prior to the request action.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EventInterface $event Cake Event
+ * @return Response|void|null
+ */
+
+ public function beforeFilter(EventInterface $event) {
+ $action = $this->request->getParam('action');
+
+ if($action == 'add'
+ && $this->request->is('get')
+ && empty($this->request->getQuery('person_id'))) {
+ // Accounts belong to a Person, so they are added from the Person's Accounts
+ // (as linked from the Cluster Status page)
+ $this->Flash->error(__d('unix_cluster', 'error.UnixClusterAccounts.person_id.required'));
+
+ return $this->redirect([
+ 'action' => 'index',
+ '?' => ['unix_cluster_id' => $this->request->getQuery('unix_cluster_id')]
+ ]);
+ }
+
+ if($action == 'delete' || $action == 'deleteWithGroup') {
+ $id = $this->request->getParam('pass')[0] ?? null;
+
+ if(!empty($id)) {
+ $account = $this->UnixClusterAccounts->find()
+ ->where(['UnixClusterAccounts.id' => (int)$id])
+ ->first();
+
+ $this->redirectPersonId = !empty($account->person_id) ? (int)$account->person_id : null;
+ }
+ }
+
+ return parent::beforeFilter($event);
+ }
+
+ /**
+ * Callback run prior to the request render.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EventInterface $event Cake Event
+ * @return Response|void|null
+ */
+
+ public function beforeRender(EventInterface $event) {
+ $link = $this->getPrimaryLink(true);
+
+ if(!empty($link->value)) {
+ $unixClusterId = (int)$link->value;
+
+ // The parent Unix Cluster (configuration) provides the supertitle and breadcrumb.
+ // It also carries the configured Types, which are needed to show where each
+ // Account attribute is derived from.
+ $unixCluster = $this->UnixClusterAccounts->UnixClusters->get(
+ $unixClusterId,
+ contain: ['Clusters', 'UsernameTypes', 'UidTypes', 'GidTypes']
+ );
+
+ $this->set('vv_bc_parent_obj', $unixCluster);
+ $this->set('vv_bc_parent_displayfield', $this->UnixClusterAccounts->UnixClusters->getDisplayField());
+ $this->set('vv_bc_parent_primarykey', $this->UnixClusterAccounts->UnixClusters->getPrimaryKey());
+
+ $this->set('vv_unix_cluster', $unixCluster);
+
+ // Only Groups mapped to this Unix Cluster may be an Account's Primary Group
+ $this->set('primaryGroups', $this->UnixClusterAccounts->UnixClusters->mappedGroups($unixClusterId));
+
+ $action = $this->request->getParam('action');
+ $personId = null;
+
+ if($action == 'add') {
+ $personId = $this->request->getQuery('person_id') ?? $this->request->getData('person_id');
+ } elseif($action == 'index') {
+ $personId = $this->request->getQuery('person_id');
+ } else {
+ $personId = $this->viewBuilder()->getVar('vv_obj')?->person_id;
+ }
+
+ if(in_array($action, ['edit', 'view'], true)) {
+ // Offer to delete the personal Group together with the Account, where permitted
+ $obj = $this->viewBuilder()->getVar('vv_obj');
+
+ if(!empty($obj->id)) {
+ $groupId = $this->UnixClusterAccounts->deletablePersonalGroupId($obj);
+
+ if($groupId !== null) {
+ $this->set('vv_personal_group', $this->UnixClusterAccounts->PrimaryGroups->get($groupId));
+ }
+ }
+ }
+
+ $person = !empty($personId) ? $this->lookupPerson($unixCluster, (int)$personId) : null;
+
+ if(!empty($person)) {
+ $selectedPerson = [
+ 'id' => $person->id,
+ 'name' => $person->primary_name->full_name ?? (string)$person->id
+ ];
+
+ $this->set('vv_selected_person', $selectedPerson);
+
+ if($action == 'index') {
+ $this->set('vv_title', __d('unix_cluster', 'information.UnixClusterAccounts.title.person', [$selectedPerson['name']]));
+ }
+ }
+ }
+
+ return parent::beforeRender($event);
+ }
+
+ /**
+ * Calculate the redirect target after an Account is saved or deleted, which
+ * is the Unix Cluster's Accounts for the same Person.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param object|null $entity Account that was saved, or null after a delete
+ * @return array Redirect
+ */
+
+ public function calculateRedirectTarget($entity): array {
+ $query = [
+ 'unix_cluster_id' => $entity->unix_cluster_id ?? $this->getPrimaryLink(true)->value
+ ];
+
+ $personId = $entity->person_id ?? $this->redirectPersonId;
+
+ if(!empty($personId)) {
+ $query['person_id'] = $personId;
+ }
+
+ return [
+ 'plugin' => 'UnixCluster',
+ 'controller' => 'UnixClusterAccounts',
+ 'action' => 'index',
+ '?' => $query
+ ];
+ }
+
+ /**
+ * Delete an Account together with its personal Group. The Group is deleted via
+ * GroupsTable, so its Unix Cluster Group mapping is removed as well. Only a
+ * Group that UnixClusterAccountsTable::deletablePersonalGroupId() permits is
+ * deleted, a manually mapped or shared Group never is.
+ *
+ * TODO: Once PR-475 (CO-3032) is merged, the LDAP entry of the deleted Group is
+ * removed even though its DN mapping was already soft deleted by the cascade,
+ * and provisioning the deleted Group also reprovisions its former members.
+ * Check then whether the explicit Person provisioning below (via the Account)
+ * is still needed, since the Person would otherwise be provisioned twice.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param string $id Unix Cluster Account ID
+ * @return Response Redirect
+ */
+
+ public function deleteWithGroup(string $id) {
+ $this->request->allowMethod(['post', 'delete']);
+
+ $account = $this->UnixClusterAccounts->get((int)$id);
+
+ $groupId = $this->UnixClusterAccounts->deletablePersonalGroupId($account);
+
+ if($groupId === null) {
+ $this->Flash->error(__d('unix_cluster', 'error.UnixClusterAccounts.delete.group'));
+
+ return $this->redirect(['action' => 'edit', $account->id]);
+ }
+
+ $Groups = $this->UnixClusterAccounts->PrimaryGroups;
+
+ $cxn = $this->UnixClusterAccounts->getConnection();
+ $cxn->begin();
+
+ try {
+ $this->UnixClusterAccounts->deleteOrFail($account);
+ $Groups->deleteOrFail($Groups->get($groupId));
+
+ $cxn->commit();
+ }
+ catch(\Exception $e) {
+ $cxn->rollback();
+
+ $this->Flash->error($e->getMessage());
+
+ return $this->redirect(['action' => 'edit', $account->id]);
+ }
+
+ // Provision the Person (whose provisioning data no longer includes the
+ // Account) and the deleted Group
+ $this->UnixClusterAccounts->requestProvisioning(id: (int)$account->id, context: ProvisioningContextEnum::Automatic);
+ $Groups->requestProvisioning(id: $groupId, context: ProvisioningContextEnum::Automatic);
+
+ $this->Flash->success(__d('unix_cluster', 'result.UnixClusterAccounts.deleted.group', [$account->username]));
+
+ return $this->redirect($this->calculateRedirectTarget(null));
+ }
+
+ /**
+ * Perform controller initialization.
+ *
+ * @since COmanage Registry v5.4.0
+ */
+
+ public function initialize(): void {
+ parent::initialize();
+
+ // Build breadcrumb chain from query context: ?unix_cluster_id=...
+ $this->Breadcrumb->configureQueryPrimaryLinks([
+ 'index' => ['unix_cluster_id']
+ ]);
+ }
+
+ /**
+ * Obtain a Person in the Unix Cluster's CO, with Primary Name.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration, with Cluster
+ * @param int $personId Person ID
+ * @return Person|null Person, or null if not found in the CO
+ */
+
+ protected function lookupPerson(UnixCluster $unixCluster, int $personId): ?Person {
+ return $this->UnixClusterAccounts->People->find()
+ ->where([
+ 'People.id' => $personId,
+ 'People.co_id' => $unixCluster->cluster->co_id
+ ])
+ ->contain(['PrimaryName'])
+ ->first();
+ }
+}
diff --git a/app/availableplugins/UnixCluster/src/Controller/UnixClusterGroupsController.php b/app/availableplugins/UnixCluster/src/Controller/UnixClusterGroupsController.php
new file mode 100644
index 000000000..0a1946a84
--- /dev/null
+++ b/app/availableplugins/UnixCluster/src/Controller/UnixClusterGroupsController.php
@@ -0,0 +1,115 @@
+ [
+ 'UnixClusterGroups.id' => 'asc'
+ ]
+ ];
+
+ /**
+ * Perform controller initialization.
+ *
+ * @since COmanage Registry v5.4.0
+ */
+
+ public function initialize(): void {
+ parent::initialize();
+
+ // Build breadcrumb chain from query context: ?unix_cluster_id=...
+ $this->Breadcrumb->configureQueryPrimaryLinks([
+ 'index' => ['unix_cluster_id']
+ ]);
+ }
+
+ /**
+ * Callback run prior to the request render.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EventInterface $event Cake Event
+ * @return Response|void|null
+ */
+
+ public function beforeRender(EventInterface $event) {
+ $link = $this->getPrimaryLink(true);
+
+ if(!empty($link->value)) {
+ $unixClusterId = (int)$link->value;
+
+ // The parent Unix Cluster (configuration) provides the supertitle and breadcrumb.
+ // It also carries the configured Types, which are needed to derive the Group
+ // Name and GID of each Unix Cluster Group from its CO Group's Identifiers.
+ $unixCluster = $this->UnixClusterGroups->UnixClusters->get(
+ $unixClusterId,
+ contain: ['Clusters', 'GroupnameTypes', 'GidTypes', 'DefaultGroups']
+ );
+
+ $this->set('vv_bc_parent_obj', $unixCluster);
+ $this->set('vv_bc_parent_displayfield', $this->UnixClusterGroups->UnixClusters->getDisplayField());
+ $this->set('vv_bc_parent_primarykey', $this->UnixClusterGroups->UnixClusters->getPrimaryKey());
+
+ $this->set('vv_unix_cluster', $unixCluster);
+
+ $action = $this->request->getParam('action');
+
+ if($action == 'index') {
+ $this->set('vv_member_counts', $this->UnixClusterGroups->memberCounts($unixClusterId));
+
+ // Personal Groups link to the Accounts of the Person they were created for
+ $this->set('vv_personal_accounts', $this->UnixClusterGroups->UnixClusters->UnixClusterAccounts->accountsByPerson($unixClusterId));
+
+ // The CO Group filter offers only the Groups mapped to this Unix Cluster
+ $this->set('groups', $this->UnixClusterGroups->UnixClusters->mappedGroups($unixClusterId));
+ } elseif(in_array($action, ['add', 'edit', 'view'], true)) {
+ // Only Groups not already mapped to this Unix Cluster may be selected,
+ // other than (when editing or viewing) the Group currently mapped
+ $currentGroupId = null;
+
+ if($action != 'add') {
+ $id = $this->request->getParam('pass')[0] ?? null;
+
+ if(!empty($id)) {
+ $currentGroupId = (int)$this->UnixClusterGroups->get((int)$id)->group_id;
+ }
+ }
+
+ $this->set('groups', $this->UnixClusterGroups->availableGroups($unixClusterId, $currentGroupId));
+ }
+ }
+
+ return parent::beforeRender($event);
+ }
+}
diff --git a/app/availableplugins/UnixCluster/src/Controller/UnixClustersController.php b/app/availableplugins/UnixCluster/src/Controller/UnixClustersController.php
new file mode 100644
index 000000000..f0004e2a1
--- /dev/null
+++ b/app/availableplugins/UnixCluster/src/Controller/UnixClustersController.php
@@ -0,0 +1,122 @@
+ [
+ 'UnixClusters.id' => 'asc'
+ ]
+ ];
+
+ /**
+ * Perform controller initialization.
+ *
+ * @since COmanage Registry v5.4.0
+ */
+
+ public function initialize(): void {
+ parent::initialize();
+
+ // Don't inject an automatic "index" breadcrumb for the configuration pages.
+ // We want: ... > Clusters > Configure Unix Cluster
+ $this->Breadcrumb->skipParents([
+ '/^\/unix-cluster\/unix-clusters\/(edit|view)\//'
+ ]);
+ }
+
+ /**
+ * Callback run prior to the request render.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EventInterface $event Cake Event
+ * @return Response|void|null
+ */
+
+ public function beforeRender(EventInterface $event) {
+ // The parent Cluster provides the supertitle and breadcrumb for the configuration pages
+ $link = $this->getPrimaryLink(true);
+
+ if(!empty($link->value)) {
+ $this->set('vv_bc_parent_obj', $this->UnixClusters->Clusters->get($link->value));
+ $this->set('vv_bc_parent_displayfield', $this->UnixClusters->Clusters->getDisplayField());
+ $this->set('vv_bc_parent_primarykey', $this->UnixClusters->Clusters->getPrimaryKey());
+ }
+
+ $id = $this->request->getParam('pass')[0] ?? null;
+
+ if(!empty($id)
+ && in_array($this->request->getParam('action'), ['edit', 'view'], true)) {
+ // Only Groups already mapped to this Unix Cluster may be the Default Group
+ $this->set('defaultGroups', $this->UnixClusters->mappedGroups((int)$id));
+
+ // The derivation summary describes the saved configuration (and not, eg,
+ // a submission that failed validation), and is only available once the
+ // configuration has been saved at least once
+ $unixCluster = $this->UnixClusters->get((int)$id, contain: ['Clusters']);
+
+ if(!empty($unixCluster->default_group_mode)) {
+ $this->set('vv_derivation', $this->UnixClusters->derivationSummary($unixCluster));
+ }
+ }
+
+ return parent::beforeRender($event);
+ }
+
+ /**
+ * Manage a Person's Unix Cluster Accounts, as linked from the Cluster Status page.
+ * Redirects to the Unix Cluster's Accounts, limited to the Person if specified.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param string $id Unix Cluster ID
+ * @return Response|null
+ */
+
+ public function manage(string $id) {
+ $query = ['unix_cluster_id' => (int)$id];
+
+ $personId = $this->request->getQuery('person_id');
+
+ if(!empty($personId)) {
+ $query['person_id'] = (int)$personId;
+ }
+
+ return $this->redirect([
+ 'plugin' => 'UnixCluster',
+ 'controller' => 'UnixClusterAccounts',
+ 'action' => 'index',
+ '?' => $query
+ ]);
+ }
+}
diff --git a/app/availableplugins/UnixCluster/src/Lib/Enum/DefaultGroupModeEnum.php b/app/availableplugins/UnixCluster/src/Lib/Enum/DefaultGroupModeEnum.php
new file mode 100644
index 000000000..a095ab321
--- /dev/null
+++ b/app/availableplugins/UnixCluster/src/Lib/Enum/DefaultGroupModeEnum.php
@@ -0,0 +1,39 @@
+ 'syncAccounts'
+ ];
+ }
+
+ /**
+ * Update a Person's Unix Cluster Accounts after an Identifier or Primary Name
+ * is saved, and reprovision Unix Cluster Groups after a Person status change.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EventInterface $event Model.afterSave event
+ * @param EntityInterface $entity Saved entity
+ * @param ArrayObject $options Save options
+ */
+
+ public function syncAccounts(EventInterface $event, EntityInterface $entity, ArrayObject $options): void {
+ // ChangelogBehavior saves the archive copy with archive=false
+ if(isset($options['archive']) && $options['archive'] === false) {
+ return;
+ }
+
+ $source = $event->getSubject()->getRegistryAlias();
+
+ if($source == 'People') {
+ if(empty($entity->id) || !$entity->isDirty('status')) {
+ return;
+ }
+
+ $Accounts = TableRegistry::getTableLocator()->get('UnixCluster.UnixClusterAccounts');
+ $unixClusterIds = $Accounts->find()
+ ->select(['unix_cluster_id'])
+ ->where(['person_id' => $entity->id])
+ ->all()
+ ->extract('unix_cluster_id')
+ ->toList();
+
+ if(empty($unixClusterIds)) {
+ return;
+ }
+
+ $UnixClusterGroups = TableRegistry::getTableLocator()->get('UnixCluster.UnixClusterGroups');
+
+ foreach(array_unique($unixClusterIds) as $unixClusterId) {
+ $UnixClusterGroups->requestMemberGroupsProvisioning((int)$unixClusterId, (int)$entity->id);
+ }
+
+ return;
+ }
+
+ if(!in_array($source, ['Identifiers', 'Names'], true)) {
+ return;
+ }
+
+ // Only current, active attributes of a Person are tracked (not those of an
+ // External Identity or Group, and not archive copies or deleted records)
+ $parentFk = ($source == 'Identifiers') ? 'identifier_id' : 'name_id';
+
+ if(empty($entity->person_id)
+ || !empty($entity->deleted)
+ || !empty($entity->$parentFk)) {
+ return;
+ }
+
+ if($source == 'Names' && !$entity->primary_name) {
+ return;
+ }
+
+ if($source == 'Identifiers' && $entity->status != SuspendableStatusEnum::Active) {
+ return;
+ }
+
+ TableRegistry::getTableLocator()
+ ->get('UnixCluster.UnixClusterAccounts')
+ ->syncFromPerson($source, $entity);
+ }
+}
diff --git a/app/availableplugins/UnixCluster/src/Lib/Traits/DerivationSummaryTrait.php b/app/availableplugins/UnixCluster/src/Lib/Traits/DerivationSummaryTrait.php
new file mode 100644
index 000000000..ffdce7a32
--- /dev/null
+++ b/app/availableplugins/UnixCluster/src/Lib/Traits/DerivationSummaryTrait.php
@@ -0,0 +1,280 @@
+lookupTypeNames($unixCluster);
+
+ return [
+ 'sample' => [
+ 'username' => $sampleUser,
+ 'uid' => $sampleUid
+ ],
+ 'account' => $this->deriveAccountAttributes($unixCluster, $typeNames, $sampleUser, $sampleUid),
+ 'group' => $this->deriveGroupAttributes($typeNames),
+ 'default_group' => $this->deriveDefaultGroup($unixCluster, $typeNames, $sampleUser, $sampleUid),
+ // Localization keys (unix_cluster domain) for warnings that apply to this configuration
+ 'warnings' => $this->derivationWarnings($unixCluster)
+ ];
+ }
+
+ /**
+ * Determine the warnings (as unix_cluster localization keys) that apply to a
+ * Unix Cluster configuration.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @return array Array of localization keys
+ */
+
+ protected function derivationWarnings(UnixCluster $unixCluster): array {
+ return match($unixCluster->default_group_mode ?? null) {
+ DefaultGroupModeEnum::Existing => empty($unixCluster->default_group_id)
+ ? ['information.UnixClusters.default_group.none']
+ : [],
+ DefaultGroupModeEnum::Personal => ['information.UnixClusters.gid_space'],
+ default => []
+ };
+ }
+
+ /**
+ * Describe how Unix Cluster Account attributes are derived.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param array $typeNames Type display names, keyed on type field
+ * @param string $sampleUser Sample username
+ * @param int $sampleUid Sample UID
+ * @return array Account attribute derivation
+ */
+
+ protected function deriveAccountAttributes(
+ UnixCluster $unixCluster,
+ array $typeNames,
+ string $sampleUser,
+ int $sampleUid
+ ): array {
+ return [
+ 'sync_mode' => [
+ 'value' => $unixCluster->sync_mode ?? null,
+ 'label' => !empty($unixCluster->sync_mode)
+ ? UnixClusterSyncModeEnum::getLocalization($unixCluster->sync_mode)
+ : null
+ ],
+ 'username' => [
+ 'type' => $typeNames['username_type_id'],
+ 'example' => $sampleUser
+ ],
+ 'uid' => [
+ 'type' => $typeNames['uid_type_id'],
+ 'example' => $sampleUid
+ ],
+ 'home_directory' => [
+ 'prefix' => $unixCluster->homedir_prefix ?? null,
+ 'subdivisions' => (int)($unixCluster->homedir_subdivisions ?? 0),
+ 'example' => !empty($unixCluster->homedir_prefix)
+ ? $this->UnixClusterAccounts->calculateHomeDirectory($unixCluster, $sampleUser)
+ : null
+ ],
+ 'login_shell' => [
+ 'example' => $unixCluster->default_shell ?? null
+ ],
+ // GECOS is always populated from the Person's Primary Name
+ 'gecos' => [
+ 'source' => 'PrimaryName'
+ ]
+ ];
+ }
+
+ /**
+ * Describe how the Default Group of a Unix Cluster Account is determined.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param array $typeNames Type display names, keyed on type field
+ * @param string $sampleUser Sample username
+ * @param int $sampleUid Sample UID
+ * @return array Default Group derivation
+ */
+
+ protected function deriveDefaultGroup(
+ UnixCluster $unixCluster,
+ array $typeNames,
+ string $sampleUser,
+ int $sampleUid
+ ): array {
+ $mode = $unixCluster->default_group_mode ?? null;
+
+ return [
+ 'mode' => $mode,
+ 'label' => !empty($mode) ? DefaultGroupModeEnum::getLocalization($mode) : null,
+ 'group' => $mode == DefaultGroupModeEnum::Existing
+ ? $this->deriveExistingGroup($unixCluster)
+ : null,
+ 'personal' => $mode == DefaultGroupModeEnum::Personal
+ ? $this->derivePersonalGroup($unixCluster, $typeNames, $sampleUser, $sampleUid)
+ : null
+ ];
+ }
+
+ /**
+ * Describe the configured Default Group, in Existing Group mode.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @return array|null Default Group id and name, or null if not set
+ */
+
+ protected function deriveExistingGroup(UnixCluster $unixCluster): ?array {
+ if(empty($unixCluster->default_group_id)) {
+ return null;
+ }
+
+ $group = $this->DefaultGroups->find()
+ ->where(['DefaultGroups.id' => $unixCluster->default_group_id])
+ ->first();
+
+ return [
+ 'id' => (int)$unixCluster->default_group_id,
+ 'name' => $group->name ?? null
+ ];
+ }
+
+ /**
+ * Describe how Unix Cluster Group attributes are derived.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param array $typeNames Type display names, keyed on type field
+ * @return array Group attribute derivation
+ */
+
+ protected function deriveGroupAttributes(array $typeNames): array {
+ return [
+ 'groupname' => [
+ 'type' => $typeNames['groupname_type_id']
+ ],
+ 'gid' => [
+ 'type' => $typeNames['gid_type_id']
+ ]
+ ];
+ }
+
+ /**
+ * Describe the recipe used to find or create a personal Default Group, in
+ * Personal Group mode. A new Group is only created when no Group with a
+ * matching Group Name Identifier already exists.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param array $typeNames Type display names, keyed on type field
+ * @param string $sampleUser Sample username
+ * @param int $sampleUid Sample UID
+ * @return array Personal Group recipe
+ */
+
+ protected function derivePersonalGroup(
+ UnixCluster $unixCluster,
+ array $typeNames,
+ string $sampleUser,
+ int $sampleUid
+ ): array {
+ $clusterDescription = $this->lookupClusterDescription($unixCluster);
+
+ return [
+ 'lookup' => [
+ 'type' => $typeNames['groupname_type_id'],
+ 'value' => $sampleUser
+ ],
+ 'name' => __d('unix_cluster', 'information.UnixClusters.personal_group.name', [$sampleUser]),
+ 'description' => __d('unix_cluster', 'information.UnixClusters.personal_group.desc', [$sampleUser, $clusterDescription]),
+ 'identifiers' => [
+ [
+ 'type' => $typeNames['groupname_type_id'],
+ 'value' => $sampleUser
+ ],
+ [
+ 'type' => $typeNames['gid_type_id'],
+ 'value' => (string)$sampleUid
+ ]
+ ],
+ 'member' => true,
+ 'owner' => true
+ ];
+ }
+}
diff --git a/app/availableplugins/UnixCluster/src/Model/Entity/UnixCluster.php b/app/availableplugins/UnixCluster/src/Model/Entity/UnixCluster.php
new file mode 100644
index 000000000..e0e477062
--- /dev/null
+++ b/app/availableplugins/UnixCluster/src/Model/Entity/UnixCluster.php
@@ -0,0 +1,42 @@
+ true,
+ 'id' => false,
+ 'slug' => false,
+ ];
+}
diff --git a/app/availableplugins/UnixCluster/src/Model/Entity/UnixClusterAccount.php b/app/availableplugins/UnixCluster/src/Model/Entity/UnixClusterAccount.php
new file mode 100644
index 000000000..a9aa8ba0c
--- /dev/null
+++ b/app/availableplugins/UnixCluster/src/Model/Entity/UnixClusterAccount.php
@@ -0,0 +1,42 @@
+ true,
+ 'id' => false,
+ 'slug' => false,
+ ];
+}
diff --git a/app/availableplugins/UnixCluster/src/Model/Entity/UnixClusterGroup.php b/app/availableplugins/UnixCluster/src/Model/Entity/UnixClusterGroup.php
new file mode 100644
index 000000000..6b09ee5fe
--- /dev/null
+++ b/app/availableplugins/UnixCluster/src/Model/Entity/UnixClusterGroup.php
@@ -0,0 +1,42 @@
+ true,
+ 'id' => false,
+ 'slug' => false,
+ ];
+}
diff --git a/app/availableplugins/UnixCluster/src/Model/Table/UnixClusterAccountsTable.php b/app/availableplugins/UnixCluster/src/Model/Table/UnixClusterAccountsTable.php
new file mode 100644
index 000000000..9bed7f390
--- /dev/null
+++ b/app/availableplugins/UnixCluster/src/Model/Table/UnixClusterAccountsTable.php
@@ -0,0 +1,1038 @@
+addBehavior('Changelog');
+ $this->addBehavior('Log');
+ $this->addBehavior('Timestamp');
+
+ // Accounts are attached to a Person, like other Person attributes
+ $this->setTableType(\App\Lib\Enum\TableTypeEnum::Secondary);
+
+ // Define associations
+ $this->belongsTo('UnixCluster.UnixClusters');
+ $this->belongsTo('People');
+ $this->belongsTo('PrimaryGroups')
+ ->setClassName('Groups')
+ ->setForeignKey('primary_group_id')
+ ->setProperty('primary_group');
+
+ $this->setDisplayField('username');
+
+ $this->setPrimaryLink(['UnixCluster.unix_cluster_id']);
+ // deleteWithGroup is a POST without the primary link in its body, so the
+ // Unix Cluster is looked up via the Account ID
+ $this->setAllowLookupPrimaryLink(['deleteWithGroup']);
+ $this->setRequiresCO(true);
+ // Return to the Unix Cluster's Accounts for the same Person, see
+ // UnixClusterAccountsController::calculateRedirectTarget()
+ $this->setRedirectGoal('special');
+
+ $this->setAutoViewVars([
+ 'statuses' => [
+ 'type' => 'enum',
+ 'class' => 'UnixCluster.UnixClusterAccountStatusEnum'
+ ],
+ 'syncModes' => [
+ 'type' => 'enum',
+ 'class' => 'UnixCluster.UnixClusterSyncModeEnum'
+ ],
+ 'loginShells' => [
+ 'type' => 'enum',
+ 'class' => 'UnixCluster.UnixShellEnum'
+ ]
+ ]);
+
+ // The Person's Identifiers and the Primary Group's Identifiers are used to
+ // show where the username, UID and GID are derived from
+ $this->setIndexContains([
+ 'People' => ['PrimaryName', 'Identifiers'],
+ 'PrimaryGroups' => ['Identifiers']
+ ]);
+ $this->setEditContains([
+ 'People' => ['PrimaryName'],
+ 'PrimaryGroups'
+ ]);
+ $this->setViewContains([
+ 'People' => ['PrimaryName'],
+ 'PrimaryGroups'
+ ]);
+
+ // The Unix Cluster's Accounts can be limited to one Person, as linked from
+ // the Cluster Status page (via UnixClustersController::manage()). The primary
+ // link (unix_cluster_id) already limits the index to the Unix Cluster's CO.
+ $this->setIndexFilter(function (\Cake\Http\ServerRequest $r): ?array {
+ $personId = $r->getQuery('person_id');
+
+ if(!empty($personId)) {
+ return ['UnixClusterAccounts.person_id' => (int)$personId];
+ }
+
+ return null;
+ });
+
+ $this->setPermissions([
+ 'ui' => [
+ // Actions that operate over an entity (ie: require an $id)
+ 'entity' => [
+ 'delete' => ['platformAdmin', 'coAdmin'],
+ // Delete the Account together with its personal Group,
+ // see UnixClusterAccountsController::deleteWithGroup()
+ 'deleteWithGroup' => ['platformAdmin', 'coAdmin'],
+ 'edit' => ['platformAdmin', 'coAdmin'],
+ 'view' => ['platformAdmin', 'coAdmin']
+ ],
+ // Actions that operate over a table (ie: do not require an $id)
+ 'table' => [
+ 'add' => ['platformAdmin', 'coAdmin'],
+ 'index' => ['platformAdmin', 'coAdmin']
+ ]
+ ]
+ ]);
+ }
+
+ /**
+ * Callback before data is marshaled into an entity.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EventInterface $event beforeMarshal event
+ * @param ArrayObject $data Entity data
+ * @param ArrayObject $options Callback options
+ */
+
+ public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options) {
+ // New Accounts default to Active. Manually created Accounts apply no derivation
+ // rules, but take their login shell and sync mode from the Unix Cluster if
+ // not otherwise provided.
+ if(!empty($data['id'])) {
+ return;
+ }
+
+ if(empty($data['status'])) {
+ $data['status'] = UnixClusterAccountStatusEnum::Active;
+ }
+
+ if(!empty($data['unix_cluster_id'])
+ && (empty($data['login_shell']) || empty($data['sync_mode']))) {
+ $unixCluster = $this->UnixClusters->find()
+ ->where(['UnixClusters.id' => (int)$data['unix_cluster_id']])
+ ->first();
+
+ if(!empty($unixCluster)) {
+ if(empty($data['login_shell'])) {
+ $data['login_shell'] = $unixCluster->default_shell;
+ }
+
+ if(empty($data['sync_mode'])) {
+ $data['sync_mode'] = $unixCluster->sync_mode;
+ }
+ }
+ }
+ }
+
+ /**
+ * Define business rules.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param RulesChecker $rules RulesChecker object
+ * @return RulesChecker
+ */
+
+ public function buildRules(RulesChecker $rules): RulesChecker {
+ // Usernames and UIDs must be unique within a Unix Cluster
+ $rules->add([$this, 'ruleUniqueInUnixCluster'],
+ 'uniqueUsername',
+ ['errorField' => 'username']);
+
+ $rules->add([$this, 'ruleUniqueInUnixCluster'],
+ 'uniqueUid',
+ ['errorField' => 'uid']);
+
+ return $rules;
+ }
+
+ /**
+ * Obtain the usernames of a Unix Cluster's Accounts, grouped by Person.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $unixClusterId Unix Cluster ID
+ * @param array $personIds If not empty, only return Accounts of these People
+ * @return array Array keyed on Person ID, of arrays of usernames keyed on Account ID
+ */
+
+ public function accountsByPerson(int $unixClusterId, array $personIds=[]): array {
+ $conditions = ['UnixClusterAccounts.unix_cluster_id' => $unixClusterId];
+
+ if(!empty($personIds)) {
+ $conditions['UnixClusterAccounts.person_id IN'] = $personIds;
+ }
+
+ $ret = [];
+
+ $accounts = $this->find()
+ ->select(['id', 'person_id', 'username'])
+ ->where($conditions)
+ ->orderBy(['UnixClusterAccounts.username' => 'ASC'])
+ ->all();
+
+ foreach($accounts as $account) {
+ $ret[$account->person_id][$account->id] = $account->username;
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Calculate the GECOS value for a Unix Cluster Account from a Person's Primary Name.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param Name|null $name Primary Name
+ * @return string GECOS value
+ * @throws \RuntimeException
+ */
+
+ public function calculateGecos(?Name $name): string {
+ $fullName = !empty($name) ? trim((string)$name->full_name) : '';
+
+ if($fullName === '') {
+ throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusters.gecos.name'));
+ }
+
+ // Colons separate passwd fields and control characters are not permitted
+ $gecos = preg_replace('/[:\x00-\x1F\x7F]/u', '', $fullName);
+
+ $maxLength = $this->getSchema()->getColumn('gecos')['length'] ?? 80;
+
+ return mb_substr($gecos, 0, (int)$maxLength);
+ }
+
+ /**
+ * Calculate the home directory for a username, in accordance with the
+ * Unix Cluster configuration.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param string $username Username to use as basis for home directory
+ * @return string Home Directory
+ */
+
+ public function calculateHomeDirectory(UnixCluster $unixCluster, string $username): string {
+ $affix = $username;
+ $subdivisions = (int)($unixCluster->homedir_subdivisions ?? 0);
+
+ if($subdivisions > 0) {
+ $infix = "";
+
+ // Don't fail if the username is shorter than the number of subdivisions
+ $levels = min($subdivisions, mb_strlen($username));
+
+ for($i = 0;$i < $levels;$i++) {
+ $infix .= mb_substr($username, $i, 1) . "/";
+ }
+
+ $affix = $infix . $affix;
+ }
+
+ // Avoid a double slash if the prefix was configured with a trailing slash (or is "/")
+ return rtrim((string)$unixCluster->homedir_prefix, "/") . "/" . $affix;
+ }
+
+ /**
+ * Obtain a Person's Accounts in a Unix Cluster.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $unixClusterId Unix Cluster ID
+ * @param int $personId Person ID
+ * @param array|null $statuses If set, only return Accounts in one of these statuses
+ * @return array Array of Unix Cluster Accounts, with Primary Group and its Identifiers
+ */
+
+ public function findForPerson(int $unixClusterId, int $personId, ?array $statuses=null): array {
+ $conditions = [
+ 'UnixClusterAccounts.unix_cluster_id' => $unixClusterId,
+ 'UnixClusterAccounts.person_id' => $personId
+ ];
+
+ if($statuses !== null) {
+ $conditions['UnixClusterAccounts.status IN'] = $statuses;
+ }
+
+ return $this->find()
+ ->where($conditions)
+ ->contain(['PrimaryGroups' => ['Identifiers']])
+ ->orderBy(['UnixClusterAccounts.username' => 'ASC'])
+ ->all()
+ ->toList();
+ }
+
+ /**
+ * Determine the personal Group that may be deleted together with an Account.
+ * This is the Account's Primary Group, but only if it is mapped to the Account's
+ * Unix Cluster as the personal Group of the Account's Person, and no other
+ * Account (in any Unix Cluster) uses it as its Primary Group. A manually mapped
+ * or shared Group is never returned.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixClusterAccount $account Unix Cluster Account
+ * @return int|null Group ID, or null if there is no such Group
+ */
+
+ public function deletablePersonalGroupId(UnixClusterAccount $account): ?int {
+ if(empty($account->primary_group_id) || empty($account->person_id)) {
+ return null;
+ }
+
+ $UnixClusterGroups = $this->UnixClusters->UnixClusterGroups;
+
+ $isPersonal = $UnixClusterGroups->exists([
+ 'UnixClusterGroups.unix_cluster_id' => $account->unix_cluster_id,
+ 'UnixClusterGroups.group_id' => $account->primary_group_id,
+ 'UnixClusterGroups.origin' => UnixClusterGroupOriginEnum::Personal,
+ 'UnixClusterGroups.person_id' => $account->person_id
+ ]);
+
+ if(!$isPersonal) {
+ return null;
+ }
+
+ $isShared = $this->exists([
+ 'UnixClusterAccounts.primary_group_id' => $account->primary_group_id,
+ 'UnixClusterAccounts.id IS NOT' => $account->id
+ ]);
+
+ return $isShared ? null : (int)$account->primary_group_id;
+ }
+
+ /**
+ * Filter metadata fields. The Unix Cluster foreign key (the primary link) and
+ * the Primary Group foreign key are treated as metadata, and not offered as
+ * index filters.
+ *
+ * @since COmanage Registry v5.4.0
+ * @return array An array of columns distinguished in metadata and non-metadata
+ */
+
+ protected function filterMetadataFields() {
+ $fields = $this->tableMetaFilterMetadataFields();
+
+ foreach(['unix_cluster_id', 'primary_group_id'] as $column) {
+ if(isset($fields[$column])) {
+ $fields['meta'][$column] = $fields[$column];
+ unset($fields[$column]);
+ }
+ }
+
+ return $fields;
+ }
+
+ /**
+ * Generate a display field for the given entity.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EntityInterface $entity Unix Cluster Account entity
+ * @return string|null Display field, or null if not available
+ */
+
+ public function generateDisplayField(EntityInterface $entity): ?string {
+ return !empty($entity->username) ? (string)$entity->username : null;
+ }
+
+ /**
+ * Determine if a username or UID is already in use by an Account in a Unix Cluster.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $unixClusterId Unix Cluster ID
+ * @param string $field Field to check, 'username' or 'uid'
+ * @param string|int $value Value to check for
+ * @param int|null $excludeId ID of an Account to ignore (ie: the Account being updated)
+ * @return bool true if the value is in use, false otherwise
+ */
+
+ public function isInUse(int $unixClusterId, string $field, string|int $value, ?int $excludeId=null): bool {
+ $conditions = [
+ 'UnixClusterAccounts.unix_cluster_id' => $unixClusterId,
+ 'UnixClusterAccounts.' . $field => $value
+ ];
+
+ if(!empty($excludeId)) {
+ $conditions['UnixClusterAccounts.id IS NOT'] = $excludeId;
+ }
+
+ return $this->exists($conditions);
+ }
+
+ /**
+ * Callback after model save. Every add, edit and delete of an Account is
+ * recorded in the Person's history.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EventInterface $event Event
+ * @param EntityInterface $entity Unix Cluster Account
+ * @param ArrayObject $options Save options, optionally with 'historyComment'
+ * @return bool True on success
+ */
+
+ public function localAfterSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): bool {
+ if(!empty($options['historyComment'])) {
+ // The caller (eg: UnixClustersTable::assign()) provides its own comment
+ $this->recordHistory($entity, null, $options['historyComment']);
+
+ return true;
+ }
+
+ $unixCluster = $this->UnixClusters->find()
+ ->where(['UnixClusters.id' => $entity->unix_cluster_id])
+ ->contain(['Clusters'])
+ ->first();
+
+ $clusterName = !empty($unixCluster) ? (string)$this->UnixClusters->lookupClusterDescription($unixCluster) : '';
+
+ $langKey = 'result.UnixClusterAccounts.edited';
+
+ if($entity->isNew()) {
+ $langKey = 'result.UnixClusterAccounts.added';
+ } elseif($entity->deleted) {
+ // ChangelogBehavior turns a delete into an update
+ $langKey = 'result.UnixClusterAccounts.deleted';
+ }
+
+ $comment = __d('unix_cluster', $langKey, [
+ $entity->username,
+ $entity->uid,
+ $clusterName
+ ]);
+
+ if($langKey == 'result.UnixClusterAccounts.edited') {
+ $changes = $this->changesToString($entity);
+
+ if($changes !== '') {
+ $comment .= ' (' . $changes . ')';
+ }
+ }
+
+ $this->recordHistory($entity, null, $comment);
+
+ return true;
+ }
+
+ /**
+ * Request provisioning for an Account. Accounts are provisioned as part of
+ * their Person, so provisioning is requested for the Person instead.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $id Unix Cluster Account ID
+ * @param string $context Context in which provisioning is being requested
+ * @param int|null $provisioningTargetId If set, the Provisioning Target ID to request provisioning for (otherwise all)
+ * @param Job|null $job If called from a Job, the current Job entity
+ * @param array|null $passThroughData Additional data to merge into the marshalled provisioning data
+ */
+
+ public function requestProvisioning(
+ int $id,
+ string $context,
+ ?int $provisioningTargetId=null,
+ ?Job $job=null,
+ ?array $passThroughData=null
+ ): void {
+ // A deleted Account is archived, but still points to its Person
+ $account = $this->find()
+ ->applyOptions(['archived' => true])
+ ->where(['UnixClusterAccounts.id' => $id])
+ ->firstOrFail();
+
+ $this->People->requestProvisioning(
+ id: (int)$account->person_id,
+ context: $context,
+ provisioningTargetId: $provisioningTargetId,
+ job: $job,
+ passThroughData: $passThroughData
+ );
+
+ // The Account's username is a member (eg: memberUid) of the Unix Cluster
+ // Groups its Person belongs to, so those Groups are reprovisioned as well
+ if($provisioningTargetId === null) {
+ $this->UnixClusters->UnixClusterGroups->requestMemberGroupsProvisioning(
+ (int)$account->unix_cluster_id,
+ (int)$account->person_id
+ );
+ }
+ }
+
+ /**
+ * Application Rule to determine if a username or UID is not already in use
+ * by another Account in the same Unix Cluster.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EntityInterface $entity Entity to be validated
+ * @param array $options Application rule options, including 'errorField'
+ * @return string|bool true if the Rule check passes, an error string otherwise
+ */
+
+ public function ruleUniqueInUnixCluster(EntityInterface $entity, array $options): string|bool {
+ $field = $options['errorField'];
+
+ if($entity->$field === null || $entity->$field === '' || !$entity->isDirty($field)) {
+ return true;
+ }
+
+ if($this->isInUse(
+ (int)$entity->unix_cluster_id,
+ $field,
+ $entity->$field,
+ $entity->isNew() ? null : (int)$entity->id
+ )) {
+ return __d('unix_cluster', 'error.UnixClusterAccounts.' . $field . '.exists', [$entity->$field]);
+ }
+
+ return true;
+ }
+
+ /**
+ * Perform a keyword search on the username, GECOS and UID of the Accounts
+ * in the Unix Clusters of a CO.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $coId CO ID to constrain search to
+ * @param string $q String to search for
+ * @param int $limit Search limit
+ * @return iterable Unix Cluster Accounts, with Person (and Primary Name) and Unix Cluster (and Cluster)
+ */
+
+ public function search(int $coId, string $q, int $limit): iterable {
+ $whereClause = [];
+
+ foreach(explode(" ", $q) as $t) {
+ $or = [
+ 'LOWER(UnixClusterAccounts.username) LIKE' => '%' . strtolower($t) . '%',
+ 'LOWER(UnixClusterAccounts.gecos) LIKE' => '%' . strtolower($t) . '%'
+ ];
+
+ // The UID is an integer column, so it is only compared to numeric tokens
+ if(ctype_digit($t)) {
+ $or['UnixClusterAccounts.uid'] = (int)$t;
+ }
+
+ $whereClause['AND'][] = ['OR' => $or];
+ }
+
+ return $this->find()
+ ->where($whereClause)
+ ->andWhere(['Clusters.co_id' => $coId])
+ ->orderBy(['UnixClusterAccounts.username'])
+ ->limit($limit)
+ ->contain([
+ 'People' => ['PrimaryName'],
+ 'UnixClusters' => ['Clusters']
+ ])
+ ->all();
+ }
+
+ /**
+ * Update the Accounts of a Person that track CO Person attributes (Sync Mode
+ * Full, as copied onto the Account when it was created) after a Person
+ * Identifier or the Primary Name was saved. Accounts are updated whatever
+ * their status (except Deleted), see UnixClusterListener.
+ *
+ * - Primary Name: GECOS
+ * - Identifier of the UID Type: UID, and the personal Group's GID Identifier if
+ * it still equals the old UID
+ * - Identifier of the Username Type: username and home directory, and the
+ * personal Group's Group Name Identifier, name and description if they still
+ * equal the values derived from the old username
+ *
+ * Conflicts (eg: the new username or UID is already used in the Unix Cluster,
+ * or the new GID by another Group) are checked before anything is written. A
+ * conflicting update is not applied, and is recorded in the Person's history.
+ * The save that triggered the update is never failed, and no transaction is
+ * opened, since the caller may already be in one.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param string $source Source table, 'Identifiers' or 'Names'
+ * @param EntityInterface $entity Saved Identifier or Name, attached to a Person
+ */
+
+ public function syncFromPerson(string $source, EntityInterface $entity): void {
+ $accounts = $this->find()
+ ->where([
+ 'UnixClusterAccounts.person_id' => (int)$entity->person_id,
+ 'UnixClusterAccounts.sync_mode' => UnixClusterSyncModeEnum::Full,
+ 'UnixClusterAccounts.status IS NOT' => UnixClusterAccountStatusEnum::Deleted
+ ])
+ ->contain([
+ 'UnixClusters' => ['Clusters'],
+ 'PrimaryGroups' => ['Identifiers']
+ ])
+ ->all();
+
+ foreach($accounts as $account) {
+ try {
+ $this->syncAccount($account, $source, $entity);
+ }
+ catch(\Exception $e) {
+ // Never fail the save of the Person attribute
+ $this->llog('error', 'Unix Cluster Account ' . $account->id . ' sync failed: ' . $e->getMessage());
+ }
+ }
+ }
+
+ /**
+ * Calculate and apply the updates of one Account (and its personal Group), see
+ * syncFromPerson().
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixClusterAccount $account Account, with Unix Cluster (and Cluster) and Primary Group (and Identifiers)
+ * @param string $source Source table, 'Identifiers' or 'Names'
+ * @param EntityInterface $entity Saved Identifier or Name
+ */
+
+ protected function syncAccount(UnixClusterAccount $account, string $source, EntityInterface $entity): void {
+ $unixCluster = $account->unix_cluster;
+
+ if(empty($unixCluster)) {
+ return;
+ }
+
+ $clusterName = (string)$this->UnixClusters->lookupClusterDescription($unixCluster);
+
+ // Account field => new value
+ $changes = [];
+ $conflicts = [];
+
+ if($source == 'Names') {
+ try {
+ $gecos = $this->calculateGecos($entity instanceof Name ? $entity : null);
+ }
+ catch(\RuntimeException $e) {
+ return;
+ }
+
+ if($gecos !== (string)$account->gecos) {
+ $changes['gecos'] = $gecos;
+ }
+ } else {
+ $value = trim((string)$entity->identifier);
+
+ if($value !== '' && $entity->type_id == $unixCluster->uid_type_id && $value !== (string)$account->uid) {
+ if(!Validation::naturalNumber($value)) {
+ $conflicts[] = __d('unix_cluster', 'error.UnixClusterAccounts.uid.invalid');
+ } elseif($this->isInUse((int)$unixCluster->id, 'uid', (int)$value, (int)$account->id)) {
+ $conflicts[] = __d('unix_cluster', 'error.UnixClusterAccounts.uid.exists', [$value]);
+ } else {
+ $changes['uid'] = (int)$value;
+ }
+ }
+
+ if($value !== '' && $entity->type_id == $unixCluster->username_type_id && $value !== (string)$account->username) {
+ if(mb_strlen($value) > $this->usernameMaxLength()) {
+ $conflicts[] = __d('unix_cluster', 'error.UnixClusterAccounts.username.length', [$value, $this->usernameMaxLength()]);
+ } elseif($this->isInUse((int)$unixCluster->id, 'username', $value, (int)$account->id)) {
+ $conflicts[] = __d('unix_cluster', 'error.UnixClusterAccounts.username.exists', [$value]);
+ } else {
+ $changes['username'] = $value;
+ $changes['home_directory'] = $this->calculateHomeDirectory($unixCluster, $value);
+ }
+ }
+ }
+
+ if(empty($changes) && empty($conflicts)) {
+ return;
+ }
+
+ // The personal Group is only updated where it still reflects the old values
+ $groupPlan = empty($conflicts)
+ ? $this->planPersonalGroupSync($account, $changes, $clusterName, $conflicts)
+ : null;
+
+ if(!empty($conflicts)) {
+ // Nothing is written, so there are no partial updates
+ $this->recordSyncHistory($account, ActionEnum::MVEAEdited, __d('unix_cluster', 'error.UnixClusterAccounts.sync', [
+ $account->username,
+ $clusterName,
+ implode(', ', $conflicts)
+ ]));
+
+ return;
+ }
+
+ $old = [];
+
+ foreach(array_keys($changes) as $field) {
+ $old[$field] = $account->$field;
+ }
+
+ $this->patchEntity($account, $changes, ['validate' => false]);
+
+ $summary = [];
+
+ foreach($changes as $field => $new) {
+ $summary[] = $field . ': ' . $old[$field] . ' > ' . $new;
+ }
+
+ if(!$this->save($account, [
+ // Don't also save the contained Unix Cluster and Primary Group
+ 'associated' => false,
+ 'historyComment' => __d('unix_cluster', 'result.UnixClusterAccounts.synced', [
+ $account->username,
+ $clusterName,
+ implode('; ', $summary)
+ ])
+ ])) {
+ $errors = [];
+
+ foreach($account->getErrors() as $field => $fieldErrors) {
+ $errors[] = $field . ': ' . implode(', ', $fieldErrors);
+ }
+
+ $this->recordSyncHistory($account, ActionEnum::MVEAEdited, __d('unix_cluster', 'error.UnixClusterAccounts.sync', [
+ $old['username'] ?? $account->username,
+ $clusterName,
+ implode('; ', $errors)
+ ]));
+
+ return;
+ }
+
+ if(!empty($groupPlan)) {
+ $this->applyPersonalGroupSync($account, $groupPlan, $clusterName);
+ }
+
+ if(isset($changes['username'])) {
+ // The username is a member (eg: memberUid) of the Person's Unix Cluster Groups
+ $this->UnixClusters->UnixClusterGroups->requestMemberGroupsProvisioning(
+ (int)$unixCluster->id,
+ (int)$account->person_id
+ );
+ }
+ }
+
+ /**
+ * Determine the updates to the personal Group of an Account. The Account's
+ * Primary Group must be mapped to the Unix Cluster as the personal Group of the
+ * Account's Person. Each value is only updated if it still equals the value
+ * derived from the old UID or username. A new GID already used by another Group
+ * is added to $conflicts.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixClusterAccount $account Account, before the changes are applied
+ * @param array $changes Account changes, keyed on field
+ * @param string $clusterName Cluster description
+ * @param array $conflicts Conflicts, added to by reference
+ * @return array|null Planned updates, or null if there are none
+ */
+
+ protected function planPersonalGroupSync(
+ UnixClusterAccount $account,
+ array $changes,
+ string $clusterName,
+ array &$conflicts
+ ): ?array {
+ $group = $account->primary_group ?? null;
+ $unixCluster = $account->unix_cluster;
+
+ if(empty($group)
+ || (!isset($changes['uid']) && !isset($changes['username']))
+ || !$this->UnixClusters->UnixClusterGroups->exists([
+ 'UnixClusterGroups.unix_cluster_id' => $unixCluster->id,
+ 'UnixClusterGroups.group_id' => $group->id,
+ 'UnixClusterGroups.origin' => UnixClusterGroupOriginEnum::Personal,
+ 'UnixClusterGroups.person_id' => $account->person_id
+ ])) {
+ return null;
+ }
+
+ $plan = ['identifiers' => [], 'group' => []];
+
+ foreach($group->identifiers ?? [] as $identifier) {
+ if($identifier->status != SuspendableStatusEnum::Active) {
+ continue;
+ }
+
+ if(isset($changes['uid'])
+ && $identifier->type_id == $unixCluster->gid_type_id
+ && (string)$identifier->identifier === (string)$account->uid) {
+ $newGid = (string)$changes['uid'];
+
+ if($this->PrimaryGroups->Identifiers->exists([
+ 'Identifiers.type_id' => $unixCluster->gid_type_id,
+ 'Identifiers.identifier' => $newGid,
+ 'Identifiers.group_id IS NOT' => null,
+ 'Identifiers.id IS NOT' => $identifier->id
+ ])) {
+ $conflicts[] = __d('unix_cluster', 'error.UnixClusterGroups.gid.exists', [$newGid]);
+ } else {
+ $plan['identifiers'][] = [$identifier, $newGid];
+ }
+ }
+
+ if(isset($changes['username'])
+ && $identifier->type_id == $unixCluster->groupname_type_id
+ && (string)$identifier->identifier === (string)$account->username) {
+ $plan['identifiers'][] = [$identifier, (string)$changes['username']];
+ }
+ }
+
+ if(isset($changes['username'])) {
+ $oldName = __d('unix_cluster', 'information.UnixClusters.personal_group.name', [$account->username]);
+ $oldDesc = __d('unix_cluster', 'information.UnixClusters.personal_group.desc', [$account->username, $clusterName]);
+
+ if($group->name === $oldName) {
+ $plan['group']['name'] = __d('unix_cluster', 'information.UnixClusters.personal_group.name', [$changes['username']]);
+ }
+
+ if($group->description === $oldDesc) {
+ $plan['group']['description'] = __d('unix_cluster', 'information.UnixClusters.personal_group.desc', [$changes['username'], $clusterName]);
+ }
+ }
+
+ return (empty($plan['identifiers']) && empty($plan['group'])) ? null : $plan;
+ }
+
+ /**
+ * Apply the planned updates to the personal Group of an Account, record them in
+ * the Group's history, and request provisioning for the Group.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixClusterAccount $account Account, with Primary Group
+ * @param array $plan Planned updates, see planPersonalGroupSync()
+ * @param string $clusterName Cluster description
+ */
+
+ protected function applyPersonalGroupSync(UnixClusterAccount $account, array $plan, string $clusterName): void {
+ $group = $account->primary_group;
+ $Identifiers = $this->PrimaryGroups->Identifiers;
+
+ $summary = [];
+ $errors = [];
+
+ foreach($plan['identifiers'] as [$identifier, $newValue]) {
+ $oldValue = $identifier->identifier;
+
+ $identifier = $Identifiers->patchEntity($identifier, ['identifier' => $newValue]);
+
+ if($Identifiers->save($identifier)) {
+ $summary[] = $oldValue . ' > ' . $newValue;
+ } else {
+ $errors[] = $oldValue . ' > ' . $newValue;
+ }
+ }
+
+ if(!empty($plan['group'])) {
+ $Groups = $this->PrimaryGroups->getTarget();
+
+ $groupEntity = $Groups->get($group->id);
+ $old = $groupEntity->extract(array_keys($plan['group']));
+
+ $groupEntity = $Groups->patchEntity($groupEntity, $plan['group']);
+
+ $entries = [];
+
+ foreach($plan['group'] as $field => $newValue) {
+ $entries[] = $field . ': ' . $old[$field] . ' > ' . $newValue;
+ }
+
+ if($Groups->save($groupEntity)) {
+ $summary = array_merge($summary, $entries);
+ } else {
+ $errors = array_merge($errors, $entries);
+ }
+ }
+
+ $HistoryRecords = TableRegistry::getTableLocator()->get('HistoryRecords');
+
+ if(!empty($summary)) {
+ $HistoryRecords->recordForGroup(
+ (int)$group->id,
+ ActionEnum::GroupEdited,
+ __d('unix_cluster', 'result.UnixClusterGroups.synced', [$account->username, $clusterName, implode('; ', $summary)]),
+ (int)$account->person_id
+ );
+ }
+
+ if(!empty($errors)) {
+ $this->llog('error', 'Personal Group ' . $group->id . ' sync failed: ' . implode('; ', $errors));
+
+ $HistoryRecords->recordForGroup(
+ (int)$group->id,
+ ActionEnum::GroupEdited,
+ __d('unix_cluster', 'error.UnixClusterGroups.sync', [$account->username, $clusterName, implode('; ', $errors)]),
+ (int)$account->person_id
+ );
+ }
+
+ try {
+ $this->PrimaryGroups->requestProvisioning(id: (int)$group->id, context: ProvisioningContextEnum::Automatic);
+ }
+ catch(\Exception $e) {
+ $this->llog('error', 'Provisioning failed for Group ' . $group->id . ': ' . $e->getMessage());
+ }
+ }
+
+ /**
+ * Record a sync result in the history of an Account's Person.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixClusterAccount $account Account
+ * @param string $action ActionEnum
+ * @param string $comment Comment
+ */
+
+ protected function recordSyncHistory(UnixClusterAccount $account, string $action, string $comment): void {
+ $this->llog('info', $comment);
+
+ TableRegistry::getTableLocator()->get('HistoryRecords')->recordForPerson(
+ (int)$account->person_id,
+ $action,
+ $comment
+ );
+ }
+
+ /**
+ * Obtain the maximum length of a Unix Cluster Account username.
+ *
+ * @since COmanage Registry v5.4.0
+ * @return int Maximum length, from the username column definition
+ */
+
+ public function usernameMaxLength(): int {
+ return (int)($this->getSchema()->getColumn('username')['length'] ?? 32);
+ }
+
+ /**
+ * Set validation rules.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param Validator $validator Validator
+ * @return Validator Validator
+ */
+
+ public function validationDefault(Validator $validator): Validator {
+ $schema = $this->getSchema();
+
+ $validator->add('unix_cluster_id', [
+ 'content' => ['rule' => 'isInteger']
+ ]);
+ $validator->notEmptyString('unix_cluster_id');
+
+ $validator->add('person_id', [
+ 'content' => ['rule' => 'isInteger']
+ ]);
+ $validator->notEmptyString('person_id');
+
+ $validator->add('sync_mode', [
+ 'content' => ['rule' => ['inList', UnixClusterSyncModeEnum::getConstValues()]]
+ ]);
+ $validator->notEmptyString('sync_mode');
+
+ $validator->add('status', [
+ 'content' => ['rule' => ['inList', UnixClusterAccountStatusEnum::getConstValues()]]
+ ]);
+ $validator->notEmptyString('status');
+
+ $this->registerStringValidation($validator, $schema, 'username', true);
+
+ $validator->add('uid', [
+ 'content' => [
+ 'rule' => ['naturalNumber', false],
+ 'message' => __d('unix_cluster', 'error.UnixClusterAccounts.uid.invalid')
+ ]
+ ]);
+ $validator->notEmptyString('uid');
+
+ $this->registerStringValidation($validator, $schema, 'gecos', false);
+
+ $validator->add('login_shell', [
+ 'content' => ['rule' => ['inList', UnixShellEnum::getConstValues()]]
+ ]);
+ $validator->notEmptyString('login_shell');
+
+ $this->registerStringValidation($validator, $schema, 'home_directory', true);
+
+ $validator->add('primary_group_id', [
+ 'content' => ['rule' => 'isInteger']
+ ]);
+ $validator->allowEmptyString('primary_group_id');
+
+ $validator->add('valid_from', [
+ 'content' => ['rule' => 'dateTime']
+ ]);
+ $validator->allowEmptyString('valid_from');
+
+ $validator->add('valid_through', [
+ 'content' => ['rule' => 'dateTime']
+ ]);
+ $validator->allowEmptyString('valid_through');
+
+ return $validator;
+ }
+}
diff --git a/app/availableplugins/UnixCluster/src/Model/Table/UnixClusterGroupsTable.php b/app/availableplugins/UnixCluster/src/Model/Table/UnixClusterGroupsTable.php
new file mode 100644
index 000000000..f2e6583b9
--- /dev/null
+++ b/app/availableplugins/UnixCluster/src/Model/Table/UnixClusterGroupsTable.php
@@ -0,0 +1,809 @@
+addBehavior('Changelog');
+ $this->addBehavior('Log');
+ $this->addBehavior('Timestamp');
+
+ $this->setTableType(\App\Lib\Enum\TableTypeEnum::Configuration);
+
+ // Define associations
+ $this->belongsTo('UnixCluster.UnixClusters');
+ $this->belongsTo('Groups');
+ $this->belongsTo('People');
+
+ $this->setDisplayField('id');
+
+ $this->setPrimaryLink(['UnixCluster.unix_cluster_id']);
+ $this->setRequiresCO(true);
+
+ $this->setAutoViewVars([
+ 'origins' => [
+ 'type' => 'enum',
+ 'class' => 'UnixCluster.UnixClusterGroupOriginEnum'
+ ]
+ // groups is set by the controller, since only Groups not already
+ // mapped to the current Unix Cluster may be selected
+ ]);
+
+ // The index derives Group Name and GID from the Group's Identifiers, and
+ // names the Person a personal Group was created for
+ $this->setIndexContains([
+ 'Groups' => ['Identifiers'],
+ 'People' => ['PrimaryName']
+ ]);
+ $this->setEditContains(['Groups']);
+ $this->setViewContains([
+ 'Groups' => ['Identifiers'],
+ 'People' => ['PrimaryName']
+ ]);
+
+ // The index can be filtered on the CO Group, in addition to the table's own
+ // columns (eg: origin). group_id is a metadata field, so it is listed here to
+ // be offered as a filter. It is an exact match on the column, and it is
+ // rendered as a select of the Unix Cluster's mapped Groups, which the
+ // controller sets as the groups view var.
+ $this->setFilterConfig([
+ 'group_id' => [
+ 'type' => 'select',
+ 'model' => null,
+ 'active' => true,
+ 'order' => 1
+ ]
+ ]);
+
+ $this->setPermissions([
+ 'ui' => [
+ // Actions that operate over an entity (ie: require an $id)
+ 'entity' => [
+ 'delete' => ['platformAdmin', 'coAdmin'],
+ 'edit' => ['platformAdmin', 'coAdmin'],
+ 'view' => ['platformAdmin', 'coAdmin']
+ ],
+ // Actions that operate over a table (ie: do not require an $id)
+ 'table' => [
+ 'add' => ['platformAdmin', 'coAdmin'],
+ 'index' => ['platformAdmin', 'coAdmin']
+ ]
+ ]
+ ]);
+ }
+
+ /**
+ * Add the derived values provisioners need to a Unix Cluster Group, so that
+ * they don't have to know the Unix Cluster configuration: group_name (the
+ * Group Name Identifier), gid_number (the GID Identifier), scope (the Unix
+ * Cluster's label, see UnixClustersTable::provisioningScope()), cluster_id (the
+ * core Cluster ID), and, if given, member_uids (the usernames of the Accounts
+ * of the CO Group's members).
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixClusterGroup $unixClusterGroup Unix Cluster Group, with Group and Group Identifiers
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param string $scope Unix Cluster label
+ * @param array|null $memberUids Usernames of the members, or null to not set member_uids
+ * @return UnixClusterGroup Unix Cluster Group, with the derived values set
+ */
+
+ public function annotateForProvisioning(
+ UnixClusterGroup $unixClusterGroup,
+ UnixCluster $unixCluster,
+ string $scope,
+ ?array $memberUids=null
+ ): UnixClusterGroup {
+ $d = $this->describeGroup($unixClusterGroup, $unixCluster);
+
+ $unixClusterGroup->set('group_name', $d['groupname']);
+ $unixClusterGroup->set('gid_number', $d['gid']);
+ $unixClusterGroup->set('scope', $scope);
+ $unixClusterGroup->set('cluster_id', $unixCluster->cluster_id);
+
+ if($memberUids !== null) {
+ $unixClusterGroup->set('member_uids', $memberUids);
+ }
+
+ return $unixClusterGroup;
+ }
+
+ /**
+ * Obtain the Groups that may be mapped to a Unix Cluster, ie active Groups in
+ * the same CO that are not already mapped to it.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $unixClusterId Unix Cluster ID
+ * @param int|null $includeGroupId Group ID to include even though it is mapped (eg: when editing)
+ * @return array Array of Group names, keyed on Group ID
+ */
+
+ public function availableGroups(int $unixClusterId, ?int $includeGroupId=null): array {
+ $unixCluster = $this->UnixClusters->get($unixClusterId, contain: ['Clusters']);
+
+ $mapped = $this->mappedGroupIds($unixClusterId);
+
+ if(!empty($includeGroupId)) {
+ $mapped->where(['UnixClusterGroups.group_id IS NOT' => $includeGroupId]);
+ }
+
+ return $this->Groups->find('list', keyField: 'id', valueField: 'name')
+ ->where([
+ 'Groups.co_id' => $unixCluster->cluster->co_id,
+ 'Groups.status' => SuspendableStatusEnum::Active,
+ 'Groups.id NOT IN' => $mapped
+ ])
+ ->orderBy(['Groups.name' => 'ASC'])
+ ->toArray();
+ }
+
+ /**
+ * Callback before data is marshaled into an entity.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EventInterface $event beforeMarshal event
+ * @param ArrayObject $data Entity data
+ * @param ArrayObject $options Callback options
+ */
+
+ public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options) {
+ // Origin and the Person a personal Group belongs to are set by the plugin
+ // itself (via the 'trustedOrigin' option), never by a submitted form
+ if(empty($options['trustedOrigin'])) {
+ unset($data['origin'], $data['person_id']);
+ }
+ }
+
+ /**
+ * Callback before an entity is saved.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EventInterface $event beforeSave event
+ * @param EntityInterface $entity Entity to be saved
+ * @param ArrayObject $options Callback options
+ */
+
+ public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options) {
+ // Anything not explicitly created as a personal Group was linked manually
+ if($entity->isNew() && empty($entity->origin)) {
+ $entity->origin = UnixClusterGroupOriginEnum::Manual;
+ }
+ }
+
+ /**
+ * Define business rules.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param RulesChecker $rules RulesChecker object
+ * @return RulesChecker
+ */
+
+ public function buildRules(RulesChecker $rules): RulesChecker {
+ $rules->add($rules->isUnique(
+ ['unix_cluster_id', 'group_id'],
+ __d('unix_cluster', 'error.UnixClusterGroups.already')
+ ),
+ 'uniqueGroupPerUnixCluster',
+ ['errorField' => 'group_id']);
+
+ $rules->add([$this, 'rulePersonalGroupUnchanged'],
+ 'personalGroupUnchanged',
+ ['errorField' => 'group_id']);
+
+ $rules->addDelete([$this, 'ruleNotDefaultGroup'],
+ 'notDefaultGroup',
+ ['errorField' => 'group_id']);
+
+ return $rules;
+ }
+
+ /**
+ * Create a personal Group for a Person: the Group itself, its Group Name and GID
+ * Identifiers, the Person's membership and ownership, and its mapping as a
+ * Unix Cluster Group. The caller is expected to manage the transaction.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param Person $person Person the Group is created for
+ * @param string $username Username, used as the Group Name Identifier
+ * @param string $uid UID, used as the GID Identifier
+ * @return int ID of the new Group
+ * @throws \RuntimeException
+ */
+
+ protected function createPersonalGroup(
+ UnixCluster $unixCluster,
+ Person $person,
+ string $username,
+ string $uid
+ ): int {
+ $Groups = $this->Groups->getTarget();
+
+ $group = $Groups->newEntity([
+ 'co_id' => $person->co_id,
+ 'cou_id' => null,
+ 'name' => __d('unix_cluster', 'information.UnixClusters.personal_group.name', [$username]),
+ 'description' => __d('unix_cluster', 'information.UnixClusters.personal_group.desc', [
+ $username,
+ $this->UnixClusters->lookupClusterDescription($unixCluster)
+ ]),
+ 'open' => false,
+ 'status' => SuspendableStatusEnum::Active,
+ 'group_type' => GroupTypeEnum::Standard
+ ]);
+
+ // Saving a new Group also creates its Owners Group
+ $Groups->saveOrFail($group);
+
+ foreach([
+ [$unixCluster->groupname_type_id, $username],
+ [$unixCluster->gid_type_id, $uid]
+ ] as [$typeId, $value]) {
+ $identifier = $Groups->Identifiers->newEntity([
+ 'group_id' => $group->id,
+ 'identifier' => $value,
+ 'type_id' => $typeId,
+ 'login' => false,
+ 'status' => SuspendableStatusEnum::Active
+ ]);
+
+ $Groups->Identifiers->saveOrFail($identifier);
+ }
+
+ // The Person is a member of the Group, and an owner via its Owners Group
+ foreach(array_filter([$group->id, $group->owners_group_id]) as $memberGroupId) {
+ $membership = $Groups->GroupMembers->newEntity([
+ 'group_id' => $memberGroupId,
+ 'person_id' => $person->id
+ ]);
+
+ $Groups->GroupMembers->saveOrFail($membership);
+ }
+
+ $this->mapPersonalGroup($unixCluster, $group->id, $person->id);
+
+ return $group->id;
+ }
+
+ /**
+ * Describe how the Unix attributes of a Unix Cluster Group are derived from
+ * its CO Group, in accordance with the Unix Cluster configuration.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixClusterGroup $unixClusterGroup Unix Cluster Group, with Group and Group Identifiers
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @return array Derived attributes and their status
+ */
+
+ public function describeGroup(UnixClusterGroup $unixClusterGroup, UnixCluster $unixCluster): array {
+ $group = $unixClusterGroup->group ?? null;
+
+ $groupname = $this->groupIdentifierValue($group->identifiers ?? [], $unixCluster->groupname_type_id);
+ $gid = $this->groupIdentifierValue($group->identifiers ?? [], $unixCluster->gid_type_id);
+ // A GID must be a positive integer
+ $gidValid = ($gid !== null && Validation::naturalNumber($gid));
+
+ return [
+ 'groupname' => $groupname,
+ 'gid' => $gid,
+ 'gid_valid' => $gidValid,
+ // A Unix Cluster Group can only be provisioned when both Identifiers are available
+ 'usable' => ($groupname !== null && $gidValid),
+ // The Group Name Identifier, not the CO Group name, is what gets provisioned
+ 'name_differs' => ($groupname !== null && !empty($group->name) && $groupname !== $group->name)
+ ];
+ }
+
+ /**
+ * Find the Group with an active Identifier of the given type and value.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $typeId Identifier Type ID
+ * @param string $identifier Identifier value
+ * @return int|null Group ID, or null if not found
+ */
+
+ protected function findGroupByIdentifier(int $typeId, string $identifier): ?int {
+ try {
+ return $this->Groups->Identifiers->lookupGroup($typeId, $identifier);
+ }
+ catch(RecordNotFoundException $e) {
+ return null;
+ }
+ }
+
+ /**
+ * Find or create the personal Group to use as the Default Group of a new Account.
+ * A Group with an Identifier of the Group Name Type matching the username is used
+ * if one exists (and mapped to the Unix Cluster if it isn't already), otherwise a
+ * new Group is created. The caller is expected to manage the transaction.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param Person $person Person
+ * @param string $username Username of the new Account
+ * @param string $uid UID of the new Account
+ * @return array Array of 'group_id' and 'created' (true if a new Group was created)
+ * @throws \RuntimeException
+ */
+
+ public function findOrCreatePersonalGroup(
+ UnixCluster $unixCluster,
+ Person $person,
+ string $username,
+ string $uid
+ ): array {
+ $groupId = $this->findGroupByIdentifier($unixCluster->groupname_type_id, $username);
+
+ if(!empty($groupId)) {
+ // Make sure the existing Group is available to this Unix Cluster
+ if(!$this->isMapped($unixCluster->id, $groupId)) {
+ $this->mapPersonalGroup($unixCluster, $groupId, $person->id);
+ }
+
+ return ['group_id' => $groupId, 'created' => false];
+ }
+
+ // The new Group's GID is the Account's UID, so it must not already be in use
+ $gidGroupId = $this->findGroupByIdentifier($unixCluster->gid_type_id, $uid);
+
+ if(!empty($gidGroupId)) {
+ $gidGroup = $this->Groups->get($gidGroupId);
+
+ throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusters.assign.gid.exists', [$uid, $gidGroup->name]));
+ }
+
+ try {
+ $groupId = $this->createPersonalGroup($unixCluster, $person, $username, $uid);
+ }
+ catch(\Exception $e) {
+ throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusters.assign.personal_group', [$e->getMessage()]));
+ }
+
+ return ['group_id' => $groupId, 'created' => true];
+ }
+
+ /**
+ * Generate a display field for the given entity, using the CO Group's name.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EntityInterface $entity Unix Cluster Group entity
+ * @return string|null Display field, or null if not available
+ */
+
+ public function generateDisplayField(EntityInterface $entity): ?string {
+ if(!empty($entity->group->name)) {
+ return (string)$entity->group->name;
+ }
+
+ if(!empty($entity->group_id)) {
+ $group = $this->Groups->find()->where(['Groups.id' => $entity->group_id])->first();
+
+ return $group->name ?? null;
+ }
+
+ return null;
+ }
+
+ /**
+ * Obtain the value of the active Identifier of the given type.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param iterable $identifiers Identifiers to search
+ * @param int|null $typeId Identifier Type ID
+ * @return string|null Identifier value, or null if not found
+ */
+
+ public function groupIdentifierValue(iterable $identifiers, ?int $typeId): ?string {
+ if(empty($typeId)) {
+ return null;
+ }
+
+ foreach($identifiers as $identifier) {
+ if($identifier->type_id == $typeId
+ && $identifier->status == SuspendableStatusEnum::Active
+ && $identifier->identifier !== null
+ && $identifier->identifier !== '') {
+ return (string)$identifier->identifier;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Filter metadata fields. The Unix Cluster foreign key is the primary link, so
+ * it is treated as metadata and not offered as an index filter.
+ *
+ * @since COmanage Registry v5.4.0
+ * @return array An array of columns distinguished in metadata and non-metadata
+ */
+
+ protected function filterMetadataFields() {
+ $fields = $this->tableMetaFilterMetadataFields();
+
+ if(isset($fields['unix_cluster_id'])) {
+ $fields['meta']['unix_cluster_id'] = $fields['unix_cluster_id'];
+ unset($fields['unix_cluster_id']);
+ }
+
+ return $fields;
+ }
+
+ /**
+ * Determine if a Group is mapped as a Unix Cluster Group of a Unix Cluster.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $unixClusterId Unix Cluster ID
+ * @param int $groupId Group ID
+ * @return bool true if the Group is mapped, false otherwise
+ */
+
+ public function isMapped(int $unixClusterId, int $groupId): bool {
+ return $this->exists([
+ 'UnixClusterGroups.unix_cluster_id' => $unixClusterId,
+ 'UnixClusterGroups.group_id' => $groupId
+ ]);
+ }
+
+ /**
+ * Marshal a Unix Cluster Group for provisioning its CO Group. Only an active,
+ * usable CO Group is provisioned. The usernames of the Active or Grace Period
+ * Accounts (in this Unix Cluster) of valid members whose People are Active or
+ * in Grace Period are set as member_uids.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param int $groupId Group ID
+ * @param string $scope Unix Cluster label
+ * @return UnixClusterGroup|null Annotated Unix Cluster Group, or null if the Group is not provisioned
+ */
+
+ public function marshalGroup(UnixCluster $unixCluster, int $groupId, string $scope): ?UnixClusterGroup {
+ $unixClusterGroup = $this->find()
+ ->where([
+ 'UnixClusterGroups.unix_cluster_id' => $unixCluster->id,
+ 'UnixClusterGroups.group_id' => $groupId
+ ])
+ ->contain(['Groups' => ['Identifiers']])
+ ->first();
+
+ if(empty($unixClusterGroup)
+ || empty($unixClusterGroup->group)
+ || $unixClusterGroup->group->status != SuspendableStatusEnum::Active
+ || !$this->describeGroup($unixClusterGroup, $unixCluster)['usable']) {
+ return null;
+ }
+
+ $personIds = [];
+
+ foreach($this->Groups->GroupMembers->find()
+ ->where(['GroupMembers.group_id' => $groupId])
+ ->contain(['People'])
+ ->all() as $groupMember) {
+ if($groupMember->isValid()
+ && in_array($groupMember->person->status ?? null, [StatusEnum::Active, StatusEnum::GracePeriod], true)) {
+ $personIds[] = (int)$groupMember->person_id;
+ }
+ }
+
+ $memberUids = [];
+
+ if(!empty($personIds)) {
+ $memberUids = $this->UnixClusters->UnixClusterAccounts->find()
+ ->select(['username'])
+ ->where([
+ 'UnixClusterAccounts.unix_cluster_id' => $unixCluster->id,
+ 'UnixClusterAccounts.person_id IN' => array_unique($personIds),
+ 'UnixClusterAccounts.status IN' => UnixClusterAccountStatusEnum::provisionableStatuses()
+ ])
+ ->orderBy(['UnixClusterAccounts.username' => 'ASC'])
+ ->all()
+ ->extract('username')
+ ->toList();
+ }
+
+ return $this->annotateForProvisioning($unixClusterGroup, $unixCluster, $scope, $memberUids);
+ }
+
+ /**
+ * Map a Group as the personal Unix Cluster Group of a Person.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param int $groupId Group ID
+ * @param int $personId ID of the Person the Group belongs to
+ * @throws \RuntimeException
+ */
+
+ protected function mapPersonalGroup(UnixCluster $unixCluster, int $groupId, int $personId): void {
+ // Origin and Person are only accepted with the trustedOrigin option
+ $unixClusterGroup = $this->newEntity([
+ 'unix_cluster_id' => $unixCluster->id,
+ 'group_id' => $groupId,
+ 'origin' => UnixClusterGroupOriginEnum::Personal,
+ 'person_id' => $personId
+ ], ['trustedOrigin' => true]);
+
+ $this->saveOrFail($unixClusterGroup);
+ }
+
+ /**
+ * Obtain a query for the IDs of the Groups mapped to a Unix Cluster, suitable
+ * for use as a subquery.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $unixClusterId Unix Cluster ID
+ * @return SelectQuery Query selecting group_id
+ */
+
+ public function mappedGroupIds(int $unixClusterId): SelectQuery {
+ return $this->find()
+ ->select(['UnixClusterGroups.group_id'])
+ ->where(['UnixClusterGroups.unix_cluster_id' => $unixClusterId]);
+ }
+
+ /**
+ * Obtain the number of members of each Group mapped to a Unix Cluster.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $unixClusterId Unix Cluster ID
+ * @return array Member counts, keyed on Group ID
+ */
+
+ public function memberCounts(int $unixClusterId): array {
+ $groupIds = $this->mappedGroupIds($unixClusterId);
+
+ $GroupMembers = $this->Groups->GroupMembers;
+
+ $query = $GroupMembers->find();
+
+ return $query->select([
+ 'group_id',
+ 'members' => $query->func()->count('DISTINCT ' . $GroupMembers->aliasField('person_id'))
+ ])
+ ->where([$GroupMembers->aliasField('group_id') . ' IN' => $groupIds])
+ ->groupBy([$GroupMembers->aliasField('group_id')])
+ ->all()
+ ->combine('group_id', 'members')
+ ->toArray();
+ }
+
+ /**
+ * Obtain the Unix Cluster Groups to provision for a Person, ie those mapped to
+ * an active CO Group the Person is a member of, and usable (with both a Group
+ * Name and a valid GID).
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param int $personId Person ID
+ * @return array Array of Unix Cluster Groups, with Group and Group Identifiers
+ */
+
+ public function provisionableGroups(UnixCluster $unixCluster, int $personId): array {
+ $unixClusterGroups = $this->find()
+ ->where(['UnixClusterGroups.unix_cluster_id' => $unixCluster->id])
+ ->contain(['Groups' => ['Identifiers']])
+ ->all();
+
+ $ret = [];
+
+ foreach($unixClusterGroups as $unixClusterGroup) {
+ if(empty($unixClusterGroup->group)
+ || $unixClusterGroup->group->status != SuspendableStatusEnum::Active
+ || !$this->describeGroup($unixClusterGroup, $unixCluster)['usable']
+ || !$this->Groups->GroupMembers->isMember((int)$unixClusterGroup->group_id, $personId)) {
+ continue;
+ }
+
+ $ret[] = $unixClusterGroup;
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Request provisioning for the CO Groups mapped to a Unix Cluster that a Person
+ * is a member of. The usernames of a Person's Accounts are provisioned as Group
+ * members (eg: memberUid), so these Groups need to be reprovisioned when an
+ * Account is added, changed or removed. A failure is logged, but not raised.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $unixClusterId Unix Cluster ID
+ * @param int $personId Person ID
+ */
+
+ public function requestMemberGroupsProvisioning(int $unixClusterId, int $personId): void {
+ $groupIds = $this->find()
+ ->select(['group_id'])
+ ->where(['UnixClusterGroups.unix_cluster_id' => $unixClusterId])
+ ->all()
+ ->extract('group_id')
+ ->toList();
+
+ foreach(array_unique($groupIds) as $groupId) {
+ try {
+ if($this->Groups->GroupMembers->isMember((int)$groupId, $personId)) {
+ $this->Groups->requestProvisioning(id: (int)$groupId, context: ProvisioningContextEnum::Automatic);
+ }
+ }
+ catch(\Exception $e) {
+ $this->llog('error', "Provisioning failed for Group $groupId: " . $e->getMessage());
+ }
+ }
+ }
+
+ /**
+ * Perform a keyword search on the names of the CO Groups mapped to the
+ * Unix Clusters of a CO.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $coId CO ID to constrain search to
+ * @param string $q String to search for
+ * @param int $limit Search limit
+ * @return iterable Unix Cluster Groups, with Group and Unix Cluster (and Cluster)
+ */
+
+ public function search(int $coId, string $q, int $limit): iterable {
+ $whereClause = [];
+
+ foreach(explode(" ", $q) as $t) {
+ $whereClause['AND'][] = [
+ 'LOWER(Groups.name) LIKE' => '%' . strtolower($t) . '%'
+ ];
+ }
+
+ return $this->find()
+ ->where($whereClause)
+ ->andWhere(['Clusters.co_id' => $coId])
+ ->orderBy(['Groups.name'])
+ ->limit($limit)
+ ->contain(['Groups', 'UnixClusters' => ['Clusters']])
+ ->all();
+ }
+
+ /**
+ * Application Rule to prevent removal of the Unix Cluster Group that is
+ * currently used as the Unix Cluster's Default Group. This only applies to
+ * a direct deletion, and not to a deletion cascading from a parent record.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EntityInterface $entity Entity to be deleted
+ * @param array $options Application rule options
+ * @return string|bool true if the Rule check passes, an error string otherwise
+ */
+
+ public function ruleNotDefaultGroup(EntityInterface $entity, array $options): string|bool {
+ if(isset($options['_primary']) && $options['_primary'] === false) {
+ return true;
+ }
+
+ if($this->UnixClusters->exists([
+ 'UnixClusters.id' => $entity->unix_cluster_id,
+ 'UnixClusters.default_group_id' => $entity->group_id
+ ])) {
+ return __d('unix_cluster', 'error.UnixClusterGroups.default');
+ }
+
+ return true;
+ }
+
+ /**
+ * Application Rule to prevent a personal Unix Cluster Group from being
+ * pointed at a different CO Group, since it was created for a specific Person.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EntityInterface $entity Entity to be validated
+ * @param array $options Application rule options
+ * @return string|bool true if the Rule check passes, an error string otherwise
+ */
+
+ public function rulePersonalGroupUnchanged(EntityInterface $entity, array $options): string|bool {
+ if(!$entity->isNew()
+ && $entity->isDirty('group_id')
+ && $entity->getOriginal('origin') == UnixClusterGroupOriginEnum::Personal) {
+ return __d('unix_cluster', 'error.UnixClusterGroups.personal');
+ }
+
+ return true;
+ }
+
+ /**
+ * Set validation rules.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param Validator $validator Validator
+ * @return Validator Validator
+ */
+
+ public function validationDefault(Validator $validator): Validator {
+ $validator->add('unix_cluster_id', [
+ 'content' => ['rule' => 'isInteger']
+ ]);
+ $validator->notEmptyString('unix_cluster_id');
+
+ $validator->add('group_id', [
+ 'content' => ['rule' => 'isInteger']
+ ]);
+ $validator->notEmptyString('group_id');
+
+ $validator->add('origin', [
+ 'content' => ['rule' => ['inList', UnixClusterGroupOriginEnum::getConstValues()]]
+ ]);
+ $validator->allowEmptyString('origin');
+
+ $validator->add('person_id', [
+ 'content' => ['rule' => 'isInteger']
+ ]);
+ $validator->allowEmptyString('person_id');
+
+ return $validator;
+ }
+}
diff --git a/app/availableplugins/UnixCluster/src/Model/Table/UnixClustersTable.php b/app/availableplugins/UnixCluster/src/Model/Table/UnixClustersTable.php
new file mode 100644
index 000000000..1a43faf07
--- /dev/null
+++ b/app/availableplugins/UnixCluster/src/Model/Table/UnixClustersTable.php
@@ -0,0 +1,1124 @@
+addBehavior('Changelog');
+ $this->addBehavior('Log');
+ $this->addBehavior('Timestamp');
+
+ $this->setTableType(\App\Lib\Enum\TableTypeEnum::Configuration);
+
+ // Define associations
+ $this->belongsTo('Clusters');
+ $this->belongsTo('UsernameTypes')
+ ->setClassName('Types')
+ ->setForeignKey('username_type_id')
+ ->setProperty('username_type');
+ $this->belongsTo('UidTypes')
+ ->setClassName('Types')
+ ->setForeignKey('uid_type_id')
+ ->setProperty('uid_type');
+ $this->belongsTo('GroupnameTypes')
+ ->setClassName('Types')
+ ->setForeignKey('groupname_type_id')
+ ->setProperty('groupname_type');
+ $this->belongsTo('GidTypes')
+ ->setClassName('Types')
+ ->setForeignKey('gid_type_id')
+ ->setProperty('gid_type');
+ $this->belongsTo('DefaultGroups')
+ ->setClassName('Groups')
+ ->setForeignKey('default_group_id')
+ ->setProperty('default_group');
+
+ $this->hasMany('UnixCluster.UnixClusterGroups')
+ ->setDependent(true)
+ ->setForeignKey('unix_cluster_id')
+ ->setCascadeCallbacks(true);
+ $this->hasMany('UnixCluster.UnixClusterAccounts')
+ ->setDependent(true)
+ ->setForeignKey('unix_cluster_id')
+ ->setCascadeCallbacks(true);
+
+ // Relations from the perspective of Core models, so that Types and Groups
+ // in use by a Unix Cluster (or as the Primary Group of an Account) are
+ // protected, Unix Cluster Groups are removed along with their CO Group (or
+ // the Person they were created for), and Accounts are removed along with
+ // their Person.
+ $this->hasManyPlugins([
+ 'Types' => [
+ [
+ 'alias' => 'UnixClusterUsernameTypes',
+ 'targetModel' => 'UnixCluster.UnixClusters',
+ 'config' => [
+ 'foreignKey' => 'username_type_id'
+ ]
+ ],
+ [
+ 'alias' => 'UnixClusterUidTypes',
+ 'targetModel' => 'UnixCluster.UnixClusters',
+ 'config' => [
+ 'foreignKey' => 'uid_type_id'
+ ]
+ ],
+ [
+ 'alias' => 'UnixClusterGroupnameTypes',
+ 'targetModel' => 'UnixCluster.UnixClusters',
+ 'config' => [
+ 'foreignKey' => 'groupname_type_id'
+ ]
+ ],
+ [
+ 'alias' => 'UnixClusterGidTypes',
+ 'targetModel' => 'UnixCluster.UnixClusters',
+ 'config' => [
+ 'foreignKey' => 'gid_type_id'
+ ]
+ ]
+ ],
+ 'Groups' => [
+ [
+ 'alias' => 'UnixClusterDefaultGroups',
+ 'targetModel' => 'UnixCluster.UnixClusters',
+ 'config' => [
+ 'foreignKey' => 'default_group_id'
+ ]
+ ],
+ [
+ 'targetModel' => 'UnixCluster.UnixClusterGroups',
+ 'config' => [
+ 'dependent' => true,
+ 'cascadeCallbacks' => true
+ ]
+ ],
+ [
+ 'alias' => 'UnixClusterAccountPrimaryGroups',
+ 'targetModel' => 'UnixCluster.UnixClusterAccounts',
+ 'config' => [
+ 'foreignKey' => 'primary_group_id'
+ ]
+ ]
+ ],
+ 'People' => [
+ [
+ 'targetModel' => 'UnixCluster.UnixClusterGroups',
+ 'config' => [
+ 'dependent' => true,
+ 'cascadeCallbacks' => true
+ ]
+ ],
+ [
+ 'targetModel' => 'UnixCluster.UnixClusterAccounts',
+ 'config' => [
+ 'dependent' => true,
+ 'cascadeCallbacks' => true
+ ]
+ ]
+ ]
+ ]);
+
+ $this->setDisplayField('cluster_id');
+
+ $this->setPrimaryLink(['cluster_id']);
+ $this->setRequiresCO(true);
+ $this->setRedirectGoal('self');
+
+ $this->setAutoViewVars([
+ 'syncModes' => [
+ 'type' => 'enum',
+ 'class' => 'UnixCluster.UnixClusterSyncModeEnum'
+ ],
+ 'defaultShells' => [
+ 'type' => 'enum',
+ 'class' => 'UnixCluster.UnixShellEnum'
+ ],
+ 'defaultGroupModes' => [
+ 'type' => 'enum',
+ 'class' => 'UnixCluster.DefaultGroupModeEnum'
+ ],
+ 'usernameTypes' => [
+ 'type' => 'type',
+ 'attribute' => 'Identifiers.type'
+ ],
+ 'uidTypes' => [
+ 'type' => 'type',
+ 'attribute' => 'Identifiers.type'
+ ],
+ 'groupnameTypes' => [
+ 'type' => 'type',
+ 'attribute' => 'Identifiers.type'
+ ],
+ 'gidTypes' => [
+ 'type' => 'type',
+ 'attribute' => 'Identifiers.type'
+ ]
+ // defaultGroups is set by the controller, since only Groups mapped as
+ // Unix Cluster Groups of the current Unix Cluster may be selected
+ ]);
+
+ $this->setViewContains(['Clusters']);
+ $this->setEditContains(['Clusters']);
+ $this->setIndexContains(['Clusters']);
+
+ $this->setPermissions([
+ 'ui' => [
+ // Actions that operate over an entity (ie: require an $id)
+ 'entity' => [
+ 'delete' => false, // Delete the pluggable object instead
+ 'edit' => ['platformAdmin', 'coAdmin'],
+ // Linked from the Cluster Status page, see UnixClustersController::manage()
+ 'manage' => ['platformAdmin', 'coAdmin'],
+ 'view' => ['platformAdmin', 'coAdmin']
+ ],
+ // Actions that operate over a table (ie: do not require an $id)
+ 'table' => [
+ 'add' => ['platformAdmin', 'coAdmin'],
+ 'index' => ['platformAdmin', 'coAdmin']
+ ]
+ ]
+ ]);
+ }
+
+ /**
+ * Assign a Unix Cluster Account for a Person, in accordance with the Unix
+ * Cluster configuration. At most one Account is created automatically per
+ * Person, any additional Accounts must be created manually.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param Cluster $cluster Cluster, as passed by ClustersTable::assign()
+ * @param int $personId Person ID
+ * @return bool true if an Account was created, false if the Person already has one
+ * @throws \RuntimeException
+ */
+
+ public function assign(Cluster $cluster, int $personId): bool {
+ $unixCluster = $this->getForCluster($cluster);
+
+ if($this->UnixClusterAccounts->exists([
+ 'UnixClusterAccounts.unix_cluster_id' => $unixCluster->id,
+ 'UnixClusterAccounts.person_id' => $personId
+ ])) {
+ return false;
+ }
+
+ $person = $this->lookupPerson($cluster, $personId);
+
+ $username = $this->requireUsername($unixCluster, $person);
+ $uid = $this->requireUid($unixCluster, $person);
+
+ $cxn = $this->getConnection();
+ $cxn->begin();
+
+ try {
+ $defaultGroup = $this->resolveDefaultGroup($unixCluster, $person, $username, $uid);
+
+ $account = $this->UnixClusterAccounts->newEntity([
+ 'unix_cluster_id' => $unixCluster->id,
+ 'person_id' => $personId,
+ // The Account keeps the Sync Mode the Unix Cluster had when it was created
+ 'sync_mode' => $unixCluster->sync_mode,
+ 'status' => UnixClusterAccountStatusEnum::Active,
+ 'username' => $username,
+ 'uid' => (int)$uid,
+ 'gecos' => $this->UnixClusterAccounts->calculateGecos($person->primary_name ?? null),
+ 'login_shell' => $unixCluster->default_shell,
+ 'home_directory' => $this->UnixClusterAccounts->calculateHomeDirectory($unixCluster, $username),
+ 'primary_group_id' => $defaultGroup['group_id'],
+ 'valid_from' => null,
+ 'valid_through' => null
+ ]);
+
+ // UnixClusterAccountsTable::localAfterSave() records the Person's history,
+ // using this comment instead of the one for a manually added Account
+ $this->UnixClusterAccounts->saveOrFail($account, [
+ 'historyComment' => __d('unix_cluster', 'result.UnixClusterAccounts.assigned', [
+ $username,
+ $uid,
+ $cluster->description
+ ])
+ ]);
+
+ $cxn->commit();
+ }
+ catch(\Exception $e) {
+ $cxn->rollback();
+
+ throw new \RuntimeException($e->getMessage());
+ }
+
+ // Now that the transaction has been committed, provision the new personal Group
+ // and the Person (whose provisioning data now includes the new Account)
+ if($defaultGroup['created']) {
+ $this->provisionGroup($defaultGroup['group_id']);
+ }
+
+ $this->provisionPerson($personId);
+
+ // The new username is a member (eg: memberUid) of the Person's Unix Cluster Groups
+ $this->UnixClusterGroups->requestMemberGroupsProvisioning($unixCluster->id, $personId);
+
+ return true;
+ }
+
+ /**
+ * Callback before data is marshaled into an entity.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EventInterface $event beforeMarshal event
+ * @param ArrayObject $data Entity data
+ * @param ArrayObject $options Callback options
+ */
+
+ public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options) {
+ // A Default Group only applies in Existing Group mode. The UI hides the field
+ // in Personal Group mode, so drop any stale value rather than failing the save.
+ if(!empty($data['default_group_mode'])
+ && $data['default_group_mode'] == DefaultGroupModeEnum::Personal) {
+ $data['default_group_id'] = null;
+ }
+ }
+
+ /**
+ * Define business rules.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param RulesChecker $rules RulesChecker object
+ * @return RulesChecker
+ */
+
+ public function buildRules(RulesChecker $rules): RulesChecker {
+ foreach(self::TYPE_FIELDS as $field) {
+ $rules->add([$this, 'ruleValidIdentifierType'],
+ 'validIdentifierType_' . $field,
+ ['errorField' => $field, 'typeField' => $field]);
+ }
+
+ $rules->add([$this, 'ruleValidDefaultGroup'],
+ 'validDefaultGroup',
+ ['errorField' => 'default_group_id']);
+
+ return $rules;
+ }
+
+ /**
+ * Generate a display field for the given entity, using the parent Cluster's description.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EntityInterface $entity Unix Cluster entity
+ * @return string|null Display field, or null if not available
+ */
+
+ public function generateDisplayField(EntityInterface $entity): ?string {
+ if(empty($entity->cluster) || empty($entity->cluster->description)) {
+ return null;
+ }
+
+ return (string)$entity->cluster->description;
+ }
+
+ /**
+ * Find the Unix Cluster configuration for a Cluster, with its parent Cluster.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param Cluster $cluster Cluster
+ * @return UnixCluster|null Unix Cluster configuration, or null if not found
+ */
+
+ protected function findForCluster(Cluster $cluster): ?UnixCluster {
+ return $this->find()
+ ->where(['UnixClusters.cluster_id' => $cluster->id])
+ ->contain(['Clusters'])
+ ->first();
+ }
+
+ /**
+ * Obtain the Unix Cluster configuration for a Cluster.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param Cluster $cluster Cluster
+ * @return UnixCluster Unix Cluster configuration
+ * @throws \RuntimeException
+ */
+
+ public function getForCluster(Cluster $cluster): UnixCluster {
+ $unixCluster = $this->findForCluster($cluster);
+
+ if(empty($unixCluster)) {
+ throw new \RuntimeException(__d('error', 'notfound', [__d('unix_cluster', 'controller.UnixClusters', [1]) . ' ' . $cluster->id]));
+ }
+
+ return $unixCluster;
+ }
+
+
+ /**
+ * Describe how a Group is mapped to the Unix Cluster of a Cluster, for display
+ * on the Group's page.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param Cluster $cluster Cluster
+ * @param int $groupId Group ID
+ * @return array Empty if the Group is not mapped, otherwise an array with 'link' (URL array) and 'comment'
+ */
+
+ public function groupClusters(Cluster $cluster, int $groupId): array {
+ $unixCluster = $this->findForCluster($cluster);
+
+ if(empty($unixCluster)) {
+ return [];
+ }
+
+ $unixClusterGroup = $this->UnixClusterGroups->find()
+ ->where([
+ 'UnixClusterGroups.unix_cluster_id' => $unixCluster->id,
+ 'UnixClusterGroups.group_id' => $groupId
+ ])
+ ->contain(['Groups' => ['Identifiers']])
+ ->first();
+
+ if(empty($unixClusterGroup)) {
+ return [];
+ }
+
+ $origin = $unixClusterGroup->origin ?? UnixClusterGroupOriginEnum::Manual;
+
+ $notes = [__d('unix_cluster', 'enumeration.UnixClusterGroupOriginEnum.' . $origin)];
+
+ if(!empty($unixCluster->default_group_id) && $unixCluster->default_group_id == $groupId) {
+ $notes[] = __d('unix_cluster', 'field.UnixClusters.default_group_id');
+ }
+
+ // Same usability check as the Unix Cluster Groups index
+ $d = $this->UnixClusterGroups->describeGroup($unixClusterGroup, $unixCluster);
+
+ $notes[] = __d('unix_cluster', $d['usable']
+ ? 'information.UnixClusterGroups.usable'
+ : 'information.UnixClusterGroups.unusable');
+
+ return [
+ 'link' => [
+ 'plugin' => 'UnixCluster',
+ 'controller' => 'UnixClusterGroups',
+ 'action' => 'index',
+ '?' => ['unix_cluster_id' => $unixCluster->id]
+ ],
+ 'comment' => implode(', ', $notes)
+ ];
+ }
+
+ /**
+ * Obtain the description of the parent Cluster of a Unix Cluster configuration.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @return string|null Cluster description, or null if not available
+ */
+
+ public function lookupClusterDescription(UnixCluster $unixCluster): ?string {
+ if(!empty($unixCluster->cluster->description)) {
+ return $unixCluster->cluster->description;
+ }
+
+ if(!empty($unixCluster->cluster_id)) {
+ return $this->Clusters->get($unixCluster->cluster_id)->description;
+ }
+
+ return null;
+ }
+
+ /**
+ * Obtain a Person in the Cluster's CO, with Primary Name.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param Cluster $cluster Cluster
+ * @param int $personId Person ID
+ * @return Person Person
+ * @throws \RuntimeException
+ */
+
+ protected function lookupPerson(Cluster $cluster, int $personId): Person {
+ $person = $this->Clusters->Cos->People->find()
+ ->where([
+ 'People.id' => $personId,
+ // This ensures the Person is in the same CO as the Cluster
+ 'People.co_id' => $cluster->co_id
+ ])
+ ->contain(['PrimaryName'])
+ ->first();
+
+ if(empty($person)) {
+ throw new \RuntimeException(__d('error', 'notfound', [__d('controller', 'People', [1]) . ' ' . $personId]));
+ }
+
+ return $person;
+ }
+
+ /**
+ * Obtain the display names of the Types configured on a Unix Cluster.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @return array Type display names (or null if not set), keyed on TYPE_FIELDS
+ */
+
+ protected function lookupTypeNames(UnixCluster $unixCluster): array {
+ $typeIds = array_filter(array_map(
+ fn($f) => !empty($unixCluster->$f) ? (int)$unixCluster->$f : null,
+ array_combine(self::TYPE_FIELDS, self::TYPE_FIELDS)
+ ));
+
+ $names = [];
+
+ if(!empty($typeIds)) {
+ $names = $this->UsernameTypes->find('list', keyField: 'id', valueField: 'display_name')
+ ->where(['id IN' => array_values($typeIds)])
+ ->toArray();
+ }
+
+ $ret = [];
+
+ foreach(self::TYPE_FIELDS as $field) {
+ $ret[$field] = isset($typeIds[$field]) ? ($names[$typeIds[$field]] ?? null) : null;
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Obtain the Groups mapped as Unix Cluster Groups of a Unix Cluster, suitable
+ * for use as the Default Group.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $unixClusterId Unix Cluster ID
+ * @return array Array of Group names, keyed on Group ID
+ */
+
+ public function mappedGroups(int $unixClusterId): array {
+ return $this->DefaultGroups->find('list', keyField: 'id', valueField: 'name')
+ ->where(['DefaultGroups.id IN' => $this->UnixClusterGroups->mappedGroupIds($unixClusterId)])
+ ->orderBy(['DefaultGroups.name' => 'ASC'])
+ ->toArray();
+ }
+
+ /**
+ * Marshal the Unix Cluster data for provisioning a Person. Only Accounts in
+ * Active or Grace Period status are provisioned, along with the usable Unix
+ * Cluster Groups the Person is a member of. Nothing is returned if the Person
+ * has no such Account. PeopleTable::marshalProvisioningData() injects the result
+ * as unix_cluster_accounts and unix_cluster_groups.
+ *
+ * Example return:
+ *
+ * [
+ * 'UnixClusterAccounts' => [
+ * [
+ * 'id' => 39,
+ * 'unix_cluster_id' => 19,
+ * 'person_id' => 3869,
+ * 'sync_mode' => 'F', // UnixClusterSyncModeEnum::Full ('F') or Manual ('M')
+ * 'status' => 'A', // UnixClusterAccountStatusEnum::Active ('A') or GracePeriod ('GP')
+ * 'username' => 'bb0@myvo.org',
+ * 'uid' => 6030,
+ * 'gecos' => 'Bob Builder',
+ * 'login_shell' => '/bin/zsh',
+ * 'home_directory' => '/hpc/b/b/bb0@myvo.org',
+ * 'primary_group_id' => 13081,
+ * 'valid_from' => null,
+ * 'valid_through' => null,
+ * 'primary_group' => [
+ * 'id' => 13081,
+ * 'co_id' => 2,
+ * 'name' => 'bb0@myvo.org UnixCluster Group',
+ * 'status' => 'A',
+ * 'identifiers' => [
+ * ['id' => 9101, 'group_id' => 13081, 'type_id' => 31, 'identifier' => 'bb0@myvo.org', 'status' => 'A'], // Group Name Type
+ * ['id' => 9102, 'group_id' => 13081, 'type_id' => 32, 'identifier' => '6030', 'status' => 'A'] // GID Type
+ * ]
+ * ],
+ *
+ * // Derived for provisioners
+ * 'cluster_id' => 3, // Core Cluster ID (eg: for the Posix schemas' Unix Cluster selector)
+ * 'scope' => 'hpc-cluster', // See provisioningScope()
+ * 'gid_number' => '6030' // GID Identifier of the Primary Group, or null
+ * ]
+ * ],
+ * 'UnixClusterGroups' => [
+ * [
+ * 'id' => 14,
+ * 'unix_cluster_id' => 19,
+ * 'group_id' => 13079,
+ * 'origin' => 'M', // UnixClusterGroupOriginEnum::Manual ('M') or Personal ('P')
+ * 'person_id' => null, // The owning Person, for origin Personal
+ * 'group' => [
+ * 'id' => 13079,
+ * 'co_id' => 2,
+ * 'name' => 'hpc-users',
+ * 'status' => 'A',
+ * 'identifiers' => [
+ * ['id' => 9110, 'group_id' => 13079, 'type_id' => 31, 'identifier' => 'hpc-users', 'status' => 'A'],
+ * ['id' => 9111, 'group_id' => 13079, 'type_id' => 32, 'identifier' => '30001', 'status' => 'A']
+ * ]
+ * ],
+ *
+ * // Derived for provisioners, see UnixClusterGroupsTable::annotateForProvisioning()
+ * 'cluster_id' => 3,
+ * 'scope' => 'hpc-cluster',
+ * 'group_name' => 'hpc-users', // Group Name Identifier
+ * 'gid_number' => '30001' // GID Identifier
+ * ]
+ * ]
+ * ]
+ *
+ *
+ * @since COmanage Registry v5.4.0
+ * @param Cluster $cluster Cluster
+ * @param int $personId Person ID
+ * @return array Array of entities to provision, keyed on model name
+ */
+
+ public function marshalProvisioningData(Cluster $cluster, int $personId): array {
+ $unixCluster = $this->findForCluster($cluster);
+
+ if(empty($unixCluster)) {
+ return [];
+ }
+
+ $accounts = $this->UnixClusterAccounts->findForPerson(
+ $unixCluster->id,
+ $personId,
+ UnixClusterAccountStatusEnum::provisionableStatuses()
+ );
+
+ if(empty($accounts)) {
+ return [];
+ }
+
+ // Provisioners (eg: the LDAP Posix schemas) don't know the Unix Cluster
+ // configuration, so the derived values are added to each entity: scope (the
+ // Unix Cluster's label) and gid_number (the GID of the Primary Group) on
+ // Accounts, and scope, group_name, gid_number and the core Cluster ID on
+ // Unix Cluster Groups.
+ $scope = $this->provisioningScope($unixCluster);
+
+ foreach($accounts as $account) {
+ $account->set('cluster_id', $unixCluster->cluster_id);
+ $account->set('scope', $scope);
+ $account->set('gid_number', $this->UnixClusterGroups->groupIdentifierValue(
+ $account->primary_group->identifiers ?? [],
+ $unixCluster->gid_type_id
+ ));
+ }
+
+ $unixClusterGroups = $this->UnixClusterGroups->provisionableGroups($unixCluster, $personId);
+
+ foreach($unixClusterGroups as $unixClusterGroup) {
+ $this->UnixClusterGroups->annotateForProvisioning($unixClusterGroup, $unixCluster, $scope);
+ }
+
+ return [
+ 'UnixClusterAccounts' => $accounts,
+ 'UnixClusterGroups' => $unixClusterGroups
+ ];
+ }
+
+ /**
+ * Marshal the Unix Cluster data for provisioning a Group. This is an opt-in
+ * Cluster plugin hook called by GroupsTable::marshalProvisioningData(). Only a
+ * Group mapped to this Unix Cluster, active and usable, is returned, with the
+ * usernames of its members' Accounts. GroupsTable::marshalProvisioningData()
+ * injects the result as unix_cluster_groups.
+ *
+ * Example return:
+ *
+ * [
+ * 'UnixClusterGroups' => [
+ * [
+ * 'id' => 14,
+ * 'unix_cluster_id' => 19,
+ * 'group_id' => 13079,
+ * 'origin' => 'M', // UnixClusterGroupOriginEnum::Manual ('M') or Personal ('P')
+ * 'person_id' => null,
+ * 'group' => [
+ * 'id' => 13079,
+ * 'co_id' => 2,
+ * 'name' => 'hpc-users',
+ * 'status' => 'A',
+ * 'identifiers' => [
+ * ['id' => 9110, 'group_id' => 13079, 'type_id' => 31, 'identifier' => 'hpc-users', 'status' => 'A'], // Group Name Type
+ * ['id' => 9111, 'group_id' => 13079, 'type_id' => 32, 'identifier' => '30001', 'status' => 'A'] // GID Type
+ * ]
+ * ],
+ *
+ * // Derived for provisioners, see UnixClusterGroupsTable::marshalGroup()
+ * 'cluster_id' => 3,
+ * 'scope' => 'hpc-cluster',
+ * 'group_name' => 'hpc-users',
+ * 'gid_number' => '30001',
+ * // Usernames of the Active/Grace Period Accounts in this Unix Cluster of the
+ * // Group's valid members whose Person is Active or in Grace Period
+ * 'member_uids' => ['bb0@myvo.org', 'mc0@myvo.org']
+ * ]
+ * ]
+ * ]
+ *
+ *
+ * @since COmanage Registry v5.4.0
+ * @param Cluster $cluster Cluster
+ * @param int $groupId Group ID
+ * @return array Array of entities to provision, keyed on model name
+ */
+
+ public function marshalGroupProvisioningData(Cluster $cluster, int $groupId): array {
+ $unixCluster = $this->findForCluster($cluster);
+
+ if(empty($unixCluster)) {
+ return [];
+ }
+
+ $unixClusterGroup = $this->UnixClusterGroups->marshalGroup(
+ $unixCluster,
+ $groupId,
+ $this->provisioningScope($unixCluster)
+ );
+
+ if(empty($unixClusterGroup)) {
+ return [];
+ }
+
+ return ['UnixClusterGroups' => [$unixClusterGroup]];
+ }
+
+ /**
+ * Calculate the label used to scope provisioned values to this Unix Cluster
+ * (eg: the voPosixAccount scope-* attribute option). The label is derived
+ * from the Cluster description, using only lower case letters, digits and
+ * hyphens (as permitted in an LDAP attribute option), and falls back to the
+ * Cluster ID.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @return string Label
+ */
+
+ public function provisioningScope(UnixCluster $unixCluster): string {
+ $label = strtolower((string)$this->lookupClusterDescription($unixCluster));
+ $label = trim((string)preg_replace('/[^a-z0-9]+/', '-', $label), '-');
+
+ return $label !== '' ? $label : 'cluster-' . $unixCluster->cluster_id;
+ }
+
+ /**
+ * Request provisioning for a Group. A failure is logged, but not raised, since
+ * the Group has already been committed.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $groupId Group ID
+ */
+
+ protected function provisionGroup(int $groupId): void {
+ try {
+ $this->DefaultGroups->requestProvisioning(id: $groupId, context: ProvisioningContextEnum::Automatic);
+ }
+ catch(\Exception $e) {
+ $this->llog('error', "Provisioning failed for Group $groupId: " . $e->getMessage());
+ }
+ }
+
+ /**
+ * Request provisioning for a Person. A failure is logged, but not raised, since
+ * the Account has already been committed.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $personId Person ID
+ */
+
+ protected function provisionPerson(int $personId): void {
+ try {
+ $this->Clusters->Cos->People->requestProvisioning(id: $personId, context: ProvisioningContextEnum::Automatic);
+ }
+ catch(\Exception $e) {
+ $this->llog('error', "Provisioning failed for Person $personId: " . $e->getMessage());
+ }
+ }
+
+ /**
+ * Obtain the UID for a new Account from the Person's Identifiers. The UID must
+ * exist, must be a positive integer, and must not be in use by another Account
+ * in this Unix Cluster.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param Person $person Person
+ * @return string UID
+ * @throws \RuntimeException
+ */
+
+ protected function requireUid(UnixCluster $unixCluster, Person $person): string {
+ $uid = $this->Clusters->Cos->People->Identifiers->lookupForPerson((int)$unixCluster->uid_type_id, $person->id);
+
+ if($uid === null) {
+ throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusters.assign.uid.missing', [
+ $this->lookupTypeNames($unixCluster)['uid_type_id'] ?? $unixCluster->uid_type_id
+ ]));
+ }
+
+ // A UID must be a positive integer
+ if(!Validation::naturalNumber($uid)) {
+ throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusters.assign.uid.invalid', [$uid]));
+ }
+
+ if($this->UnixClusterAccounts->isInUse($unixCluster->id, 'uid', (int)$uid)) {
+ throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusterAccounts.uid.exists', [$uid]));
+ }
+
+ return $uid;
+ }
+
+ /**
+ * Obtain the username for a new Account from the Person's Identifiers. The
+ * username must exist and must not be in use by another Account in this Unix Cluster.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param Person $person Person
+ * @return string Username
+ * @throws \RuntimeException
+ */
+
+ protected function requireUsername(UnixCluster $unixCluster, Person $person): string {
+ $username = $this->Clusters->Cos->People->Identifiers->lookupForPerson((int)$unixCluster->username_type_id, $person->id);
+
+ if($username === null) {
+ throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusters.assign.username.missing', [
+ $this->lookupTypeNames($unixCluster)['username_type_id'] ?? $unixCluster->username_type_id
+ ]));
+ }
+
+ $maxLength = $this->UnixClusterAccounts->usernameMaxLength();
+
+ if(mb_strlen($username) > $maxLength) {
+ throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusters.assign.username.length', [$username, $maxLength]));
+ }
+
+ if($this->UnixClusterAccounts->isInUse($unixCluster->id, 'username', $username)) {
+ throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusterAccounts.username.exists', [$username]));
+ }
+
+ return $username;
+ }
+
+ /**
+ * Determine the Default Group of a new Account, in accordance with the
+ * Default Group Mode.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param Person $person Person
+ * @param string $username Username of the new Account
+ * @param string $uid UID of the new Account
+ * @return array Array of 'group_id' and 'created' (true if a new Group was created)
+ * @throws \RuntimeException
+ */
+
+ protected function resolveDefaultGroup(
+ UnixCluster $unixCluster,
+ Person $person,
+ string $username,
+ string $uid
+ ): array {
+ return match($unixCluster->default_group_mode) {
+ DefaultGroupModeEnum::Existing => [
+ 'group_id' => $this->verifyExistingDefaultGroup($unixCluster, $person),
+ 'created' => false
+ ],
+ DefaultGroupModeEnum::Personal => $this->UnixClusterGroups->findOrCreatePersonalGroup($unixCluster, $person, $username, $uid),
+ default => throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusters.assign.mode'))
+ };
+ }
+
+ /**
+ * Application Rule to determine if the Default Group is valid. If set, the Default
+ * Group Mode must be Existing Group, and the Group must be mapped as one of the
+ * Unix Cluster's Unix Cluster Groups. An empty Default Group is permitted (since
+ * no Groups can be mapped before the configuration is first saved). That the Group
+ * is in the same CO is enforced by the core RuleBuilderEventListener (GMR-2).
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EntityInterface $entity Entity to be validated
+ * @param array $options Application rule options
+ * @return string|bool true if the Rule check passes, an error string otherwise
+ */
+
+ public function ruleValidDefaultGroup(EntityInterface $entity, array $options): string|bool {
+ if(empty($entity->default_group_id)) {
+ return true;
+ }
+
+ if($entity->default_group_mode != DefaultGroupModeEnum::Existing) {
+ return __d('unix_cluster', 'error.UnixClusters.default_group_id.mode');
+ }
+
+ if(empty($entity->id)
+ || !$this->UnixClusterGroups->isMapped($entity->id, (int)$entity->default_group_id)) {
+ return __d('unix_cluster', 'error.UnixClusters.default_group_id.mapped');
+ }
+
+ return true;
+ }
+
+ /**
+ * Application Rule to determine if a configured Type is an active Identifier Type.
+ * That the Type is in the same CO is enforced by the core RuleBuilderEventListener
+ * (GMR-2).
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EntityInterface $entity Entity to be validated
+ * @param array $options Application rule options, including 'typeField'
+ * @return string|bool true if the Rule check passes, an error string otherwise
+ */
+
+ public function ruleValidIdentifierType(EntityInterface $entity, array $options): string|bool {
+ $field = $options['typeField'];
+
+ if(empty($entity->$field) || !$entity->isDirty($field)) {
+ return true;
+ }
+
+ $type = $this->UsernameTypes->find()
+ ->where(['UsernameTypes.id' => $entity->$field])
+ ->first();
+
+ if(empty($type)
+ || $type->attribute != 'Identifiers.type'
+ || $type->status != SuspendableStatusEnum::Active) {
+ return __d('unix_cluster', 'error.UnixClusters.type_id');
+ }
+
+ return true;
+ }
+
+ /**
+ * Obtain the status of a Person's Unix Cluster Accounts. The Cluster is Active
+ * if any Account is Active or in Grace Period, Locked if otherwise any Account
+ * is Suspended, and Expired if all Accounts are Deleted. The comment lists each
+ * Account with its status.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param Cluster $cluster Cluster
+ * @param int $personId Person ID
+ * @return array Array with 'status' (ClusterStatusEnum) and 'comment' keys
+ */
+
+ public function status(Cluster $cluster, int $personId): array {
+ $unixCluster = $this->findForCluster($cluster);
+
+ if(empty($unixCluster)) {
+ return [
+ 'status' => ClusterStatusEnum::NotCreated,
+ 'comment' => __d('unix_cluster', 'information.UnixClusters.unconfigured')
+ ];
+ }
+
+ $accounts = $this->UnixClusterAccounts->findForPerson($unixCluster->id, $personId);
+
+ if(empty($accounts)) {
+ return [
+ 'status' => ClusterStatusEnum::NotCreated,
+ 'comment' => __d('unix_cluster', 'information.UnixClusterAccounts.none')
+ ];
+ }
+
+ $statuses = array_map(fn($a) => $a->status, $accounts);
+
+ $status = match(true) {
+ !empty(array_intersect($statuses, UnixClusterAccountStatusEnum::provisionableStatuses()))
+ => ClusterStatusEnum::Active,
+ in_array(UnixClusterAccountStatusEnum::Suspended, $statuses, true)
+ => ClusterStatusEnum::Locked,
+ default
+ => ClusterStatusEnum::Expired
+ };
+
+ $list = array_map(
+ fn($a) => $a->username . ' (' . __d('unix_cluster', 'enumeration.UnixClusterAccountStatusEnum.' . $a->status) . ')',
+ $accounts
+ );
+
+ return [
+ 'status' => $status,
+ 'comment' => __d('unix_cluster', 'information.UnixClusterAccounts.registered', [count($accounts), implode(', ', $list)])
+ ];
+ }
+
+ /**
+ * Verify the Default Group of a new Account in Existing Group mode. A Default
+ * Group must be set, must be mapped as a Unix Cluster Group of this Unix Cluster,
+ * and the Person must be a member of it.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param UnixCluster $unixCluster Unix Cluster configuration
+ * @param Person $person Person
+ * @return int Default Group ID
+ * @throws \RuntimeException
+ */
+
+ protected function verifyExistingDefaultGroup(UnixCluster $unixCluster, Person $person): int {
+ if(empty($unixCluster->default_group_id)) {
+ throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusters.assign.default_group.none'));
+ }
+
+ $groupId = (int)$unixCluster->default_group_id;
+ $group = $this->DefaultGroups->find()->where(['DefaultGroups.id' => $groupId])->first();
+ $groupName = $group->name ?? (string)$groupId;
+
+ if(empty($group)
+ || !$this->UnixClusterGroups->isMapped($unixCluster->id, $groupId)) {
+ throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusters.assign.default_group.mapped', [$groupName]));
+ }
+
+ if(!$this->DefaultGroups->GroupMembers->isMember($groupId, $person->id)) {
+ throw new \RuntimeException(__d('unix_cluster', 'error.UnixClusters.assign.default_group.member', [$groupName]));
+ }
+
+ return $groupId;
+ }
+
+ /**
+ * Set validation rules.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param Validator $validator Validator
+ * @return Validator Validator
+ */
+
+ public function validationDefault(Validator $validator): Validator {
+ $schema = $this->getSchema();
+
+ $validator->add('cluster_id', [
+ 'content' => ['rule' => 'isInteger']
+ ]);
+ $validator->notEmptyString('cluster_id');
+
+ $validator->add('sync_mode', [
+ 'content' => ['rule' => ['inList', UnixClusterSyncModeEnum::getConstValues()]]
+ ]);
+ $validator->notEmptyString('sync_mode');
+
+ foreach(self::TYPE_FIELDS as $field) {
+ $validator->add($field, [
+ 'content' => ['rule' => 'isInteger']
+ ]);
+ $validator->notEmptyString($field);
+ }
+
+ $validator->add('default_shell', [
+ 'content' => ['rule' => ['inList', UnixShellEnum::getConstValues()]]
+ ]);
+ $validator->notEmptyString('default_shell');
+
+ $this->registerStringValidation($validator, $schema, 'homedir_prefix', true);
+ $validator->add('homedir_prefix', [
+ 'absolute' => [
+ 'rule' => ['custom', '/^\//'],
+ 'message' => __d('unix_cluster', 'error.UnixClusters.homedir_prefix')
+ ]
+ ]);
+
+ $validator->add('homedir_subdivisions', [
+ 'content' => [
+ 'rule' => ['naturalNumber', true],
+ 'message' => __d('unix_cluster', 'error.UnixClusters.homedir_subdivisions')
+ ]
+ ]);
+ $validator->allowEmptyString('homedir_subdivisions');
+
+ $validator->add('default_group_mode', [
+ 'content' => ['rule' => ['inList', DefaultGroupModeEnum::getConstValues()]]
+ ]);
+ $validator->notEmptyString('default_group_mode');
+
+ $validator->add('default_group_id', [
+ 'content' => ['rule' => 'isInteger']
+ ]);
+ $validator->allowEmptyString('default_group_id');
+
+ return $validator;
+ }
+}
diff --git a/app/availableplugins/UnixCluster/src/UnixClusterPlugin.php b/app/availableplugins/UnixCluster/src/UnixClusterPlugin.php
new file mode 100644
index 000000000..4e1706712
--- /dev/null
+++ b/app/availableplugins/UnixCluster/src/UnixClusterPlugin.php
@@ -0,0 +1,96 @@
+on(new \UnixCluster\Lib\Events\UnixClusterListener());
+ }
+
+ /**
+ * Add routes for the plugin.
+ *
+ * If your plugin has many routes and you would like to isolate them into a separate file,
+ * you can create `$plugin/config/routes.php` and delete this method.
+ *
+ * @param \Cake\Routing\RouteBuilder $routes The route builder to update.
+ * @return void
+ */
+ public function routes(RouteBuilder $routes): void
+ {
+ $routes->plugin(
+ 'UnixCluster',
+ ['path' => '/unix-cluster'],
+ function (RouteBuilder $builder) {
+ // Add custom routes here
+
+ $builder->fallbacks();
+ }
+ );
+ parent::routes($routes);
+ }
+
+ /**
+ * Add middleware for the plugin.
+ *
+ * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to update.
+ * @return \Cake\Http\MiddlewareQueue
+ */
+ public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
+ {
+ // Add your middlewares here
+
+ return $middlewareQueue;
+ }
+
+ /**
+ * Add commands for the plugin.
+ *
+ * @param \Cake\Console\CommandCollection $commands The command collection to update.
+ * @return \Cake\Console\CommandCollection
+ */
+ public function console(CommandCollection $commands): CommandCollection
+ {
+ // Add your commands here
+
+ $commands = parent::console($commands);
+
+ return $commands;
+ }
+
+ /**
+ * Register application container services.
+ *
+ * @param \Cake\Core\ContainerInterface $container The Container to update.
+ * @return void
+ * @link https://book.cakephp.org/4/en/development/dependency-injection.html#dependency-injection
+ */
+ public function services(ContainerInterface $container): void
+ {
+ // Add your services here
+ }
+}
diff --git a/app/availableplugins/UnixCluster/templates/UnixClusterAccounts/columns.inc b/app/availableplugins/UnixCluster/templates/UnixClusterAccounts/columns.inc
new file mode 100644
index 000000000..cbbbfa47c
--- /dev/null
+++ b/app/availableplugins/UnixCluster/templates/UnixClusterAccounts/columns.inc
@@ -0,0 +1,165 @@
+get('UnixCluster.UnixClusterGroups');
+
+$unixCluster = $vv_unix_cluster ?? null;
+
+$typeName = function($type) {
+ return !empty($type->display_name)
+ ? $type->display_name
+ : __d('unix_cluster', 'information.UnixClusters.derivation.unset');
+};
+
+// Compare an Account value with the Person Identifier it is derived from. Values
+// are only derived when the Account is created (and kept in sync in Full Sync
+// Mode), so a difference is noted rather than treated as an error.
+$sourceNote = function($entity, string $value, ?int $typeId, $type) use ($UnixClusterGroups, $typeName) {
+ $current = $UnixClusterGroups->groupIdentifierValue($entity->person->identifiers ?? [], $typeId);
+
+ if($current === null) {
+ return ' (' . h(__d('unix_cluster', 'information.UnixClusterAccounts.source.missing', [$typeName($type)])) . ')';
+ }
+
+ if($current !== $value) {
+ return ' (' . h(__d('unix_cluster', 'information.UnixClusterAccounts.source.differs', [$typeName($type), $current])) . ')';
+ }
+
+ return '';
+};
+
+$indexColumns = [
+ 'username' => [
+ 'type' => 'closure',
+ 'label' => __d('unix_cluster', 'field.UnixClusterAccounts.username'),
+ 'sortable' => true,
+ 'function' => function($entity) use ($sourceNote, $unixCluster) {
+ return $this->Html->link(
+ $entity->username,
+ ['plugin' => 'UnixCluster', 'controller' => 'UnixClusterAccounts', 'action' => 'edit', $entity->id]
+ ) . $sourceNote($entity, (string)$entity->username, $unixCluster->username_type_id ?? null, $unixCluster->username_type ?? null);
+ }
+ ],
+ 'person_id' => [
+ 'type' => 'closure',
+ 'label' => __d('controller', 'People', [1]),
+ 'function' => function($entity) {
+ if(empty($entity->person)) {
+ return h(__d('unix_cluster', 'information.UnixClusterGroups.person_missing'));
+ }
+
+ return $this->Html->link(
+ $entity->person->primary_name->full_name ?? (string)$entity->person_id,
+ ['plugin' => null, 'controller' => 'people', 'action' => 'edit', $entity->person_id]
+ );
+ }
+ ],
+ 'uid' => [
+ 'type' => 'closure',
+ 'label' => __d('unix_cluster', 'field.UnixClusterAccounts.uid'),
+ 'sortable' => true,
+ 'function' => function($entity) use ($sourceNote, $unixCluster) {
+ return h((string)$entity->uid)
+ . $sourceNote($entity, (string)$entity->uid, $unixCluster->uid_type_id ?? null, $unixCluster->uid_type ?? null);
+ }
+ ],
+ 'home_directory' => [
+ 'type' => 'echo',
+ 'label' => __d('unix_cluster', 'field.UnixClusterAccounts.home_directory')
+ ],
+ 'primary_group_id' => [
+ 'type' => 'closure',
+ 'label' => __d('unix_cluster', 'field.UnixClusterAccounts.primary_group_id'),
+ 'function' => function($entity) use ($UnixClusterGroups, $unixCluster) {
+ if(empty($entity->primary_group)) {
+ return h(__d('unix_cluster', 'information.UnixClusterGroups.missing'));
+ }
+
+ $ret = $this->Html->link(
+ $entity->primary_group->name,
+ ['plugin' => null, 'controller' => 'groups', 'action' => 'edit', $entity->primary_group->id]
+ );
+
+ // The GID provisioned for the Primary Group comes from its Identifiers
+ $gid = $UnixClusterGroups->groupIdentifierValue($entity->primary_group->identifiers ?? [], $unixCluster->gid_type_id ?? null);
+
+ $ret .= ' (' . h($gid !== null
+ ? __d('unix_cluster', 'information.UnixClusterAccounts.gid', [$gid])
+ : __d('unix_cluster', 'information.UnixClusterAccounts.gid.missing')) . ')';
+
+ if(!$UnixClusterGroups->isMapped((int)$entity->unix_cluster_id, (int)$entity->primary_group_id)) {
+ $ret .= ' (' . h(__d('unix_cluster', 'information.UnixClusterAccounts.primary_group.unmapped')) . ')';
+ }
+
+ return $ret;
+ }
+ ],
+ 'status' => [
+ 'type' => 'enum',
+ 'plugin' => 'UnixCluster',
+ 'class' => 'UnixClusterAccountStatusEnum',
+ 'sortable' => true
+ ],
+ 'sync_mode' => [
+ 'type' => 'enum',
+ 'plugin' => 'UnixCluster',
+ 'class' => 'UnixClusterSyncModeEnum'
+ ]
+];
+
+// Accounts belong to a Person, so they can only be added for a specific Person
+$suppressAddLink = true;
+$topLinks = [];
+
+if(!empty($vv_selected_person)) {
+ $topLinks[] = [
+ 'icon' => 'Add',
+ 'order' => 'Add',
+ 'label' => __d('operation', 'add.a', [__d('unix_cluster', 'controller.UnixClusterAccounts', [1])]),
+ 'link' => [
+ 'plugin' => 'UnixCluster',
+ 'controller' => 'UnixClusterAccounts',
+ 'action' => 'add',
+ '?' => ['person_id' => $vv_selected_person['id']]
+ ]
+ ];
+}
+
+$subnav = [
+ 'tabs' => ['Clusters', 'UnixCluster.UnixClusters', 'UnixCluster.UnixClusterGroups', 'UnixCluster.UnixClusterAccounts'],
+ 'action' => [
+ 'Clusters' => ['edit'],
+ 'UnixCluster.UnixClusters' => ['edit', 'view'],
+ 'UnixCluster.UnixClusterGroups' => ['index'],
+ 'UnixCluster.UnixClusterAccounts' => ['index']
+ ],
+ 'counter' => ['UnixCluster.UnixClusterGroups', 'UnixCluster.UnixClusterAccounts']
+];
diff --git a/app/availableplugins/UnixCluster/templates/UnixClusterAccounts/fields.inc b/app/availableplugins/UnixCluster/templates/UnixClusterAccounts/fields.inc
new file mode 100644
index 000000000..d8eef0266
--- /dev/null
+++ b/app/availableplugins/UnixCluster/templates/UnixClusterAccounts/fields.inc
@@ -0,0 +1,122 @@
+display_name)
+ ? $type->display_name
+ : __d('unix_cluster', 'information.UnixClusters.derivation.unset');
+};
+
+$fields = [];
+$hidden = [];
+$alerts = [];
+
+if(!empty($vv_selected_person)) {
+ // The Person is set by the link that led here, and cannot be changed
+ $hidden['person_id'] = $vv_selected_person['id'];
+
+ // 'person_name' is not a real field, see the groupMember infoDiv
+ $fields['person_name'] = [
+ 'fieldLabel' => __d('controller', 'People', [1]),
+ 'groupmember' => $vv_selected_person
+ ];
+} elseif($vv_action == 'add') {
+ $alerts[] = [
+ 'type' => 'warning',
+ 'message' => __d('unix_cluster', 'error.UnixClusterAccounts.person_id.required')
+ ];
+}
+
+$fields += [
+ 'username' => [
+ 'fieldDescription' => __d('unix_cluster', 'field.UnixClusterAccounts.username.desc')
+ ],
+ 'uid',
+ 'gecos',
+ // Manually created Accounts default to the Unix Cluster's Default Login Shell
+ 'login_shell' => [
+ 'default' => $unixCluster->default_shell ?? null
+ ],
+ 'home_directory',
+ // Only Groups mapped to this Unix Cluster are offered (see UnixClusterAccountsController)
+ 'primary_group_id',
+ 'sync_mode' => [
+ 'default' => $unixCluster->sync_mode ?? null
+ ],
+ 'status' => [
+ 'default' => UnixClusterAccountStatusEnum::Active
+ ],
+ 'valid_from',
+ 'valid_through'
+];
+
+if($unixCluster !== null) {
+ // Where these values come from when an Account is created automatically, and
+ // why manually assigned values may later conflict with automatic ones
+ $alerts[] = [
+ 'type' => 'information',
+ 'message' => __d('unix_cluster', 'information.UnixClusterAccounts.derivation', [
+ $typeName($unixCluster->username_type ?? null),
+ $typeName($unixCluster->uid_type ?? null)
+ ])
+ ];
+}
+
+// A plain Delete only removes the Account. If the Account's Primary Group is its
+// Person's own (unshared) personal Group, it may be deleted together with the
+// Account (see UnixClusterAccountsController::deleteWithGroup()).
+$topLinks = [];
+
+if(!empty($vv_personal_group) && !empty($vv_obj->id)) {
+ $topLinks[] = [
+ 'icon' => 'Delete',
+ 'order' => 'Delete',
+ 'label' => __d('unix_cluster', 'operation.UnixClusterAccounts.delete.group'),
+ 'link' => [
+ 'action' => 'deleteWithGroup',
+ $vv_obj->id
+ ],
+ 'class' => 'deletebutton',
+ 'confirm' => [
+ 'method' => 'post',
+ 'dg_title' => __d('unix_cluster', 'operation.UnixClusterAccounts.delete.group'),
+ 'dg_body_txt' => __d('unix_cluster', 'operation.UnixClusterAccounts.delete.group.confirm', [
+ $vv_obj->username,
+ $vv_personal_group->name
+ ]),
+ 'dg_confirm_btn' => __d('operation', 'delete')
+ ]
+ ];
+}
+
+// No subnavigation: the 'standard' set adds a plugin configuration tab, which
+// only applies to pluggable models (with a plugin column). Unix Cluster Accounts
+// are reached from the Unix Cluster's Accounts tab and the breadcrumbs.
diff --git a/app/availableplugins/UnixCluster/templates/UnixClusterGroups/columns.inc b/app/availableplugins/UnixCluster/templates/UnixClusterGroups/columns.inc
new file mode 100644
index 000000000..71b19c1f4
--- /dev/null
+++ b/app/availableplugins/UnixCluster/templates/UnixClusterGroups/columns.inc
@@ -0,0 +1,204 @@
+get('UnixCluster.UnixClusterGroups');
+
+$unixCluster = $vv_unix_cluster ?? null;
+$memberCounts = $vv_member_counts ?? [];
+$personalAccounts = $vv_personal_accounts ?? [];
+
+// Cache the derivation per row, since several columns use it
+$derived = [];
+$describe = function($entity) use ($UnixClusterGroups, $unixCluster, &$derived) {
+ if($unixCluster === null) {
+ // Without the Unix Cluster configuration nothing can be derived
+ return [
+ 'groupname' => null,
+ 'gid' => null,
+ 'gid_valid' => false,
+ 'usable' => false,
+ 'name_differs' => false
+ ];
+ }
+
+ if(!isset($derived[$entity->id])) {
+ $derived[$entity->id] = $UnixClusterGroups->describeGroup($entity, $unixCluster);
+ }
+
+ return $derived[$entity->id];
+};
+
+$typeName = function($type) {
+ return !empty($type->display_name)
+ ? $type->display_name
+ : __d('unix_cluster', 'information.UnixClusters.derivation.unset');
+};
+
+$indexColumns = [
+ 'group_id' => [
+ 'type' => 'closure',
+ 'label' => __d('unix_cluster', 'field.UnixClusterGroups.group_id'),
+ 'function' => function($entity) use ($describe, $unixCluster) {
+ if(empty($entity->group)) {
+ return h(__d('unix_cluster', 'information.UnixClusterGroups.missing'));
+ }
+
+ $ret = $this->Html->link(
+ $entity->group->name,
+ ['plugin' => null, 'controller' => 'groups', 'action' => 'edit', $entity->group->id]
+ );
+
+ if(!empty($unixCluster->default_group_id)
+ && $unixCluster->default_group_id == $entity->group_id) {
+ $ret .= ' (' . h(__d('unix_cluster', 'field.UnixClusters.default_group_id')) . ')';
+ }
+
+ $d = $describe($entity);
+
+ if($d['name_differs']) {
+ // The CO Group name is a label only, what gets provisioned is the Group Name Identifier
+ $ret .= '
'
+ . h(__d('unix_cluster', 'information.UnixClusterGroups.name_differs', [$d['groupname']]))
+ . '
';
+ }
+
+ return $ret;
+ }
+ ],
+ 'origin' => [
+ 'type' => 'closure',
+ 'label' => __d('unix_cluster', 'field.UnixClusterGroups.origin'),
+ 'function' => function($entity) use ($personalAccounts) {
+ $origin = $entity->origin ?? UnixClusterGroupOriginEnum::Manual;
+
+ $ret = h(__d('unix_cluster', 'enumeration.UnixClusterGroupOriginEnum.' . $origin));
+
+ if($origin == UnixClusterGroupOriginEnum::Personal) {
+ if(!empty($entity->person->primary_name)) {
+ $ret .= ' ' . __d('unix_cluster', 'information.UnixClusterGroups.personal_for', [
+ $this->Html->link(
+ $entity->person->primary_name->full_name,
+ ['plugin' => null, 'controller' => 'people', 'action' => 'edit', $entity->person->id]
+ )
+ ]);
+ } else {
+ $ret .= ' (' . h(__d('unix_cluster', 'information.UnixClusterGroups.person_missing')) . ')';
+ }
+
+ // Link to the Person's Accounts in this Unix Cluster
+ $accountLinks = [];
+
+ foreach($personalAccounts[$entity->person_id] ?? [] as $accountId => $username) {
+ $accountLinks[] = $this->Html->link(
+ $username,
+ ['plugin' => 'UnixCluster', 'controller' => 'UnixClusterAccounts', 'action' => 'edit', $accountId]
+ );
+ }
+
+ if(!empty($accountLinks)) {
+ $ret .= ' (' . __d('unix_cluster', 'information.UnixClusterGroups.accounts', [implode(', ', $accountLinks)]) . ')';
+ }
+ }
+
+ return $ret;
+ }
+ ],
+ 'groupname' => [
+ 'type' => 'closure',
+ 'label' => __d('unix_cluster', 'field.UnixClusterGroups.groupname.col', [$typeName($unixCluster->groupname_type ?? null)]),
+ 'function' => function($entity) use ($describe) {
+ $d = $describe($entity);
+
+ if($d['groupname'] === null) {
+ return h(__d('unix_cluster', 'information.UnixClusterGroups.missing'));
+ }
+
+ return h($d['groupname']);
+ }
+ ],
+ 'gid' => [
+ 'type' => 'closure',
+ 'label' => __d('unix_cluster', 'field.UnixClusterGroups.gid.col', [$typeName($unixCluster->gid_type ?? null)]),
+ 'function' => function($entity) use ($describe) {
+ $d = $describe($entity);
+
+ if($d['gid'] === null) {
+ return h(__d('unix_cluster', 'information.UnixClusterGroups.missing'));
+ }
+
+ $ret = h($d['gid']);
+
+ if(!$d['gid_valid']) {
+ $ret .= ' (' . h(__d('unix_cluster', 'information.UnixClusterGroups.invalid')) . ')';
+ }
+
+ return $ret;
+ }
+ ],
+ 'members' => [
+ 'type' => 'closure',
+ 'label' => __d('unix_cluster', 'field.UnixClusterGroups.members'),
+ 'function' => function($entity) use ($memberCounts) {
+ return $this->Html->link(
+ (string)($memberCounts[$entity->group_id] ?? 0),
+ [
+ 'plugin' => null,
+ 'controller' => 'group-members',
+ 'action' => 'index',
+ '?' => ['group_id' => $entity->group_id]
+ ]
+ );
+ }
+ ],
+ 'usable' => [
+ 'type' => 'closure',
+ 'label' => __d('unix_cluster', 'field.UnixClusterGroups.usable'),
+ 'function' => function($entity) use ($describe) {
+ $d = $describe($entity);
+
+ return h(__d('unix_cluster', $d['usable']
+ ? 'information.UnixClusterGroups.usable'
+ : 'information.UnixClusterGroups.unusable'));
+ }
+ ]
+];
+
+$subnav = [
+ 'tabs' => ['Clusters', 'UnixCluster.UnixClusters', 'UnixCluster.UnixClusterGroups', 'UnixCluster.UnixClusterAccounts'],
+ 'action' => [
+ 'Clusters' => ['edit'],
+ 'UnixCluster.UnixClusters' => ['edit', 'view'],
+ 'UnixCluster.UnixClusterGroups' => ['index'],
+ 'UnixCluster.UnixClusterAccounts' => ['index']
+ ],
+ 'counter' => ['UnixCluster.UnixClusterGroups', 'UnixCluster.UnixClusterAccounts']
+];
diff --git a/app/availableplugins/UnixCluster/templates/UnixClusterGroups/fields.inc b/app/availableplugins/UnixCluster/templates/UnixClusterGroups/fields.inc
new file mode 100644
index 000000000..a568dc89f
--- /dev/null
+++ b/app/availableplugins/UnixCluster/templates/UnixClusterGroups/fields.inc
@@ -0,0 +1,53 @@
+origin) && $vv_obj->origin == UnixClusterGroupOriginEnum::Personal);
+
+$fields = [
+ // The select only offers Groups in this CO that are not yet mapped to this
+ // Unix Cluster (see UnixClusterGroupsController). A personal Group was created
+ // for a specific Person, so it cannot be pointed at another CO Group.
+ // FieldHelper renders a readonly select as disabled.
+ 'group_id' => [
+ 'readonly' => $isPersonal
+ ]
+];
+
+$alerts = [];
+
+if($isPersonal) {
+ $alerts[] = [
+ 'type' => 'information',
+ 'message' => __d('unix_cluster', 'information.UnixClusterGroups.personal')
+ ];
+}
+
+// No subnavigation: the 'standard' set adds a plugin configuration tab, which
+// only applies to pluggable models (with a plugin column). Unix Cluster Groups
+// are reached from the Unix Cluster's Groups tab and the breadcrumbs.
diff --git a/app/availableplugins/UnixCluster/templates/UnixClusters/fields.inc b/app/availableplugins/UnixCluster/templates/UnixClusters/fields.inc
new file mode 100644
index 000000000..03045ffc7
--- /dev/null
+++ b/app/availableplugins/UnixCluster/templates/UnixClusters/fields.inc
@@ -0,0 +1,156 @@
+ [
+ 'element' => 'UnixCluster.derivationSummaryToggle'
+ ]
+ ];
+}
+
+$fields += [
+ 'SUBTITLE.account' => [
+ 'subtitle' => __d('unix_cluster', 'information.UnixClusters.header.account')
+ ],
+ 'sync_mode' => [
+ 'default' => UnixClusterSyncModeEnum::Full
+ ],
+ 'username_type_id',
+ 'uid_type_id',
+ 'default_shell' => [
+ 'default' => UnixShellEnum::Bash
+ ],
+ 'homedir_prefix' => [
+ 'default' => '/home'
+ ],
+ 'homedir_subdivisions' => [
+ 'default' => 0
+ ],
+ 'SUBTITLE.group' => [
+ 'subtitle' => __d('unix_cluster', 'information.UnixClusters.header.group')
+ ],
+ 'groupname_type_id',
+ 'gid_type_id',
+ 'SUBTITLE.default_group' => [
+ 'subtitle' => __d('unix_cluster', 'information.UnixClusters.header.default_group')
+ ],
+ 'default_group_mode' => [
+ 'default' => DefaultGroupModeEnum::Existing
+ ],
+ 'default_group_id'
+];
+
+$subnav = [
+ 'tabs' => ['Clusters', 'UnixCluster.UnixClusters'],
+ 'action' => [
+ 'Clusters' => ['edit'],
+ 'UnixCluster.UnixClusters' => ['edit', 'view']
+ ],
+ 'counter' => []
+];
+
+// As for core Hierarchy tabs, only link to the Unix Cluster Groups and Accounts
+// when those models support views
+foreach(['UnixCluster.UnixClusterGroups', 'UnixCluster.UnixClusterAccounts'] as $childModel) {
+ if($this->Tab->modelSupportsView($childModel)) {
+ $subnav['tabs'][] = $childModel;
+ $subnav['action'][$childModel] = ['index'];
+ $subnav['counter'][] = $childModel;
+ }
+}
+
+// Warnings that apply to the saved configuration
+$alerts = [];
+
+foreach($vv_derivation['warnings'] ?? [] as $warning) {
+ $message = __d('unix_cluster', $warning);
+
+ if($warning == 'information.UnixClusters.default_group.none') {
+ // Point the admin to where a Default Group can be made available
+ $message .= ' ' . $this->Html->link(
+ __d('unix_cluster', 'information.UnixClusters.default_group.manage'),
+ [
+ 'plugin' => 'UnixCluster',
+ 'controller' => 'UnixClusterGroups',
+ 'action' => 'index',
+ '?' => ['unix_cluster_id' => $vv_obj->id]
+ ]
+ );
+ }
+
+ $alerts[] = [
+ 'type' => 'warning',
+ 'message' => $message
+ ];
+}
+
+?>
+
+
+ = $this->element('UnixCluster.derivationSummary', ['vv_derivation' => $vv_derivation]) ?>
+
+
+
diff --git a/app/availableplugins/UnixCluster/templates/element/derivationSummary.php b/app/availableplugins/UnixCluster/templates/element/derivationSummary.php
new file mode 100644
index 000000000..70ed802a7
--- /dev/null
+++ b/app/availableplugins/UnixCluster/templates/element/derivationSummary.php
@@ -0,0 +1,246 @@
+' . h($name) . ''
+ : '' . __d('unix_cluster', 'information.UnixClusters.derivation.unset') . '';
+};
+
+// Render an example value, or a placeholder if it can't be calculated
+$example = function(mixed $value): string {
+ return ($value !== null && $value !== '')
+ ? '' . h((string)$value) . ''
+ : '' . __d('unix_cluster', 'information.UnixClusters.derivation.unset') . '';
+};
+
+// Account attribute rows, as [label, source, example]
+$accountRows = [
+ [
+ __d('unix_cluster', 'field.UnixClusterAccounts.username'),
+ __d('unix_cluster', 'information.UnixClusters.derivation.username_limit', [
+ __d('unix_cluster', 'information.UnixClusters.derivation.person_identifier', [$typeName($account['username']['type'])]),
+ 32
+ ]),
+ $example($account['username']['example'])
+ ],
+ [
+ __d('unix_cluster', 'field.UnixClusterAccounts.uid'),
+ __d('unix_cluster', 'information.UnixClusters.derivation.person_identifier', [$typeName($account['uid']['type'])]),
+ $example($account['uid']['example'])
+ ],
+ [
+ __d('unix_cluster', 'field.UnixClusterAccounts.home_directory'),
+ __d('unix_cluster', 'information.UnixClusters.derivation.home_directory', [
+ $example($account['home_directory']['prefix']),
+ $account['home_directory']['subdivisions']
+ ]),
+ $example($account['home_directory']['example'])
+ ],
+ [
+ __d('unix_cluster', 'field.UnixClusterAccounts.login_shell'),
+ __d('unix_cluster', 'information.UnixClusters.derivation.login_shell'),
+ $example($account['login_shell']['example'])
+ ],
+ [
+ __d('unix_cluster', 'field.UnixClusterAccounts.gecos'),
+ __d('unix_cluster', 'information.UnixClusters.derivation.gecos'),
+ '' . __d('unix_cluster', 'information.UnixClusters.derivation.gecos.example') . ''
+ ],
+ [
+ __d('unix_cluster', 'field.UnixClusterAccounts.sync_mode'),
+ __d('unix_cluster', 'information.UnixClusters.derivation.sync_mode'),
+ h((string)($account['sync_mode']['label'] ?? ''))
+ ]
+];
+
+// Group attribute rows, as [label, source]
+$groupRows = [
+ [
+ __d('unix_cluster', 'field.UnixClusterGroups.groupname'),
+ __d('unix_cluster', 'information.UnixClusters.derivation.group_identifier', [$typeName($group['groupname']['type'])])
+ ],
+ [
+ __d('unix_cluster', 'field.UnixClusterGroups.gid'),
+ __d('unix_cluster', 'information.UnixClusters.derivation.group_identifier', [$typeName($group['gid']['type'])])
+ ]
+];
+
+?>
+
+
diff --git a/app/availableplugins/UnixCluster/templates/element/derivationSummaryToggle.php b/app/availableplugins/UnixCluster/templates/element/derivationSummaryToggle.php
new file mode 100644
index 000000000..4ffc4aaa3
--- /dev/null
+++ b/app/availableplugins/UnixCluster/templates/element/derivationSummaryToggle.php
@@ -0,0 +1,57 @@
+
+
+
diff --git a/app/availableplugins/UnixCluster/webroot/.gitkeep b/app/availableplugins/UnixCluster/webroot/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/app/plugins/LdapConnector/config/plugin.json b/app/plugins/LdapConnector/config/plugin.json
index b5f9b93a7..b55282162 100644
--- a/app/plugins/LdapConnector/config/plugin.json
+++ b/app/plugins/LdapConnector/config/plugin.json
@@ -1,5 +1,4 @@
{
- "_comment": "TODO: Add PosixGroupSchemas, PosixAccountSchemas, VoPosixGroupSchemas, and VoPosixAccountSchemas to types.ldap_schema after the Unix Cluster Plugin is implemented.",
"types": {
"provisioning_target": [
"LdapProvisioners"
@@ -12,7 +11,11 @@
"GroupOfNamesSchemas",
"EduMemberSchemas",
"EduPersonSchemas",
- "VoPersonSchemas"
+ "VoPersonSchemas",
+ "PosixAccountSchemas",
+ "PosixGroupSchemas",
+ "VoPosixAccountSchemas",
+ "VoPosixGroupSchemas"
]
},
"schema": {
@@ -234,6 +237,7 @@
"type": "integer",
"foreignkey": { "table": "ldap_schemas", "column": "id" }
},
+ "cluster_id": { "notnull": false },
"cn": { "type": "boolean" },
"gid_number": { "type": "boolean" },
"member_uid": { "type": "boolean" }
@@ -241,6 +245,9 @@
"indexes": {
"posix_group_schemas_i1": {
"columns": [ "ldap_schema_id" ]
+ },
+ "posix_group_schemas_i2": {
+ "columns": [ "cluster_id" ]
}
}
},
@@ -253,6 +260,7 @@
"type": "integer",
"foreignkey": { "table": "ldap_schemas", "column": "id" }
},
+ "cluster_id": { "notnull": false },
"cn": { "type": "boolean" },
"uid": { "type": "boolean" },
"uid_number": { "type": "boolean" },
@@ -264,6 +272,9 @@
"indexes": {
"posix_account_schemas_i1": {
"columns": [ "ldap_schema_id" ]
+ },
+ "posix_account_schemas_i2": {
+ "columns": [ "cluster_id" ]
}
}
},
diff --git a/app/plugins/LdapConnector/resources/locales/en_US/ldap_connector.po b/app/plugins/LdapConnector/resources/locales/en_US/ldap_connector.po
index 4c1d69fb5..98ec3c8b6 100644
--- a/app/plugins/LdapConnector/resources/locales/en_US/ldap_connector.po
+++ b/app/plugins/LdapConnector/resources/locales/en_US/ldap_connector.po
@@ -232,6 +232,9 @@ msgid "field.InetOrgPersonSchemas.uid_type_id"
msgstr "UID Type"
# PosixGroupSchemas
+msgid "field.PosixGroupSchemas.cluster_id"
+msgstr "Unix Cluster"
+
msgid "field.PosixGroupSchemas.cn"
msgstr "Common Name"
@@ -242,6 +245,9 @@ msgid "field.PosixGroupSchemas.member_uid"
msgstr "Member UID"
# PosixAccountSchemas
+msgid "field.PosixAccountSchemas.cluster_id"
+msgstr "Unix Cluster"
+
msgid "field.PosixAccountSchemas.cn"
msgstr "Common Name"
@@ -263,6 +269,12 @@ msgstr "Login Shell"
msgid "field.PosixAccountSchemas.gecos"
msgstr "GECOS"
+msgid "field.PosixAccountSchemas.cluster_id.desc"
+msgstr "Choose the Unix Cluster whose account data this schema provisions. Leave blank to retain the default behavior."
+
+msgid "field.PosixGroupSchemas.cluster_id.desc"
+msgstr "Choose the Unix Cluster whose group data this schema provisions. Leave blank to retain the default behavior."
+
# LdapPublicKeySchemas
msgid "field.LdapPublicKeySchemas.ssh_public_key"
msgstr "SSH Public Key"
diff --git a/app/plugins/LdapConnector/src/Lib/Traits/PosixSchemaTrait.php b/app/plugins/LdapConnector/src/Lib/Traits/PosixSchemaTrait.php
new file mode 100644
index 000000000..cc0adec24
--- /dev/null
+++ b/app/plugins/LdapConnector/src/Lib/Traits/PosixSchemaTrait.php
@@ -0,0 +1,209 @@
+unix_cluster_accounts, entities shown as arrays,
+ * see UnixClustersTable::marshalProvisioningData()):
+ *
+ * [
+ * [
+ * 'id' => 39,
+ * 'unix_cluster_id' => 19,
+ * 'person_id' => 3869,
+ * 'status' => 'A', // Active ('A') or Grace Period ('GP')
+ * 'username' => 'bb0@myvo.org', // uid, voPosixAccount uid
+ * 'uid' => 6030, // uidNumber, voPosixAccountUidNumber
+ * 'gecos' => 'Bob Builder', // gecos, voPosixAccountGecos
+ * 'login_shell' => '/bin/zsh', // loginShell, voPosixAccountLoginShell
+ * 'home_directory' => '/hpc/b/b/bb0@myvo.org', // homeDirectory, voPosixAccountHomeDirectory
+ * 'primary_group_id' => 13081,
+ * 'primary_group' => ['id' => 13081, 'name' => 'bb0@myvo.org UnixCluster Group', 'identifiers' => [...]],
+ * 'cluster_id' => 3, // Matched against the schema's cluster_id
+ * 'scope' => 'hpc-cluster', // Attribute option scope-hpc-cluster
+ * 'gid_number' => '6030' // gidNumber, voPosixAccountGidNumber
+ * ]
+ * ]
+ *
+ *
+ * Example input, Groups ($data->unix_cluster_groups, see
+ * UnixClustersTable::marshalGroupProvisioningData()):
+ *
+ * [
+ * [
+ * 'id' => 14,
+ * 'unix_cluster_id' => 19,
+ * 'group_id' => 13079,
+ * 'origin' => 'M', // Manual ('M') or Personal ('P')
+ * 'person_id' => null,
+ * 'group' => ['id' => 13079, 'name' => 'hpc-users', 'identifiers' => [...]],
+ * 'cluster_id' => 3, // Matched against the schema's cluster_id
+ * 'scope' => 'hpc-cluster', // Attribute option scope-hpc-cluster
+ * 'group_name' => 'hpc-users', // Added to cn
+ * 'gid_number' => '30001', // gidNumber, voPosixAccountGidNumber
+ * 'member_uids' => ['bb0@myvo.org', 'mc0@myvo.org'] // memberUid
+ * ]
+ * ]
+ *
+ */
+trait PosixSchemaTrait
+{
+ /**
+ * Obtain the Posix Accounts of a provisioned Person that have all the values
+ * required by RFC 2307 (username, numeric UID and GID, home directory), in a
+ * deterministic order (by Unix Cluster, then by Account). If a Cluster ID is
+ * supplied, only Accounts from that Unix Cluster are returned.
+ *
+ * @param object $data Provisioned Person
+ * @param int|null $clusterId Core Cluster ID, if filtering to one Cluster
+ * @return array Unix Cluster Accounts
+ * @since COmanage Registry v5.4.0
+ */
+ protected function posixAccounts(object $data, ?int $clusterId=null): array
+ {
+ $accounts = array_values(array_filter(
+ (array)($data->unix_cluster_accounts ?? []),
+ static fn($a) => is_object($a)
+ && trim((string)($a->username ?? '')) !== ''
+ && Validation::naturalNumber((string)($a->uid ?? ''))
+ && Validation::naturalNumber((string)($a->gid_number ?? ''))
+ && trim((string)($a->home_directory ?? '')) !== ''
+ && ($clusterId === null || (int)($a->cluster_id ?? 0) === $clusterId)
+ ));
+
+ usort($accounts, static fn($a, $b) =>
+ [(int)$a->unix_cluster_id, (int)$a->id] <=> [(int)$b->unix_cluster_id, (int)$b->id]);
+
+ return $accounts;
+ }
+
+ /**
+ * Obtain the Posix Groups of a provisioned Group that have a Unix group name and
+ * a numeric GID, in a deterministic order (by Unix Cluster, then by mapping).
+ * If a Cluster ID is supplied, only mappings from that Unix Cluster are returned.
+ *
+ * @param object $data Provisioned Group
+ * @param int|null $clusterId Core Cluster ID, if filtering to one Cluster
+ * @return array Unix Cluster Groups
+ * @since COmanage Registry v5.4.0
+ */
+ protected function posixGroups(object $data, ?int $clusterId=null): array
+ {
+ $groups = array_values(array_filter(
+ (array)($data->unix_cluster_groups ?? []),
+ static fn($g) => is_object($g)
+ && trim((string)($g->group_name ?? '')) !== ''
+ && Validation::naturalNumber((string)($g->gid_number ?? ''))
+ && ($clusterId === null || (int)($g->cluster_id ?? 0) === $clusterId)
+ ));
+
+ usort($groups, static fn($a, $b) =>
+ [(int)$a->unix_cluster_id, (int)$a->id] <=> [(int)$b->unix_cluster_id, (int)$b->id]);
+
+ return $groups;
+ }
+
+ /**
+ * Common names for a Posix Group: the CO Group name (which other schemas, and
+ * typically the RDN, use) followed by the Unix group names.
+ *
+ * @param object $data Provisioned Group
+ * @param array $groups Posix Groups, see posixGroups()
+ * @return array Common names
+ * @since COmanage Registry v5.4.0
+ */
+ protected function posixGroupCommonNames(object $data, array $groups): array
+ {
+ $names = [(string)($data->name ?? '')];
+
+ foreach ($groups as $g) {
+ $names[] = (string)$g->group_name;
+ }
+
+ return $this->uniquePosixValues('cn', $names);
+ }
+
+ /**
+ * Build an attribute description, with the scope-* attribute option when
+ * attribute options are enabled and a scope is available.
+ *
+ * @param string $attr Attribute name
+ * @param string|null $scope Unix Cluster label
+ * @param bool $enabled Whether attribute options are enabled
+ * @return string Attribute description
+ * @since COmanage Registry v5.4.0
+ */
+ protected function scopedAttribute(string $attr, ?string $scope, bool $enabled): string
+ {
+ $scope = trim((string)$scope);
+
+ return ($enabled && $scope !== '') ? $attr . ';scope-' . $scope : $attr;
+ }
+
+ /**
+ * De-duplicate the values of a multi-valued attribute, dropping empty values.
+ *
+ * TODO: Once PR-476 (CO-3031) is merged, use LdapMatchingRulesTrait::uniqueAttributeValues()
+ * here, so values are compared by the attribute's equality matching rule. Add
+ * memberuid (caseExactIA5Match) and gecos (caseIgnoreIA5Match) to the RFC 2307
+ * block of LdapMatchingRuleEnum at the same time. Until then array_unique() is
+ * used, which compares case-sensitively. That is correct for memberUid, but does
+ * not merge uid values differing only in case.
+ *
+ * @param string $attr Attribute name
+ * @param array $values Values
+ * @return array Unique values
+ * @since COmanage Registry v5.4.0
+ */
+ protected function uniquePosixValues(string $attr, array $values): array
+ {
+ $values = array_map(static fn($v) => trim((string)$v), $values);
+
+ return array_values(array_unique(array_filter($values, static fn($v) => $v !== '')));
+ }
+}
diff --git a/app/plugins/LdapConnector/src/Model/Table/LdapProvisionersTable.php b/app/plugins/LdapConnector/src/Model/Table/LdapProvisionersTable.php
index c3e3202f4..0b2f441bc 100644
--- a/app/plugins/LdapConnector/src/Model/Table/LdapProvisionersTable.php
+++ b/app/plugins/LdapConnector/src/Model/Table/LdapProvisionersTable.php
@@ -114,6 +114,22 @@ public function initialize(array $config): void {
'cascadeCallbacks' => true
]
]
+ ],
+ 'Clusters' => [
+ [
+ 'alias' => 'LdapConnectorPosixAccountSchemas',
+ 'targetModel' => 'LdapConnector.PosixAccountSchemas',
+ 'config' => [
+ 'foreignKey' => 'cluster_id'
+ ]
+ ],
+ [
+ 'alias' => 'LdapConnectorPosixGroupSchemas',
+ 'targetModel' => 'LdapConnector.PosixGroupSchemas',
+ 'config' => [
+ 'foreignKey' => 'cluster_id'
+ ]
+ ]
]
]);
diff --git a/app/plugins/LdapConnector/src/Model/Table/PosixAccountSchemasTable.php b/app/plugins/LdapConnector/src/Model/Table/PosixAccountSchemasTable.php
index ba8198416..2d41b369e 100644
--- a/app/plugins/LdapConnector/src/Model/Table/PosixAccountSchemasTable.php
+++ b/app/plugins/LdapConnector/src/Model/Table/PosixAccountSchemasTable.php
@@ -29,6 +29,7 @@
namespace LdapConnector\Model\Table;
+use App\Model\Entity\Person;
use Cake\Datasource\EntityInterface;
use Cake\ORM\Table;
use Cake\Validation\Validator;
@@ -46,6 +47,7 @@ class PosixAccountSchemasTable extends Table {
use \App\Lib\Traits\TableMetaTrait;
use \App\Lib\Traits\ValidationTrait;
use \LdapConnector\Lib\Traits\LdapObjectClassSchemaTrait;
+ use \LdapConnector\Lib\Traits\PosixSchemaTrait;
/**
* Perform Cake model initialization.
@@ -66,10 +68,20 @@ public function initialize(array $config): void {
$this->addBehavior('Timestamp');
$this->belongsTo('LdapConnector.LdapSchemas');
+ $this->belongsTo('Clusters')
+ ->setProperty('cluster');
$this->setPrimaryLink(['LdapConnector.ldap_schema_id']);
$this->setRequiresCO(true);
+ $this->setAutoViewVars([
+ 'clusters' => [
+ 'type' => 'select',
+ 'model' => 'Clusters',
+ 'where' => ['plugin' => 'UnixCluster.UnixClusters']
+ ]
+ ]);
+
$this->setViewContains(['LdapSchemas']);
$this->setEditContains(['LdapSchemas']);
$this->setIndexContains(['LdapSchemas']);
@@ -143,21 +155,41 @@ public function getDefaults(): array {
* - Multi-valued. Enabled via boolean flag `user_password`.
* - Password hash for Unix authentication.
*
- * Implementation note:
- * - POSIX account attribute assembly is currently a stub pending POSIX service / Unix cluster
- * integration. It returns an empty array until active data source mapping is connected.
+ * Data source:
+ * - The Person's Unix Cluster Accounts (unix_cluster_accounts, marshalled by the UnixCluster
+ * plugin, Active and Grace Period only). If a Unix Cluster is selected in cluster_id, only
+ * that Cluster's Accounts are considered. Otherwise, all complete Accounts are ordered by Unix
+ * Cluster and Account. Since posixAccount attributes are single-valued, uidNumber, gidNumber,
+ * homeDirectory, loginShell and gecos come from the first complete Account; uid lists the
+ * usernames of the considered Accounts. Use voPosixAccount to provision several Accounts
+ * with their own values.
+ * - cn is the Person's Primary Name, as for the person schema.
+ * - If the Person has no Account, nothing is emitted on add, and the Posix attributes are
+ * cleared on modify/rename (without objectClass, which removes posixAccount). uid and cn
+ * are shared with other schemas and are not cleared.
*
- * Example (expected return format when populated for a Person):
+ * Example (add for a Person with one Account, see PosixSchemaTrait for the input data):
*
* [
* 'objectClass' => ['posixAccount'],
- * 'cn' => 'Robert Andrews',
- * 'uid' => 'randrews',
- * 'uidNumber' => '10001',
- * 'gidNumber' => '1000',
- * 'homeDirectory' => '/home/randrews',
- * 'loginShell' => '/bin/bash',
- * 'gecos' => 'Robert Andrews,Bldg 1 Room 203'
+ * 'cn' => 'Bob Builder',
+ * 'uid' => ['bb0@myvo.org'],
+ * 'uidNumber' => '6030',
+ * 'gidNumber' => '6030',
+ * 'homeDirectory' => '/hpc/b/b/bb0@myvo.org',
+ * 'loginShell' => '/bin/zsh',
+ * 'gecos' => 'Bob Builder'
+ * ]
+ *
+ *
+ * Example (modify/rename for a Person who no longer has an Account; posixAccount is removed):
+ *
+ * [
+ * 'uidNumber' => [],
+ * 'gidNumber' => [],
+ * 'homeDirectory' => [],
+ * 'loginShell' => [],
+ * 'gecos' => []
* ]
*
*
@@ -177,7 +209,78 @@ public function assemblePluginAttributes(
object $data,
string $op
): array {
- return [];
+ $ret = [];
+
+ // posixAccount applies to People provisions only
+ if ($className !== 'People' || !($data instanceof Person)) {
+ return $ret;
+ }
+
+ $isModifyLike = ($op === 'modify' || $op === 'rename');
+
+ $accounts = $this->posixAccounts(
+ $data,
+ !empty($schema->cluster_id) ? (int)$schema->cluster_id : null
+ );
+
+ if (empty($accounts)) {
+ if (!$isModifyLike) {
+ return $ret;
+ }
+
+ // Clear the attributes only this schema manages. No objectClass is added, so
+ // posixAccount is removed by the (replacing) modify along with its attributes.
+ foreach ([
+ 'uid_number' => 'uidNumber',
+ 'gid_number' => 'gidNumber',
+ 'home_directory' => 'homeDirectory',
+ 'login_shell' => 'loginShell',
+ 'gecos' => 'gecos'
+ ] as $flag => $attr) {
+ if (!empty($schema->$flag)) {
+ $ret[$attr] = [];
+ }
+ }
+
+ return $ret;
+ }
+
+ $account = $accounts[0];
+
+ if (!empty($schema->cn)) {
+ $cn = $this->renderName($data->primary_name ?? new \stdClass());
+ $ret['cn'] = ($cn !== '') ? $cn : (string)$account->username;
+ }
+
+ if (!empty($schema->uid)) {
+ $ret['uid'] = $this->uniquePosixValues('uid', array_map(static fn($a) => $a->username, $accounts));
+ }
+
+ if (!empty($schema->uid_number)) {
+ $ret['uidNumber'] = (string)$account->uid;
+ }
+
+ if (!empty($schema->gid_number)) {
+ $ret['gidNumber'] = (string)$account->gid_number;
+ }
+
+ if (!empty($schema->home_directory)) {
+ $ret['homeDirectory'] = (string)$account->home_directory;
+ }
+
+ if (!empty($schema->login_shell)) {
+ $ret['loginShell'] = !empty($account->login_shell) ? (string)$account->login_shell : ($isModifyLike ? [] : null);
+ }
+
+ if (!empty($schema->gecos)) {
+ $ret['gecos'] = !empty($account->gecos) ? (string)$account->gecos : ($isModifyLike ? [] : null);
+ }
+
+ $ret = array_filter($ret, static fn($v) => $v !== null);
+
+ $this->ensureSchemaObjectClass($ret);
+
+ return $ret;
}
/**
@@ -196,6 +299,11 @@ public function validationDefault(Validator $validator): Validator {
]);
$validator->notEmptyString('ldap_schema_id');
+ $validator->add('cluster_id', [
+ 'content' => ['rule' => 'isInteger']
+ ]);
+ $validator->allowEmptyString('cluster_id');
+
foreach ([
'cn',
'uid_number',
diff --git a/app/plugins/LdapConnector/src/Model/Table/PosixGroupSchemasTable.php b/app/plugins/LdapConnector/src/Model/Table/PosixGroupSchemasTable.php
index 5687427b3..bbd952838 100644
--- a/app/plugins/LdapConnector/src/Model/Table/PosixGroupSchemasTable.php
+++ b/app/plugins/LdapConnector/src/Model/Table/PosixGroupSchemasTable.php
@@ -29,6 +29,7 @@
namespace LdapConnector\Model\Table;
+use App\Model\Entity\Group;
use Cake\Datasource\EntityInterface;
use Cake\ORM\Table;
use Cake\Validation\Validator;
@@ -46,6 +47,7 @@ class PosixGroupSchemasTable extends Table {
use \App\Lib\Traits\TableMetaTrait;
use \App\Lib\Traits\ValidationTrait;
use \LdapConnector\Lib\Traits\LdapObjectClassSchemaTrait;
+ use \LdapConnector\Lib\Traits\PosixSchemaTrait;
/**
* Perform Cake model initialization.
@@ -66,10 +68,20 @@ public function initialize(array $config): void {
$this->addBehavior('Timestamp');
$this->belongsTo('LdapConnector.LdapSchemas');
+ $this->belongsTo('Clusters')
+ ->setProperty('cluster');
$this->setPrimaryLink(['LdapConnector.ldap_schema_id']);
$this->setRequiresCO(true);
+ $this->setAutoViewVars([
+ 'clusters' => [
+ 'type' => 'select',
+ 'model' => 'Clusters',
+ 'where' => ['plugin' => 'UnixCluster.UnixClusters']
+ ]
+ ]);
+
$this->setViewContains(['LdapSchemas']);
$this->setEditContains(['LdapSchemas']);
$this->setIndexContains(['LdapSchemas']);
@@ -140,17 +152,44 @@ public function getDefaults(): array {
* - Multi-valued. Enabled via boolean flag `member_uid`.
* - List of member login usernames (UIDs) belonging to this POSIX group.
*
- * Implementation note:
- * - POSIX group attribute assembly is currently a stub pending POSIX service / Unix cluster
- * integration. It returns an empty array until active data source mapping is connected.
+ * Data source:
+ * - The Group's Unix Cluster Groups (unix_cluster_groups, marshalled by the UnixCluster plugin
+ * for active, usable mappings). If a Unix Cluster is selected in cluster_id, only that
+ * Cluster's mapping is considered. Otherwise, the default behavior is preserved: gidNumber
+ * comes from the first mapping (ordered by Unix Cluster, then mapping), and memberUid lists
+ * the usernames of the members' Accounts in all mapped Unix Clusters.
+ * - cn lists the CO Group name (kept so the value used by other schemas and the RDN stays
+ * present) followed by the Unix group name(s) from the Group Name Identifier.
+ * - If the Group is not mapped, nothing is emitted on add, and gidNumber/memberUid are cleared
+ * on modify/rename (without objectClass, which removes posixGroup).
+ * - RFC 2307 defines posixGroup as structural, so combining it with groupOfNames requires a
+ * directory schema where posixGroup is auxiliary (eg rfc2307bis).
+ *
+ * Example (add for a Group mapped to one Unix Cluster, see PosixSchemaTrait for the input data):
+ *
+ * [
+ * 'objectClass' => ['posixGroup'],
+ * 'cn' => ['hpc-users'], // CO Group name, then Unix group names (de-duplicated)
+ * 'gidNumber' => '30001',
+ * 'memberUid' => ['bb0@myvo.org', 'mc0@myvo.org']
+ * ]
+ *
*
- * Example (expected return format when populated for a Group):
+ * Example (add for a personal Group, whose CO Group name differs from its Unix group name):
*
* [
* 'objectClass' => ['posixGroup'],
- * 'cn' => 'sysadmins',
- * 'gidNumber' => '1000',
- * 'memberUid' => ['jdoe', 'asmith', 'bjones']
+ * 'cn' => ['bb0@myvo.org UnixCluster Group', 'bb0@myvo.org'],
+ * 'gidNumber' => '6030',
+ * 'memberUid' => ['bb0@myvo.org']
+ * ]
+ *
+ *
+ * Example (modify/rename for a Group that is no longer mapped; posixGroup is removed):
+ *
+ * [
+ * 'gidNumber' => [],
+ * 'memberUid' => []
* ]
*
*
@@ -170,7 +209,60 @@ public function assemblePluginAttributes(
object $data,
string $op
): array {
- return [];
+ $ret = [];
+
+ // posixGroup applies to Groups provisions only
+ if ($className !== 'Groups' || !($data instanceof Group)) {
+ return $ret;
+ }
+
+ $isModifyLike = ($op === 'modify' || $op === 'rename');
+
+ $groups = $this->posixGroups(
+ $data,
+ !empty($schema->cluster_id) ? (int)$schema->cluster_id : null
+ );
+
+ if (empty($groups)) {
+ if ($isModifyLike) {
+ // cn is shared with other schemas, so only gidNumber and memberUid are cleared
+ if (!empty($schema->gid_number)) {
+ $ret['gidNumber'] = [];
+ }
+
+ if (!empty($schema->member_uid)) {
+ $ret['memberUid'] = [];
+ }
+ }
+
+ return $ret;
+ }
+
+ if (!empty($schema->cn)) {
+ $ret['cn'] = $this->posixGroupCommonNames($data, $groups);
+ }
+
+ if (!empty($schema->gid_number)) {
+ $ret['gidNumber'] = (string)$groups[0]->gid_number;
+ }
+
+ if (!empty($schema->member_uid)) {
+ $memberUids = [];
+
+ foreach ($groups as $g) {
+ $memberUids = array_merge($memberUids, (array)($g->member_uids ?? []));
+ }
+
+ $memberUids = $this->uniquePosixValues('memberUid', $memberUids);
+
+ if (!empty($memberUids) || $isModifyLike) {
+ $ret['memberUid'] = $memberUids;
+ }
+ }
+
+ $this->ensureSchemaObjectClass($ret);
+
+ return $ret;
}
/**
@@ -189,6 +281,11 @@ public function validationDefault(Validator $validator): Validator {
]);
$validator->notEmptyString('ldap_schema_id');
+ $validator->add('cluster_id', [
+ 'content' => ['rule' => 'isInteger']
+ ]);
+ $validator->allowEmptyString('cluster_id');
+
foreach (['cn', 'gid_number', 'member_uid'] as $f) {
$validator->add($f, [
'content' => ['rule' => 'boolean']
diff --git a/app/plugins/LdapConnector/src/Model/Table/VoPosixAccountSchemasTable.php b/app/plugins/LdapConnector/src/Model/Table/VoPosixAccountSchemasTable.php
index c69d06ac3..53ce779de 100644
--- a/app/plugins/LdapConnector/src/Model/Table/VoPosixAccountSchemasTable.php
+++ b/app/plugins/LdapConnector/src/Model/Table/VoPosixAccountSchemasTable.php
@@ -31,6 +31,7 @@
namespace LdapConnector\Model\Table;
+use App\Model\Entity\Person;
use Cake\Datasource\EntityInterface;
use Cake\ORM\Table;
use Cake\Validation\Validator;
@@ -48,6 +49,7 @@ class VoPosixAccountSchemasTable extends Table {
use \App\Lib\Traits\TableMetaTrait;
use \App\Lib\Traits\ValidationTrait;
use \LdapConnector\Lib\Traits\LdapObjectClassSchemaTrait;
+ use \LdapConnector\Lib\Traits\PosixSchemaTrait;
/**
* Perform Cake model initialization.
@@ -142,19 +144,50 @@ public function getDefaults(): array {
* - Single-valued. Enabled via boolean flag `vo_posix_account_gecos`.
* - User information string for VO POSIX systems.
*
- * Implementation note:
- * - VO POSIX account attribute assembly is currently a stub pending VO POSIX service integration.
- * It returns an empty array until active data source mapping is connected.
+ * Data source:
+ * - The Person's Unix Cluster Accounts (unix_cluster_accounts, marshalled by the UnixCluster
+ * plugin, Active and Grace Period only). Each Account contributes one value per attribute.
+ * - When attribute options are enabled on the provisioner, each value (including uid) carries
+ * the `scope-{cluster}` option, where the label is derived from the Cluster description (eg
+ * `voPosixAccountUidNumber;scope-hpc`). When disabled, the values of all Accounts are
+ * aggregated under the plain attribute names.
+ * - cn is the Person's Primary Name, as for the person schema.
+ * - If the Person has no Account, nothing is emitted on add. On modify/rename the plain
+ * attributes are cleared (best effort: scoped variants of Accounts that no longer exist
+ * cannot be enumerated without reading the entry, as for voPersonApplicationPassword).
*
- * Example (expected return format when populated for a Person):
+ * Example (add for a Person with Accounts in two Unix Clusters, attribute options enabled,
+ * see PosixSchemaTrait for the input data):
+ *
+ * [
+ * 'objectClass' => ['voPosixAccount'],
+ * 'cn' => 'Bob Builder',
+ * 'uid;scope-hpc-cluster' => ['bb0@myvo.org'],
+ * 'voPosixAccountUidNumber;scope-hpc-cluster' => ['6030'],
+ * 'voPosixAccountGidNumber;scope-hpc-cluster' => ['6030'],
+ * 'voPosixAccountHomeDirectory;scope-hpc-cluster' => ['/hpc/b/b/bb0@myvo.org'],
+ * 'voPosixAccountLoginShell;scope-hpc-cluster' => ['/bin/zsh'],
+ * 'voPosixAccountGecos;scope-hpc-cluster' => ['Bob Builder'],
+ * 'uid;scope-debian-cluster' => ['bbuilder'],
+ * 'voPosixAccountUidNumber;scope-debian-cluster' => ['7010'],
+ * 'voPosixAccountGidNumber;scope-debian-cluster' => ['20216'],
+ * 'voPosixAccountHomeDirectory;scope-debian-cluster' => ['/home/bbuilder'],
+ * 'voPosixAccountLoginShell;scope-debian-cluster' => ['/bin/bash'],
+ * 'voPosixAccountGecos;scope-debian-cluster' => ['Bob Builder']
+ * ]
+ *
+ *
+ * Example (same Person, attribute options disabled; values of all Accounts are aggregated):
*
* [
* 'objectClass' => ['voPosixAccount'],
- * 'voPosixAccountUidNumber' => '20005',
- * 'voPosixAccountGidNumber' => '2000',
- * 'voPosixAccountHomeDirectory' => '/vo/home/jdoe',
- * 'voPosixAccountLoginShell' => '/bin/bash',
- * 'voPosixAccountGecos' => 'Jane Doe [VO Project]'
+ * 'cn' => 'Bob Builder',
+ * 'uid' => ['bb0@myvo.org', 'bbuilder'],
+ * 'voPosixAccountUidNumber' => ['6030', '7010'],
+ * 'voPosixAccountGidNumber' => ['6030', '20216'],
+ * 'voPosixAccountHomeDirectory' => ['/hpc/b/b/bb0@myvo.org', '/home/bbuilder'],
+ * 'voPosixAccountLoginShell' => ['/bin/zsh', '/bin/bash'],
+ * 'voPosixAccountGecos' => ['Bob Builder']
* ]
*
*
@@ -174,7 +207,68 @@ public function assemblePluginAttributes(
object $data,
string $op
): array {
- return [];
+ $ret = [];
+
+ // voPosixAccount applies to People provisions only
+ if ($className !== 'People' || !($data instanceof Person)) {
+ return $ret;
+ }
+
+ $isModifyLike = ($op === 'modify' || $op === 'rename');
+ $scoped = $this->attributeOptionsEnabled($ldapProvisioner);
+
+ // Schema flag => [LDAP attribute, Account property]
+ $map = [
+ 'vo_posix_account_uid_number' => ['voPosixAccountUidNumber', 'uid'],
+ 'vo_posix_account_gid_number' => ['voPosixAccountGidNumber', 'gid_number'],
+ 'vo_posix_account_home_directory' => ['voPosixAccountHomeDirectory', 'home_directory'],
+ 'vo_posix_account_login_shell' => ['voPosixAccountLoginShell', 'login_shell'],
+ 'vo_posix_account_gecos' => ['voPosixAccountGecos', 'gecos']
+ ];
+
+ $accounts = $this->posixAccounts($data);
+
+ if (empty($accounts)) {
+ if ($isModifyLike) {
+ foreach ($map as $flag => [$attr, $prop]) {
+ if (!empty($schema->$flag)) {
+ $ret[$attr] = [];
+ }
+ }
+ }
+
+ return $ret;
+ }
+
+ if (!empty($schema->cn)) {
+ $cn = $this->renderName($data->primary_name ?? new \stdClass());
+ $ret['cn'] = ($cn !== '') ? $cn : (string)$accounts[0]->username;
+ }
+
+ $values = [];
+
+ foreach ($accounts as $account) {
+ $scope = $account->scope ?? null;
+
+ if (!empty($schema->uid)) {
+ // The plain uid is shared with other schemas, the scoped one belongs to the Account
+ $values[$this->scopedAttribute('uid', $scope, $scoped)][] = (string)$account->username;
+ }
+
+ foreach ($map as $flag => [$attr, $prop]) {
+ if (!empty($schema->$flag) && (string)($account->$prop ?? '') !== '') {
+ $values[$this->scopedAttribute($attr, $scope, $scoped)][] = (string)$account->$prop;
+ }
+ }
+ }
+
+ foreach ($values as $attr => $vals) {
+ $ret[$attr] = $this->uniquePosixValues($attr, $vals);
+ }
+
+ $this->ensureSchemaObjectClass($ret);
+
+ return $ret;
}
/**
diff --git a/app/plugins/LdapConnector/src/Model/Table/VoPosixGroupSchemasTable.php b/app/plugins/LdapConnector/src/Model/Table/VoPosixGroupSchemasTable.php
index c135f15a4..8fca58853 100644
--- a/app/plugins/LdapConnector/src/Model/Table/VoPosixGroupSchemasTable.php
+++ b/app/plugins/LdapConnector/src/Model/Table/VoPosixGroupSchemasTable.php
@@ -29,6 +29,7 @@
namespace LdapConnector\Model\Table;
+use App\Model\Entity\Group;
use Cake\Datasource\EntityInterface;
use Cake\ORM\Table;
use Cake\Validation\Validator;
@@ -46,6 +47,7 @@ class VoPosixGroupSchemasTable extends Table {
use \App\Lib\Traits\TableMetaTrait;
use \App\Lib\Traits\ValidationTrait;
use \LdapConnector\Lib\Traits\LdapObjectClassSchemaTrait;
+ use \LdapConnector\Lib\Traits\PosixSchemaTrait;
/**
* Perform Cake model initialization.
@@ -140,17 +142,36 @@ public function getDefaults(): array {
* - Multi-valued. Enabled via boolean flag `member_uid`.
* - List of member login usernames (UIDs) belonging to this VO POSIX group.
*
- * Implementation note:
- * - VO POSIX group attribute assembly is currently a stub pending VO POSIX service integration.
- * It returns an empty array until active data source mapping is connected.
+ * Data source:
+ * - The Group's Unix Cluster Groups (unix_cluster_groups, marshalled by the UnixCluster plugin
+ * for active, usable mappings). Each mapping contributes its GID. When attribute options are
+ * enabled on the provisioner, the GID carries the `scope-{cluster}` option (eg
+ * `voPosixAccountGidNumber;scope-hpc`), otherwise the GIDs are aggregated.
+ * - memberUid (not a voPosixAccount attribute, so never scoped) lists the usernames of the
+ * members' Accounts in all mapped Unix Clusters.
+ * - cn lists the CO Group name followed by the Unix group name(s), as for posixGroup.
+ * - If the Group is not mapped, nothing is emitted on add, and the plain attributes are
+ * cleared on modify/rename (best effort, as for voPosixAccount).
*
- * Example (expected return format when populated for a Group):
+ * Example (add for a Group mapped to two Unix Clusters, attribute options enabled,
+ * see PosixSchemaTrait for the input data):
+ *
+ * [
+ * 'objectClass' => ['voPosixGroup'],
+ * 'cn' => ['hpc-users'],
+ * 'voPosixAccountGidNumber;scope-hpc-cluster' => ['30001'],
+ * 'voPosixAccountGidNumber;scope-debian-cluster' => ['20300'],
+ * 'memberUid' => ['bb0@myvo.org', 'mc0@myvo.org', 'bbuilder']
+ * ]
+ *
+ *
+ * Example (same Group, attribute options disabled; the GIDs are aggregated):
*
* [
* 'objectClass' => ['voPosixGroup'],
- * 'cn' => 'vo-researchers',
- * 'voPosixAccountGidNumber' => '2000',
- * 'memberUid' => ['jdoe', 'asmith', 'bjones']
+ * 'cn' => ['hpc-users'],
+ * 'voPosixAccountGidNumber' => ['30001', '20300'],
+ * 'memberUid' => ['bb0@myvo.org', 'mc0@myvo.org', 'bbuilder']
* ]
*
*
@@ -170,7 +191,61 @@ public function assemblePluginAttributes(
object $data,
string $op
): array {
- return [];
+ $ret = [];
+
+ // voPosixGroup applies to Groups provisions only
+ if ($className !== 'Groups' || !($data instanceof Group)) {
+ return $ret;
+ }
+
+ $isModifyLike = ($op === 'modify' || $op === 'rename');
+ $scoped = $this->attributeOptionsEnabled($ldapProvisioner);
+
+ $groups = $this->posixGroups($data);
+
+ if (empty($groups)) {
+ if ($isModifyLike) {
+ if (!empty($schema->vo_posix_account_gid_number)) {
+ $ret['voPosixAccountGidNumber'] = [];
+ }
+
+ if (!empty($schema->member_uid)) {
+ $ret['memberUid'] = [];
+ }
+ }
+
+ return $ret;
+ }
+
+ if (!empty($schema->cn)) {
+ $ret['cn'] = $this->posixGroupCommonNames($data, $groups);
+ }
+
+ $memberUids = [];
+ $gids = [];
+
+ foreach ($groups as $g) {
+ $gids[$this->scopedAttribute('voPosixAccountGidNumber', $g->scope ?? null, $scoped)][] = (string)$g->gid_number;
+ $memberUids = array_merge($memberUids, (array)($g->member_uids ?? []));
+ }
+
+ if (!empty($schema->vo_posix_account_gid_number)) {
+ foreach ($gids as $attr => $vals) {
+ $ret[$attr] = $this->uniquePosixValues($attr, $vals);
+ }
+ }
+
+ if (!empty($schema->member_uid)) {
+ $memberUids = $this->uniquePosixValues('memberUid', $memberUids);
+
+ if (!empty($memberUids) || $isModifyLike) {
+ $ret['memberUid'] = $memberUids;
+ }
+ }
+
+ $this->ensureSchemaObjectClass($ret);
+
+ return $ret;
}
/**
diff --git a/app/plugins/LdapConnector/templates/PosixAccountSchemas/fields.inc b/app/plugins/LdapConnector/templates/PosixAccountSchemas/fields.inc
index 78d64a7d6..cbf5afe17 100644
--- a/app/plugins/LdapConnector/templates/PosixAccountSchemas/fields.inc
+++ b/app/plugins/LdapConnector/templates/PosixAccountSchemas/fields.inc
@@ -26,6 +26,7 @@
*/
$fields = [
+ 'cluster_id',
'cn' => [
'checked' => true,
'readonly' => true,
diff --git a/app/plugins/LdapConnector/templates/PosixGroupSchemas/fields.inc b/app/plugins/LdapConnector/templates/PosixGroupSchemas/fields.inc
index 7d3366709..9a57a3859 100644
--- a/app/plugins/LdapConnector/templates/PosixGroupSchemas/fields.inc
+++ b/app/plugins/LdapConnector/templates/PosixGroupSchemas/fields.inc
@@ -26,6 +26,7 @@
*/
$fields = [
+ 'cluster_id',
'cn' => [
'checked' => true,
'readonly' => true,
diff --git a/app/resources/locales/en_US/field.po b/app/resources/locales/en_US/field.po
index a48ed74a0..139634ffe 100644
--- a/app/resources/locales/en_US/field.po
+++ b/app/resources/locales/en_US/field.po
@@ -728,6 +728,9 @@ msgstr "Target Group"
msgid "GroupNestings.target_group_id.desc"
msgstr "Where the current group will be nested"
+msgid "Groups.clusters.desc"
+msgstr "Clusters that map this Group. Follow a link to see how the Group is provisioned to that Cluster."
+
msgid "Groups.desc.admins"
msgstr "{0} Administrators"
diff --git a/app/src/Command/JobCommand.php b/app/src/Command/JobCommand.php
index 450214873..6829d00ae 100644
--- a/app/src/Command/JobCommand.php
+++ b/app/src/Command/JobCommand.php
@@ -38,6 +38,7 @@
use Cake\Utility\Security;
use App\Lib\Enum\JobStatusEnum;
use App\Lib\Events\CoIdEventListener;
+use App\Lib\Util\EventUtilities;
class JobCommand extends BaseCommand
{
@@ -113,6 +114,10 @@ public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar
public function execute(Arguments $args, ConsoleIo $io)
{
+ // AppController::initialize() is not called for command line tools, so we
+ // register the Actor and Rule Builder Event Listeners here (CFM-558)
+ EventUtilities::registerCoreListeners(actor: EventUtilities::cliActor());
+
$CosTable = $this->getTableLocator()->get('Cos');
$JobTable = $this->getTableLocator()->get('Jobs');
diff --git a/app/src/Controller/AppController.php b/app/src/Controller/AppController.php
index b69c8e0a0..45e3d16a2 100644
--- a/app/src/Controller/AppController.php
+++ b/app/src/Controller/AppController.php
@@ -33,9 +33,8 @@
use App\Lib\Enum\TAndCLoginModeEnum;
use App\Lib\Enum\TAndCStatusEnum;
use App\Lib\Enum\TemplateableStatusEnum;
-use App\Lib\Events\ActorEventListener;
use App\Lib\Events\CoIdEventListener;
-use App\Lib\Events\RuleBuilderEventListener;
+use App\Lib\Util\EventUtilities;
use App\Lib\Util\StringUtilities;
use Cake\Controller\Controller;
use Cake\Datasource\Exception\RecordNotFoundException;
@@ -97,11 +96,9 @@ public function initialize(): void {
// Breadcrumb Manager
$this->loadComponent('Breadcrumb');
- $ActorEventListener = new ActorEventListener($this->RegistryAuth);
- EventManager::instance()->on($ActorEventListener);
-
- $RuleBuilderEventListener = new RuleBuilderEventListener();
- EventManager::instance()->on($RuleBuilderEventListener);
+ // Register the Actor and Rule Builder Event Listeners. Command line tools
+ // perform the equivalent setup via EventUtilities directly (CFM-558).
+ EventUtilities::registerCoreListeners(auth: $this->RegistryAuth);
if(!$this->request->is('restful')) {
// Initialization for non-RESTful
diff --git a/app/src/Controller/ClustersController.php b/app/src/Controller/ClustersController.php
index 7eec8455e..1ef8fd5f8 100644
--- a/app/src/Controller/ClustersController.php
+++ b/app/src/Controller/ClustersController.php
@@ -41,6 +41,20 @@ class ClustersController extends StandardPluggableController {
]
];
+ /**
+ * Perform Controller initialization.
+ *
+ * @since COmanage Registry v5.4.0
+ */
+
+ public function initialize(): void {
+ parent::initialize();
+
+ // The status page belongs to a Person (?person_id=), so don't link back to the
+ // Clusters index. The Person links are injected from the primary link.
+ $this->Breadcrumb->skipParents(['/^\/clusters\/status/']);
+ }
+
/**
* Assign accounts for all Clusters for a Person,
*
diff --git a/app/src/Controller/GroupsController.php b/app/src/Controller/GroupsController.php
index 69edb536c..ca6c5652e 100644
--- a/app/src/Controller/GroupsController.php
+++ b/app/src/Controller/GroupsController.php
@@ -30,6 +30,7 @@
namespace App\Controller;
// XXX not doing anything with Log yet
+use Cake\Event\EventInterface;
use Cake\Log\Log;
class GroupsController extends StandardController {
@@ -38,6 +39,29 @@ class GroupsController extends StandardController {
'Groups.name' => 'asc'
]
];
+
+ /**
+ * Callback run prior to the request render.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param EventInterface $event Cake Event
+ * @return \Cake\Http\Response|null|void
+ */
+
+ public function beforeRender(EventInterface $event) {
+ if(in_array($this->request->getParam('action'), ['edit', 'view'], true)) {
+ $obj = $this->viewBuilder()->getVar('vv_obj');
+
+ if(!empty($obj->id)) {
+ // The Clusters that map this Group, as reported by each Cluster Plugin
+ $Clusters = $this->getTableLocator()->get('Clusters');
+
+ $this->set('vv_group_clusters', $Clusters->groupClusters((int)$obj->id));
+ }
+ }
+
+ return parent::beforeRender($event);
+ }
/**
* Reconcile a Group's memberships.
diff --git a/app/src/Lib/Events/ActorEventListener.php b/app/src/Lib/Events/ActorEventListener.php
index e7264f608..a5b179127 100644
--- a/app/src/Lib/Events/ActorEventListener.php
+++ b/app/src/Lib/Events/ActorEventListener.php
@@ -39,16 +39,39 @@
class ActorEventListener Implements EventListenerInterface {
// RegistryAuth Component
protected $RegistryAuth;
+
+ // Fixed actor identifier, used when there is no RegistryAuth (eg: command line tools)
+ protected ?string $actor;
/**
- * Constructor.
+ * Constructor. Either a RegistryAuthComponent (for web and API requests) or
+ * a fixed actor identifier (for command line tools) should be provided.
*
* @since COmanage Registry v5.0.0
- * @param RegistryAuthComponent $Auth RegistryAuthComponent
+ * @param RegistryAuthComponent|null $Auth RegistryAuthComponent
+ * @param string|null $actor Actor identifier, used if $Auth is not provided (since v5.4.0)
*/
- public function __construct(RegistryAuthComponent $Auth) {
+ public function __construct(?RegistryAuthComponent $Auth = null, ?string $actor = null) {
$this->RegistryAuth = $Auth;
+ $this->actor = $actor;
+ }
+
+ /**
+ * Inject the actor information into the save options.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param ArrayObject $options Save options
+ */
+
+ protected function setActorOptions(\ArrayObject $options): void {
+ if($this->RegistryAuth) {
+ $options['actor'] = $this->RegistryAuth->getAuthenticatedUser();
+ $options['apiuser'] = $this->RegistryAuth->isApiUser();
+ } elseif(!empty($this->actor)) {
+ $options['actor'] = $this->actor;
+ $options['apiuser'] = false;
+ }
}
/**
@@ -61,14 +84,9 @@ public function __construct(RegistryAuthComponent $Auth) {
*/
public function beforeMarshal(EventInterface $event, \ArrayObject $data, \ArrayObject $options) {
- // Tweak the options so HistoryRecords and similar models can see who performed the save
-
- if($this->RegistryAuth) {
- $options['actor'] = $this->RegistryAuth->getAuthenticatedUser();
- $options['apiuser'] = $this->RegistryAuth->isApiUser();
-
- // We don't autocalculate the actor_person_id here because most models won't need it
- }
+ // Tweak the options so HistoryRecords and similar models can see who performed the save.
+ // We don't autocalculate the actor_person_id here because most models won't need it.
+ $this->setActorOptions($options);
}
/**
@@ -82,11 +100,7 @@ public function beforeMarshal(EventInterface $event, \ArrayObject $data, \ArrayO
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options) {
// Tweak the options so ChangelogBehavior can see who performed the save
-
- if($this->RegistryAuth) {
- $options['actor'] = $this->RegistryAuth->getAuthenticatedUser();
- $options['apiuser'] = $this->RegistryAuth->isApiUser();
- }
+ $this->setActorOptions($options);
}
/**
diff --git a/app/src/Lib/Util/EventUtilities.php b/app/src/Lib/Util/EventUtilities.php
new file mode 100644
index 000000000..a6b751b3f
--- /dev/null
+++ b/app/src/Lib/Util/EventUtilities.php
@@ -0,0 +1,97 @@
+off(self::$actorListener);
+ }
+
+ if(self::$ruleBuilderListener !== null) {
+ $EventManager->off(self::$ruleBuilderListener);
+ }
+
+ self::$actorListener = new ActorEventListener($auth, $actor);
+ $EventManager->on(self::$actorListener);
+
+ self::$ruleBuilderListener = new RuleBuilderEventListener();
+ $EventManager->on(self::$ruleBuilderListener);
+ }
+}
diff --git a/app/src/Model/Table/ClustersTable.php b/app/src/Model/Table/ClustersTable.php
index 910c9aa48..8a5f9616f 100644
--- a/app/src/Model/Table/ClustersTable.php
+++ b/app/src/Model/Table/ClustersTable.php
@@ -152,6 +152,62 @@ public function assign(int $personId): array {
return $ret;
}
+ /**
+ * Obtain the Clusters that map a Group. Each Cluster Plugin may optionally
+ * implement groupClusters(Cluster $cluster, int $groupId), returning an empty
+ * array if the Group is not mapped, or an array with a 'link' (URL array) and
+ * an optional 'comment'. Plugins that do not implement it are skipped. The
+ * returned 'comment' also notes the Cluster's status if it is not Active.
+ *
+ * @since COmanage Registry v5.4.0
+ * @param int $groupId Group ID
+ * @return array Array of Clusters mapping the Group, each with 'cluster', 'link' and 'comment' keys
+ */
+
+ public function groupClusters(int $groupId): array {
+ $ret = [];
+
+ // First we need the CO for the Group
+ $group = $this->Cos->Groups->get($groupId);
+
+ // Suspended Clusters are included, since their mappings still exist
+ $clusters = $this->find()
+ ->where(['co_id' => $group->co_id])
+ ->contain($this->getPluginRelations())
+ ->orderBy(['description' => 'ASC'])
+ ->all();
+
+ foreach($clusters as $cluster) {
+ $Plugin = TableRegistry::getTableLocator()->get($cluster->plugin);
+
+ if(!method_exists($Plugin, 'groupClusters')) {
+ continue;
+ }
+
+ $mapping = $Plugin->groupClusters($cluster, $groupId);
+
+ if(!empty($mapping)) {
+ $notes = [];
+
+ if(!empty($mapping['comment'])) {
+ $notes[] = $mapping['comment'];
+ }
+
+ if($cluster->status != SuspendableStatusEnum::Active) {
+ $notes[] = __d('enumeration', 'SuspendableStatusEnum.' . $cluster->status);
+ }
+
+ $ret[] = [
+ 'cluster' => $cluster,
+ 'link' => $mapping['link'] ?? null,
+ 'comment' => !empty($notes) ? implode(', ', $notes) : null
+ ];
+ }
+ }
+
+ return $ret;
+ }
+
/**
* Obtain Cluster status for a Person.
*
diff --git a/app/src/Model/Table/GroupsTable.php b/app/src/Model/Table/GroupsTable.php
index 4b0507ecf..0b4554a9d 100644
--- a/app/src/Model/Table/GroupsTable.php
+++ b/app/src/Model/Table/GroupsTable.php
@@ -1104,6 +1104,25 @@ public function localAfterSave(EventInterface $event, EntityInterface $entity, \
* 'identifier' => 'council-faculty',
* 'status' => 'A'
* ]
+ * ],
+ *
+ * // Dynamically injected by Cluster plugins (eg: UnixCluster, if configured & active),
+ * // Eligible Groups only. One entry per Unix Cluster that maps this Group, if the Group
+ * // is usable there. See UnixClustersTable::marshalGroupProvisioningData().
+ * 'unix_cluster_groups' => [
+ * [
+ * 'id' => 14,
+ * 'unix_cluster_id' => 19,
+ * 'group_id' => 57,
+ * 'origin' => 'M', // Manual ('M') or Personal ('P')
+ * 'person_id' => null,
+ * 'group' => ['id' => 57, 'name' => 'Faculty Council', 'identifiers' => [...]],
+ * 'cluster_id' => 3, // Derived: core Cluster ID
+ * 'scope' => 'hpc-cluster', // Derived: Unix Cluster label
+ * 'group_name' => 'council-faculty', // Derived: Group Name Identifier
+ * 'gid_number' => '30001', // Derived: GID Identifier
+ * 'member_uids' => ['jdoe', 'rsmith'] // Derived: usernames of the members' Accounts
+ * ]
* ]
* ]
* ]
@@ -1158,13 +1177,49 @@ public function marshalProvisioningData(int $id): array {
$identifiers = [];
- foreach($ret['data']->identifiers as $id) {
- if($id->status == SuspendableStatusEnum::Active) {
- $identifiers[] = $id;
+ foreach($ret['data']->identifiers as $identifier) {
+ if($identifier->status === SuspendableStatusEnum::Active) {
+ $identifiers[] = $identifier;
}
}
$ret['data']->identifiers = $identifiers;
+
+ // Cluster Plugins may provide data for provisioning the Group (eg: the
+ // Unix group name, GID and member usernames of a Unix Cluster Group).
+ // This is opt-in: plugins that don't implement marshalGroupProvisioningData()
+ // are skipped. We use the returned entity name as its key in the data.
+
+ $Clusters = TableRegistry::getTableLocator()->get('Clusters');
+
+ $clusters = $Clusters->find()
+ ->where([
+ 'co_id' => $ret['data']->co_id,
+ 'status' => SuspendableStatusEnum::Active
+ ])
+ ->contain($Clusters->getPluginRelations())
+ ->all();
+
+ foreach($clusters as $cluster) {
+ $CPlugin = TableRegistry::getTableLocator()->get($cluster->plugin);
+
+ if(!method_exists($CPlugin, 'marshalGroupProvisioningData')) {
+ continue;
+ }
+
+ $pluginData = $CPlugin->marshalGroupProvisioningData($cluster, $ret['data']->id);
+
+ foreach($pluginData as $pluginModelName => $entityData) {
+ $entityKey = \Cake\Utility\Inflector::tableize($pluginModelName);
+
+ if(!empty($ret['data']->$entityKey)) {
+ // Merge the results of multiple instantiations of the same plugin
+ $ret['data']->$entityKey = array_merge($ret['data']->$entityKey, $entityData);
+ } else {
+ $ret['data']->$entityKey = $entityData;
+ }
+ }
+ }
} else {
$ret['eligibility'] = ProvisioningEligibilityEnum::Ineligible;
// For Ineligible records, we remove the group memberships, and
@@ -1174,8 +1229,8 @@ public function marshalProvisioningData(int $id): array {
$identifiers = [];
- foreach($ret['data']->identifiers as $id) {
- if($id->status == SuspendableStatusEnum::Active) {
+ foreach($ret['data']->identifiers as $identifier) {
+ if($identifier->status === SuspendableStatusEnum::Active) {
$identifiers[] = $id;
}
}
@@ -1190,10 +1245,10 @@ public function marshalProvisioningData(int $id): array {
* Assemble the set of potential parent Groups.
*
* @since COmanage Registry v5.2.0
- * @param int $coId CO ID
- * @param int $id Group ID to determine potential parents of, or null for any (or a new) Group
- * @param bool $hierarchy Render the hierarchy in the name
- * @param array $where Additional conditions for filtering potential parents
+ * @param int $coId CO ID
+ * @param int|null $id Group ID to determine potential parents of, or null for any (or a new) Group
+ * @param bool $hierarchy Render the hierarchy in the name
+ * @param array $where Additional conditions for filtering potential parents
* @return array Array of Group IDs and Group Names
* @todo Make a TreeTrait and move the function there
*/
@@ -1225,11 +1280,12 @@ public function potentialParents(
* Reconcile the members of an automatic or nested Group.
*
* @since COmanage Registry v5.0.0
- * @param int $id Group ID
- * @param Job $job Job entity, if in Job context
+ * @param int $id Group ID
+ * @param Job|null $job Job entity, if in Job context
*/
- public function reconcile(int $id, ?Job $job=null) {
+ public function reconcile(int $id, ?Job $job=null): void
+ {
$group = $this->get($id);
if($group->isAutomatic()) {
@@ -1244,7 +1300,7 @@ public function reconcile(int $id, ?Job $job=null) {
*
* @since COmanage Registry v5.0.0
* @param EntityInterface $entity Group
- * @param Job $job Job entity, if in Job context
+ * @param Job|null $job Job entity, if in Job context
*/
protected function reconcileAutomaticGroup(
@@ -1348,7 +1404,7 @@ protected function reconcileAutomaticGroup(
*
* @since COmanage Registry v5.0.0
* @param EntityInterface $entity Group
- * @param Job $job Job entity, if in Job context
+ * @param Job|null $job Job entity, if in Job context
*/
protected function reconcileNestedMemberships(
diff --git a/app/src/Model/Table/PeopleTable.php b/app/src/Model/Table/PeopleTable.php
index 278dd3a31..5c13b804f 100644
--- a/app/src/Model/Table/PeopleTable.php
+++ b/app/src/Model/Table/PeopleTable.php
@@ -754,6 +754,43 @@ public function localAfterSave(\Cake\Event\EventInterface $event, \Cake\Datasour
* 'locked' => false
* ]
* ]
+ * ],
+ *
+ * // Dynamically injected by Cluster plugins (eg: UnixCluster, if configured & active).
+ * // Only Active/Grace Period Accounts, and the usable Unix Cluster Groups the Person
+ * // is a member of. See UnixClustersTable::marshalProvisioningData().
+ * 'unix_cluster_accounts' => [
+ * [
+ * 'id' => 1601,
+ * 'unix_cluster_id' => 19,
+ * 'person_id' => 101,
+ * 'sync_mode' => 'F',
+ * 'status' => 'A',
+ * 'username' => 'jdoe',
+ * 'uid' => 6030,
+ * 'gecos' => 'Jane Doe',
+ * 'login_shell' => '/bin/bash',
+ * 'home_directory' => '/home/j/d/jdoe',
+ * 'primary_group_id' => 57,
+ * 'primary_group' => ['id' => 57, 'name' => 'jdoe UnixCluster Group', 'identifiers' => [...]],
+ * 'cluster_id' => 3, // Derived: core Cluster ID
+ * 'scope' => 'hpc-cluster', // Derived: Unix Cluster label
+ * 'gid_number' => '6030' // Derived: GID Identifier of the Primary Group
+ * ]
+ * ],
+ * 'unix_cluster_groups' => [
+ * [
+ * 'id' => 14,
+ * 'unix_cluster_id' => 19,
+ * 'group_id' => 57,
+ * 'origin' => 'P', // Personal
+ * 'person_id' => 101,
+ * 'group' => ['id' => 57, 'name' => 'jdoe UnixCluster Group', 'identifiers' => [...]],
+ * 'cluster_id' => 3,
+ * 'scope' => 'hpc-cluster',
+ * 'group_name' => 'jdoe', // Derived: Group Name Identifier
+ * 'gid_number' => '6030' // Derived: GID Identifier
+ * ]
* ]
* ]
* ]
diff --git a/app/templates/Clusters/fields.inc b/app/templates/Clusters/fields.inc
index 248df8e28..cdaa99f7a 100644
--- a/app/templates/Clusters/fields.inc
+++ b/app/templates/Clusters/fields.inc
@@ -33,4 +33,26 @@ $fields = [
]
];
-$subnav = 'standard';
+// Cluster plugins may define child models (eg Unix Cluster Groups and Unix Cluster
+// Accounts), each of which gets its own tab, in the same order as the plugin's own
+// pages. A Hierarchy tab can't be used here since it only links the first child model.
+if(!empty($vv_obj['plugin'])) {
+ $subnav = [
+ 'tabs' => ['Clusters', 'Clusters.Plugin'],
+ 'action' => [
+ 'Clusters' => ['edit'],
+ 'Clusters.Plugin' => ['edit']
+ ],
+ 'counter' => [],
+ ];
+
+ foreach($this->Tab->getHasManyAssociationModels($vv_obj['plugin']) as $childModel) {
+ if(!empty($childModel) && $this->Tab->modelSupportsView($childModel)) {
+ $subnav['tabs'][] = $childModel;
+ $subnav['action'][$childModel] = ['index'];
+ $subnav['counter'][] = $childModel;
+ }
+ }
+} else {
+ $subnav = 'standard';
+}
diff --git a/app/templates/Groups/fields.inc b/app/templates/Groups/fields.inc
index 69dc693de..adc49e0ba 100644
--- a/app/templates/Groups/fields.inc
+++ b/app/templates/Groups/fields.inc
@@ -72,6 +72,16 @@ if($vv_action != 'add') {
'labelIsTextOnly' => true
];
}
+
+ // Link to the Clusters that map this Group (see GroupsController::beforeRender)
+ if(!empty($vv_group_clusters)) {
+ $fields['clusters'] = [
+ 'fieldLabel' => __d('controller', 'Clusters', [99]),
+ 'fieldDescription' => __d('field', 'Groups.clusters.desc'),
+ 'status' => $this->element('groupClusters', ['groupClusters' => $vv_group_clusters]),
+ 'labelIsTextOnly' => true
+ ];
+ }
}
// List the MVEAs that may be shown on the mveaCanvas
diff --git a/app/templates/element/form/unorderedList.php b/app/templates/element/form/unorderedList.php
index 5403325be..d446726a8 100644
--- a/app/templates/element/form/unorderedList.php
+++ b/app/templates/element/form/unorderedList.php
@@ -43,8 +43,12 @@
if(!empty($vv_fields)) {
// Output the visible fields from the fields.inc configuration
foreach($vv_fields as $key => $field) {
- if($key === 'SUBTITLE' || $key === 'HTML') {
- if($key === 'SUBTITLE') {
+ // Pseudo-fields may be suffixed (eg "SUBTITLE.account") so that a single
+ // configuration can define more than one of them
+ $pseudoField = is_string($key) ? explode('.', $key, 2)[0] : null;
+
+ if($pseudoField === 'SUBTITLE' || $pseudoField === 'HTML') {
+ if($pseudoField === 'SUBTITLE') {
// We have a subtitle
$content = $field['subtitle'];
$type = 'subtitle';
diff --git a/app/templates/element/groupClusters.php b/app/templates/element/groupClusters.php
new file mode 100644
index 000000000..c829b8f4e
--- /dev/null
+++ b/app/templates/element/groupClusters.php
@@ -0,0 +1,50 @@
+ Cluster, 'link' => URL array or null, 'comment' => string or null],
+ * ];
+ *
+ * @link https://www.internet2.edu/comanage COmanage Project
+ * @package registry
+ * @since COmanage Registry v5.4.0
+ * @license Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
+ */
+
+declare(strict_types = 1);
+
+$lines = [];
+
+foreach($groupClusters ?? [] as $gc) {
+ $label = (string)$gc['cluster']->description;
+
+ $line = !empty($gc['link']) ? $this->Html->link($label, $gc['link']) : h($label);
+
+ if(!empty($gc['comment'])) {
+ $line .= ' (' . h($gc['comment']) . ')';
+ }
+
+ $lines[] = $line;
+}
+
+print implode('
', $lines);
diff --git a/app/templates/element/menuPanel.php b/app/templates/element/menuPanel.php
index 06790a0cf..fb6e3e36a 100644
--- a/app/templates/element/menuPanel.php
+++ b/app/templates/element/menuPanel.php
@@ -111,6 +111,22 @@
+
+ Url->build([
+ 'plugin' => null,
+ 'controller' => 'clusters',
+ 'action' => 'index',
+ '?' => [
+ 'co_id' => $vv_cur_co->id
+ ]
+ ]);
+ ?>
+
+ dns
+
+
+
Url->build(
@@ -457,6 +473,22 @@
+
+ Url->build([
+ 'plugin' => null,
+ 'controller' => 'clusters',
+ 'action' => 'index',
+ '?' => [
+ 'co_id' => $vv_cur_co->id
+ ]
+ ]);
+ ?>
+
+ dns
+
+
+
filter_list Data Filters
sync External Identity Sources