rc-1.0.x-dev/modules/rc_group/src/Services/RcGroup.php
modules/rc_group/src/Services/RcGroup.php
<?php
namespace Drupal\rc_group\Services;
use ATDev\RocketChat\Groups\Group;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Config\FileStorage;
use Drupal\Core\Logger\LoggerChannelFactory;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\rc_group\Groups\GroupRc;
use ATDev\RocketChat\Users\User;
use ATDev\RocketChat\Roles\Role;
/**
* Class RcGroup.
*
* Groups in Rocket chat are the private channels (rooms).
*/
class RcGroup {
/**
* @var object
*/
protected object $user;
/**
* @var mixed
*/
protected $rcUser;
/**
* The module configuration.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
protected $config;
/**
* The logging service.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* @param Drupal\Core\Config\ConfigFactory $config_factory
*
* @param \Drupal\Core\Logger\LoggerChannelFactory $logger_factory
* The logging service.
*/
protected $rcAuth;
/**
* @var string[]
*/
protected array $userRoles;
/**
* @param \Drupal\Core\Config\ConfigFactory $config_factory
* @param \Drupal\Core\Logger\LoggerChannelFactory $logger_factory
*/
public function __construct(
ConfigFactory $config_factory,
LoggerChannelFactory $logger_factory) {
$this->config = $config_factory->get('rc.settings');
$this->logger = $logger_factory->get('rc');
$this->rcAuth = \Drupal::service('rc.auth');
$this->rcUser = \Drupal::service('rc.user');
$this->userRoles = ['owner', 'moderator'];
}
/**
* Validate the Drupal group name to fulfill the Rocket Chat room naming
* convention.
*
* @param string $groupName
*
* @return string
*/
public function validateGroupName(string $groupName): string {
return preg_replace("![^a-z0-9]+!i", "", ucwords($groupName));
}
/**
* Get Rocket Chat room info.
*
* @param object $group
*
* @return \ATDev\RocketChat\Groups\Group|bool|void
*/
public function groupInfo(object $group) {
// Login to Rocket Chat server as admin.
if ($this->rcUser->loginRcAdmin()) {
// Get room ID from field.
$rcRoomId = $group->field_rc_room_id->value;
// If room ID is not set try by valid group name.
if (!$rcRoomId) {
$groupName = $group->label();
$rcRoomId = $this->validateGroupName($groupName);
}
// Initiate getting group info.
$rcGroup = new GroupRc($rcRoomId);
// Get the result.
$result = $rcGroup->info();
// Log error if no result.
if (!$result) {
// Log the error.
$this->logger->error($rcGroup->getError());
return;
}
return $result;
}
}
// /**
// * @param object $group
// *
// * @return array the ID of the array is the Drupal group ID and the value is
// * the Rocket Chat
// * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
// * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
// */
// public function checkIfGroupWithSameNameExists(object $group) {
// // Check if a group with the same title exists. This will determine if we
// // have to do a deeper checking while creating a new chat group.
// $drupalGroupName = $group->label();
// $query = \Drupal::entityQuery('group');
// $query->condition('label', $drupalGroupName);
// $drupalGroupIds = $query->execute();
// if ($drupalGroupIds) {
// $rcGroupsNames = [];
// foreach ($drupalGroupIds as $rcGroupsName) {
// $drupalGroup = \Drupal::entityTypeManager()
// ->getStorage('group')->load($rcGroupsName);
// $groupInfo = $this->groupInfo($drupalGroup);
// if ($groupInfo) {
// $rcGroupsNames[] = ['rc_room_name' => $groupInfo->getName()];
// }
// if ($rcGroupsNames) {
// return $rcGroupsNames;
// }
// }
// }
//
// }
/**
* This method check if the Rocket Chat group exists. If exists, it returns
* a list of all rocket chat room (channel) names in an array.
*
* @param $group
*
* @return array
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function checkIfGroupExists(object $group) {
// Login as Admin.
if ($this->rcUser->loginRcAdmin()) {
// Get a list of all Rocket Chat rooms.
$listAll = Group::listAll();
// Log error if the request is not successful.
if (!$listAll) {
$error = Group::getError();
$this->logger
->error('Rocket Chat error adding group owner: ' . $error);
return;
}
// Get group name.
$drupalGroupLabel = $group->label();
// Validate group name to match rocket chat channels naming convention.
$drupalGroupName = $this->validateGroupName($drupalGroupLabel);
// Get all Rocket Chat groups names.
$allGroupsNames = [];
$allGroups = $listAll->getValues();
// @todo replace foreach with array_column.
foreach ($allGroups as $group) {
$groupName = $group->getName();
$allGroupsNames[] = $groupName;
}
// Check if room exists in the array.
if (in_array($drupalGroupName, $allGroupsNames)) {
return $allGroupsNames;
}
}
}
/**
* This methode checks if a user is a member in a Rocket Chat room.
*
* @param object $user
* @param object $group
*
* @return bool|void
*/
public function checkIfMemberInGroup(object $user, object $group) {
// Login as an admin.
if ($this->rcUser->loginRcAdmin()) {
// Get all members in a room.
$rcGroupMembers = $this->groupMembersList($group);
// Return if can't get a list of members.
if (!$rcGroupMembers) {
return;
}
// Get the Rocket Chat members names.
$rcMembers = $rcGroupMembers->getValues();
// Get the user ID from Rocket Chat ID field.
$userId = $user->field_rcid->value;
// Check if the user is a member in the room.
$members = [];
foreach ($rcMembers as $member) {
$members[] = $member->getUserId();
}
if (in_array($userId, $members)) {
return TRUE;
}
}
}
/**
* This method gets a list of Rocket Chat room's members.
*
* @param object $group
*
* @return \ATDev\RocketChat\Users\Collection|void
*/
public function groupMembersList(object $group) {
// Get the Rocket Chat room id from group entity field.
$rcGroupId = $group->field_rc_room_id->value;
// Initiate request.
$rcGroup = new Group($rcGroupId);
// Get results.
$result = $rcGroup->members();
// Log errors if no results.
if (!$result) {
$error = $rcGroup->getError();
\Drupal::messenger()->addStatus('Rocket chat error while listing group members ' . $error);
return;
}
return $result;
}
/**
* This method generate a unique Rocket Chat room name if a room
* with a similar name exists.
*
* @param string $groupName
* @param array $roomNames
*
* @return string
*/
public function uniqueGroupName(string $groupName, array $roomNames) {
// Rocket chat only accepts unique room (Channel) ID. Generating unique
// room names of Drupal groups with the same name exists.
$i = 0;
do {
$groupNameArray = explode('-', $groupName);
$groupName = $groupNameArray[0];
$groupName = $groupName . '-' . $i;
$i++;
} while (in_array($groupName, $roomNames));
return $groupName;
}
/**
* This method creates Rocket Chat room that is associated with Drupal group
* WITHOUT saving the group entity by default to be used with preprocess
* hooks e.g. HOOK_group_presave, HOOK_group_predelete, while the option to
* save is available to be used with custom hooks and functions.
*
* @param object $group
* @param bool $save
*
* @return \ATDev\RocketChat\Groups\Group|bool|void
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function createGroup(object $group, bool $save = FALSE) {
// Prepare the needed data to create the room.
$groupOwner = $group->getOwner();
$groupLabel = $group->label();
$groupName = $this->validateGroupName($groupLabel);
// Check if user exists.
if (!$this->rcUser->checkIfUserExist($groupOwner)) {
$this->rcUser->createUser($groupOwner, TRUE);
}
// Login with group author account.
if ($this->rcUser->loginUserByName($groupOwner)) {
// Get owner Rocket Chat ID from field.
$groupOwnerId = $groupOwner->field_rcid->value;
// Check if a group with the same name exists.
$checkIfGroupExists = $this->checkIfGroupExists($group);
// If the room exists, generate a unique room name.
if ($checkIfGroupExists) {
$groupName = $this->uniqueGroupName($groupName, $checkIfGroupExists);
}
// Creating new groups.
$rcGroup = new Group();
$rcGroup->setName($groupName);
$rcGroup->setReadOnlyValue(FALSE);
$result = $rcGroup->create();
if (!$result) {
// Log the error.
$error = $rcGroup->getError();
\Drupal::messenger()->addStatus('Rocket chat error while creating group ' . $error);
return;
}
// Invite group owner to the chat group and ser as owner.
$rcId = new User($groupOwner->field_rcid->value);
$rcGroupInvite = new Group($rcGroup->getRoomId());
$rcGroupInvite->invite($rcId);
$rcGroupInvite->addOwner($rcId);
// Save the room ID in the group entity.
$group->field_rc_room_id->value = $result->getGroupId();
if ($save) {
// Save the group entity.
$group->save();
}
\Drupal::messenger()->addStatus('Chat group has been created as ' . $result->getName() . ' for ' . $groupLabel);
return $result;
}
}
/**
* This method adds the Rocket Chat room ID field to the group entity type.
* It is used in Chat group settings form.
*
* @param string $entity
* @param string $bundle
* @param string $fieldName
* @param string $label
* @param bool $required
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @throws \Drupal\Core\Entity\EntityStorageException
*/
public function createRcRoomIdField(
string $entity,
string $bundle,
string $fieldName,
string $label,
bool $required = FALSE
) {
// Create field_rc_room_id storage config if it does not exist.
$roomIdFieldStorage = FieldStorageConfig::loadByName($entity, $fieldName);
// Create field storage if it does not exist.
if (!$roomIdFieldStorage) {
$configDirectory = new FileStorage(\Drupal::service('extension.list.module')->getPath('rc_group') . '/config/install');
// Import the field from the associated config file.
$rcRoomIdConfig = $configDirectory
->read('field.storage.group.' . $fieldName);
FieldStorageConfig::create($rcRoomIdConfig)
->save();
}
// Load field by name.
$field = FieldConfig::loadByName($entity, $bundle, $fieldName);
if (empty($field)) {
// Define the field entity.
FieldConfig::create(
[
'field_name' => $fieldName,
'entity_type' => $entity,
'bundle' => $bundle,
'label' => $label,
'required' => $required,
'translatable' => TRUE,
]
)->save();
// Set message.
$message = t(
"Field @a created in bundle @b.",
['@a' => $label, '@b' => $bundle]
);
\Drupal::messenger()->addStatus($message);
// Assign widget settings for the 'default' form mode.
$entityTypeManager = \Drupal::entityTypeManager();
$displayForm = $entityTypeManager
->getStorage('entity_form_display')
->load($entity . '.' . $bundle . '.default');
if ($displayForm) {
$displayForm
->setComponent($fieldName, [
'type' => 'string_textfield',
'weight' => 999,
]);
$displayForm->save();
$message = t(
"The form display of @a in bundle @b is set",
['@a' => $fieldName, '@b' => $bundle]
);
\Drupal::messenger()->addStatus($message);
}
else {
$message = t(
"The form display of @a in bundle @b could not be set",
['@a' => $fieldName, '@b' => $bundle]
);
\Drupal::messenger()->addWarning($message);
}
unset($displayForm);
// Assign display settings for the 'default' view modes.
$displayDefault = $entityTypeManager
->getStorage('entity_view_display')
->load('group.' . $bundle . '.default');
if ($displayDefault) {
$displayDefault->removeComponent($fieldName);
$displayDefault->save();
// Set a message.
$message = t(
"The default display of @a in bundle @b is set",
['@a' => $fieldName, '@b' => $bundle]
);
\Drupal::messenger()->addStatus($message);
}
else {
$message .= t(
"The default display of @a in bundle @b could not be set",
['@a' => $fieldName, '@b' => $bundle]
);
\Drupal::messenger()->addWarning($message);
}
unset($displayDefault);
}
else {
$message = t(
"Field @a already exists in bundle @b.",
['@a' => $fieldName, '@b' => $bundle]
);
\Drupal::messenger()->addWarning($message);
}
}
/**
* This method rename the RC channel.
*
* @param object $group
*
* @return \ATDev\RocketChat\Groups\Group|void
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function renameGroup(object $group) {
// Get the Rocket Chat room ID from field.
$roomId = $group->field_rc_room_id->value;
// Get the room owner from Drupal author Rocket Chat ID field.
$groupOwner = $group->getOwner();
// Get and validate the new room name.
$groupLabel = $group->label();
$groupName = $this->validateGroupName($groupLabel);
// Login with group author account.
if ($this->rcUser->loginUserByName($groupOwner)) {
$checkIfGroupExists = $this->checkIfGroupExists($group);
if ($checkIfGroupExists) {
$groupName = $this->uniqueGroupName($groupName, $checkIfGroupExists);
}
if ($roomId) {
$group = new Group($roomId);
$result = $group->rename($groupName);
if (!$result) {
$error = $group->getError();
$this->logger->error('Rocket Chat error while renaming the group ' . $groupLabel . ' : ' . $error);
return;
}
\Drupal::messenger()->addStatus('Chat group name has been created as ' . $result->getName() . ' for ' . $groupLabel);
return $result;
}
}
}
/**
* @param object $group
*
* @return \ATDev\RocketChat\Groups\Group|bool|void
*/
public function deleteGroup(object $group) {
// Get the Rocket Chat room ID from field.
$roomId = $group->field_rc_room_id->value;
// Login as admin.
if ($this->rcUser->loginRcAdmin()) {
if ($roomId) {
$rcGroup = new Group($roomId);
$result = $rcGroup->delete();
if (!$result) {
// Log the error.
$error = $rcGroup->getError();
$this->logger->error('Rocket Chat error while deleting a group: ' . $error);
return;
}
\Drupal::messenger()->addStatus('Chat group' . $result->getName() . ' has been deleted');
return $result;
}
}
}
/**
* This method add user to a Rocket Chat room. The owner of the room
* is used to add the user to the room.
*
* @param object $groupOwner
* @param object $user
* @param object $group
*
* @return \ATDev\RocketChat\Groups\Group|bool|void
*/
public function groupInviteUser(object $groupOwner, object $user, object $group) {
// Login as a room owner.
if ($this->rcUser->loginUserByName($groupOwner)) {
// Get user Rocket Chat ID from field.
$rcUser = new User($user->field_rcid->value);
// Get Rocket Chat room ID from field.
$rcGroup = new Group($group->field_rc_room_id->value);
$result = $rcGroup->invite($rcUser);
if (!$result) {
// Log the error.
$error = $rcGroup->getError();
$this->logger->error('Rocket Chat error while adding user to a group: ' . $error);
return;
}
\Drupal::messenger()->addStatus($user->label() . ' is added to ' . $group->label() . ' chat group.');
return $result;
}
}
/**
* This method add user to a Rocket Chat room. The Rocket Chat admin account
* is used to add the user to the room. This is helpful when permissions does
* not allow owners or other roles to add user to a room.
*
* @param object $groupOwner
* @param object $user
* @param object $group
*
* @return \ATDev\RocketChat\Groups\Group|bool|void
*/
public function groupInviteUserByAdmin(object $groupOwner, object $user, object $group) {
// Login as an admin.
if ($this->rcUser->loginRcAdmin()) {
// Get the Rocket Chat User ID from field.
$rcUserId = $user->field_rcid->value;
$rcUser = new User($rcUserId);
// Get the Rocket Chat room ID from field.
$rcRoomId = $group->field_rc_room_id->value;
// Add user to room.
$rcGroup = new Group($group->field_rc_room_id->value);
$result = $rcGroup->invite($rcUser);
if (!$result) {
// Log the error.
$error = $rcGroup->getError();
$this->logger->error('Rocket Chat error while adding user to a group: ' . $error);
return;
}
\Drupal::messenger()->addStatus($user->label() . ' is added to ' . $group->label() . ' chat group.');
return $result;
}
}
/**
* This method removes user from a room using the room owner account or admin account.
*
* @param object $groupOwner
* @param object $user
* @param object $group
*
* @return \ATDev\RocketChat\Groups\Group|bool|void
*/
public function groupKickUser(object $groupOwner, object $user, object $group) {
// The Drupal group member who holds an Owner account on Rocket chat group
// cannot remove his/her account from the group. If that member leaves the
// Drupal group or removed, the Rocket Chat admin account will be used to
// kick the member out of the Rocket chat group.
if ($groupOwner->field_rcid->value == $user->field_rcid->value) {
$loginUser = $this->rcUser->loginRcAdmin();
}
else {
$loginUser = $this->rcUser->loginUserByName($groupOwner);
}
if ($loginUser) {
// Get the chat account using Rocket Chat User ID field.
$rcUser = new User($user->field_rcid->value);
// Get the room using Rocket Chat room ID field.
$rcGroup = new Group($group->field_rc_room_id->value);
$result = $rcGroup->kick($rcUser);
if (!$result) {
// Log the error.
$error = $rcGroup->getError();
$this->logger->error('Rocket Chat error while removing user from a group: ' . $error);
return;
}
\Drupal::messenger()->addStatus($user->label() . ' is removed from ' . $group->label() . ' chat group.');
return $result;
}
}
/**
* This method add an owner roll to the user. The Drupal group author account
* is used to add the user to the room.
*
* @param object $groupOwner
* @param object $user
* @param object $group
*
* @return \ATDev\RocketChat\Groups\Group|bool|void
*/
public function groupAddOwner(object $groupOwner, object $user, object $group) {
// Login with Group author account.
if ($this->rcUser->loginUserByName($groupOwner)) {
// Get the chat account using Rocket Chat User ID field.
$rcUser = new User($user->field_rcid->value);
// Get the room using Rocket Chat room ID field.
$rcGroup = new Group($group->field_rc_room_id->value);
$result = $rcGroup->addOwner($rcUser);
if (!$result) {
// Log the error.
$error = $rcGroup->getError();
$this->logger->error('Rocket Chat error adding group owner: ' . $error);
return;
}
\Drupal::messenger()->addStatus($user->label() . ' is added as a chat group owner.');
return $result;
}
}
/**
* This method add an owner roll to the user. The Rocket Chat admin account
* is used to add the user to the room. This is helpful while creating
* a new room as the owner will not be set directly while the creation
* and must be set by the admin.
*
* @param object $group
* @param string $rcGroupId
*/
public function groupAddOwnerByAdmin(object $user, object $group) {
// Login as admin.
if ($this->rcUser->loginRcAdmin()) {
// Get the chat account using Rocket Chat User ID field.
$rcUserId = $user->field_rcid->value;
$rcUser = new User($rcUserId);
// Get the room using Rocket Chat room ID field.
$rcGroup = new Group($group->field_rc_room_id->value);
$result = $rcGroup->addOwner($rcUser);
if (!$result) {
// Log the error.
$error = $rcGroup->getError();
$this->logger->error('Rocket Chat error adding group owner: ' . $error);
return;
}
\Drupal::messenger()->addStatus($user->label() . ' is added as a chat group owner.');
return $result;
}
}
/**
* Remove the owner role from a user in a room using the Drupal group author account.
*
* @param object $groupOwner
* @param object $user
* @param object $group
*
* @return \ATDev\RocketChat\Groups\Group|bool|void
*/
public function GroupRemoveOwner(object $groupOwner, object $user, object $group) {
// Login with Drupal group author account.
if ($this->rcUser->loginUserByName($groupOwner)) {
// Get the chat account using Rocket Chat User ID field.
$rcUser = new User($user->field_rcid->value);
// Get the room using Rocket Chat room ID field.
$rcGroup = new Group($group->field_rc_room_id->value);
$result = $rcGroup->removeOwner($rcUser);
if (!$result) {
// Log the error.
$error = $rcGroup->getError();
$this->logger->error('Rocket Chat error while removing owner from a group: ' . $error);
return;
}
\Drupal::messenger()->addStatus($user->label() . ' role as chat owner is removed from ' . $group->label() . ' chat group .');
return $result;
}
}
/**
* Add moderator role to a user in a room using Drupal group author account.
*
* @param object $groupOwner
* @param object $user
* @param object $group
*
* @return \ATDev\RocketChat\Groups\Group|void
*/
public function groupAddModerator(object $groupOwner, object $user, object $group) {
// Login with Drupal group author account.
if ($this->rcUser->loginUserByName($groupOwner)) {
// Get the chat account using Rocket Chat User ID field.
$rcUser = new User($user->field_rcid->value);
// Get the room using Rocket Chat room ID field.
$rcGroup = new Group($group->field_rc_room_id->value);
$result = $rcGroup->addModerator($rcUser);
if (!$result) {
// Log the error.
$error = $rcGroup->getError();
$this->logger->error('Rocket Chat error adding group moderator: ' . $error);
return;
}
\Drupal::messenger()->addStatus($user->label() . ' is added as a chat group moderator.');
return $result;
}
}
/**
* Removes a moderator account from a user in a room using Drupal group author account.
*
* @param object $groupOwner
* @param object $user
* @param object $group
*
* @return \ATDev\RocketChat\Groups\Group|void
*/
public function groupRemoveModerator(object $groupOwner, object $user, object $group) {
// Login with Drupal group author account.
if ($this->rcUser->loginUserByName($groupOwner)) {
// Get the chat account using Rocket Chat User ID field.
$rcUser = new User($user->field_rcid->value);
// Get the room using Rocket Chat room ID field.
$rcGroup = new Group($group->field_rc_room_id->value);
$result = $rcGroup->removeModerator($rcUser);
if (!$result) {
// Log the error.
$error = $rcGroup->getError();
$this->logger->error('Rocket Chat error while removing moderator from a group: ' . $error);
return;
}
\Drupal::messenger()->addStatus($user->label() . ' role as chat owner is removed from ' . $group->label() . ' chat group .');
return $result;
}
}
/**
* This method updates the user roles in a room.
*
* @param object $groupContent
*/
public function groupUpdateUserRoles(object $groupContent) {
// Get the current user group roles.
$groupRoles = array_column($groupContent->group_roles
->getValue(), 'target_id');
// Get the original user group roles.
$originalGroupRoles = array_column($groupContent
->original->group_roles->getValue(), 'target_id');
// Check if the user group role is changed.
if ($groupRoles != $originalGroupRoles) {
// Get Group object.
$group = $groupContent->getGroup();
// Get the Group entity bundle.
$groupBundle = $group->bundle();
// Load the rc_group Groups class.
$rcGroup = \Drupal::service('rc_group.group');
// Get the groups settings from config.
$rcGroupSettings = \Drupal::config('rc_group.settings');
// Get the admin roles from config.
$adminRoles = array_diff($rcGroupSettings->get('groups_admin_roles.' . $groupBundle), ['0']);
// Get the moderator roles from config.
$moderatorRoles = array_diff($rcGroupSettings->get('groups_moderator_roles.' . $groupBundle), ['0']);
// If role is changed, point what is added and when is removed.
$removedRoles = array_diff($originalGroupRoles, $groupRoles);
$addedRoles = array_diff($groupRoles, $originalGroupRoles);
// Merge the changed roles for better code shortening.
$alteredRoles = array_merge($removedRoles, $addedRoles);
// Check if there are changed roles.
if (!empty($alteredRoles)) {
// Get the group owner object.
$owner = $groupContent->getOwner();
// Get the group user that is being changed.
$user = $groupContent->getEntity();
foreach ($alteredRoles as $alteredRole) {
// Check if role is in the Admin Roles.
$roleInAdminRoles = in_array($alteredRole, $adminRoles);
// Check if role is in the Moderator Roles.
$roleInModeratorRoles = in_array($alteredRole, $moderatorRoles);
// Check if role is added.
$roleInAddedRoles = in_array($alteredRole, $addedRoles);
// Check if role is removed.
$roleInRemovedRoles = in_array($alteredRole, $removedRoles);
// Check if user has another active admin or moderator roles other
// than the one that is being changed.
$userOtherGroupAdminRoles = [];
$userOtherGroupModeratorRoles = [];
foreach ($groupRoles as $groupRole) {
$groupFilteredRoles = array_diff($groupRoles, [$groupRole]);
foreach ($groupFilteredRoles as $filteredRole) {
if (in_array($filteredRole, $groupRoles)) {
$userOtherGroupAdminRoles[] = $filteredRole;
}
elseif (in_array($filteredRole, $groupRoles)) {
$userOtherGroupModeratorRoles[] = $filteredRole;
}
}
}
// Add Rocket Chat owner role to the user if the group role is mapped
// as an owner role.
if ($roleInAddedRoles && $roleInAdminRoles) {
$rcGroup->groupAddOwner($owner, $user, $group);
}
// Remove the Rocket Chat owner role from the user if the group role
// is mapped as an owner role and the user does not have any other
// owner role.
elseif ($roleInRemovedRoles && $roleInAdminRoles && empty($userOtherGroupAdminRoles)) {
$rcGroup->GroupRemoveOwner($owner, $user, $group);
}
// Add Rocket Chat moderator role to the user if the group role is
// mapped as a moderator role.
if ($roleInAddedRoles && $roleInModeratorRoles) {
$rcGroup->groupAddModerator($owner, $user, $group);
}
// Remove the Rocket Chat moderator role from the user if the group
// role is mapped as a moderator role and the user does not have any
// other moderator role.
elseif ($roleInRemovedRoles && $roleInModeratorRoles && empty($userOtherGroupModeratorRoles)) {
$rcGroup->groupRemoveModerator($owner, $user, $group);
}
}
}
}
}
/**
* @inheritDoc
*/
public function groupRolesListing() {
if ($this->rcUser->loginRcAdmin()) {
$listing = Role::listing()->getValues();
// $first = $listing[0]->getName;
if (!$listing) {
// Log the error.
$error = Role::getError();
$this->logger->error('Rocket Chat error while listing group roles: ' . $error);
return;
}
$roles = [];
foreach ($listing as $role) {
$roleArray = json_decode(json_encode($role, TRUE), TRUE);
if ($roleArray['scope'] = 'Subscriptions') {
$roles[] = $roleArray['name'];
}
}
return $roles;
}
}
/**
* @param object $groupOwner
* @param object $user
* @param object $group
*
* @return array|void
*/
public function groupUserRoles(object $groupOwner, object $user, object $group) {
// Login using Drupal group author account.
if ($this->rcUser->loginUserByName($groupOwner)) {
// Get the user Rocket Chat ID from field.
$rcId = $user->field_rcid->value;
// Get the Rocket Chat room ID from field.
$roomId = $group->field_rc_room_id->value;
$rcGroup = new Group($roomId);
// Get Rocket Chat roles.
$rcRoles = $rcGroup->roles()->getValues();
if (!$rcRoles) {
$error = $rcGroup->getError();
$this->logger->error('Rocket Chat error while listing group user roles: ' . $error);
return;
}
// Define Rocket Chat user roles array.
$userRoles = [];
foreach ($rcRoles as $rcRole) {
$rcUserId = $rcRole->getUser()->getUserId();
if ($rcUserId == $rcId) {
$userRoles[] = $rcRole->getRoles();
}
}
return $userRoles;
}
}
// Public function checkGroupUserRole(object $groupOwner, object $user, object $group, string $role) {
// if ($this->rcUser->loginUserByName($groupOwner)) {
// $rcId = $user->field_rcid->value;
// $roomId = $group->field_rc_room_id->value;
// $role = (new Role())->setName($role);
//
// $result = $role->getUsersInRole($roomId);
//
// if (!$result) {
// // Log the error
// $error = $role->getError();
// }
// else {
// $rcUserId = json_decode(json_encode($result->getValues() ,true),true);
// $test = $rcUserId;
// return $result;
// }
//
// }
// }.
}
