Generates HTML to display the users roles and any available actions

@param int $userid
@param array $roles
@param array $assignableroles
@param moodle_url $pageurl
@return string
434190
public function user_roles_and_actions($userid, $roles, $assignableroles, $canassign, $pageurl) {

        // Get list of roles.
        $rolesoutput = '';
        foreach ($roles as $roleid=>$role) {
            if ($canassign and (is_siteadmin() or isset($assignableroles[$roleid])) and !$role['unchangeable']) {
                $strunassign = get_string('unassignarole', 'role', $role['text']);
                $icon = $this->output->pix_icon('t/delete', $strunassign);
                $url = new moodle_url($pageurl, array('action'=>'unassign', 'roleid'=>$roleid, 'user'=>$userid));
                $rolesoutput .= html_writer::tag('div', $role['text'] . html_writer::link($url, $icon, array('class'=>'unassignrolelink', 'rel'=>$roleid, 'title'=>$strunassign)), array('class'=>'role role_'.$roleid));
            } else {
                $rolesoutput .= html_writer::tag('div', $role['text'], array('class'=>'role unchangeable', 'rel'=>$roleid));
            }
        }
        $output = '';
        if (!empty($assignableroles) && $canassign) {
            $roleids = array_keys($roles);
            $hasallroles = true;
            foreach (array_keys($assignableroles) as $key) {
                if (!in_array($key, $roleids)) {
                    $hasallroles = false;
                    break;
                }
            }
            if (!$hasallroles) {
                $url = new moodle_url($pageurl, array('action' => 'assign', 'user' => $userid));
                $roleicon = $this->output->pix_icon('i/assignroles', get_string('assignroles', 'role'));
                $link = html_writer::link($url, $roleicon, array('class' => 'assignrolelink'));
                $output = html_writer::tag('div', $link, array('class'=>'addrole'));
            }
        }
        $output .= html_writer::tag('div', $rolesoutput, array('class'=>'roles'));
        return $output;
    }
1088189
public function get_user_roles($userid) {
        $roles = array();
        $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
        $plugins = $this->get_enrolment_plugins(false);
        foreach ($ras as $ra) {
            if ($ra->contextid != $this->context->id) {
                if (!array_key_exists($ra->roleid, $roles)) {
                    $roles[$ra->roleid] = null;
                }
                // higher ras, course always takes precedence
                continue;
            }
            if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
                continue;
            }
            $changeable = true;
            if ($ra->component) {
                $changeable = false;
                if (strpos($ra->component, 'enrol_') === 0) {
                    $plugin = substr($ra->component, 6);
                    if (isset($plugins[$plugin])) {
                        $changeable = !$plugins[$plugin]->roles_protected();
                    }
                }
            }

            $roles[$ra->roleid] = $changeable;
        }
        return $roles;
    }
1053175
private static function buildOrganizationUserRoles(array $roles, RoleableInterface $user, $orgName)
    {
        foreach ($user->getRoles() as $role) {
            $roles[] = RoleUtil::formatName($role).'__'.$orgName;
        }

        return $roles;
    }
841531
public function getByRolesAndNameIncludingGroups(array $roles, $search, $page = 1, $max = 20, $orderedBy = 'id', $direction = null)
    {
        $res = $this->userRepo->findByRolesAndNameIncludingGroups($roles, $search, true, $orderedBy, $direction);

        return $this->pagerFactory->createPager($res, $page, $max);
    }
771387
public function updateRole($roleUuid, array $permissions)
    {
        $options = [
            'form_params' => [
                'permissions' => $permissions,
            ],
        ];

        return new OperationResponse(
            $this->connector->request('put', "/roles/${roleUuid}", $this->query, $options)
        );
    }
181552
public static function get_children_of_user($userid) {
        global $DB;

        // Get users that the user has role assignments to.
        $allusernames = get_all_user_name_fields(true, 'u');
        $sql = "SELECT u.id, $allusernames
                  FROM {role_assignments} ra, {context} c, {user} u
                 WHERE ra.userid = :userid
                       AND ra.contextid = c.id
                       AND c.instanceid = u.id
                       AND c.contextlevel = :contextlevel";
        $params = [
            'userid' => $userid,
            'contextlevel' => CONTEXT_USER
        ];

        // The final list of users that we will return.
        $finalresults = [];

        // Our prospective list of users.
        if ($candidates = $DB->get_records_sql($sql, $params)) {
            foreach ($candidates as $key => $child) {
                $childcontext = \context_user::instance($child->id);
                if (has_capability('tool/dataprivacy:makedatarequestsforchildren', $childcontext, $userid)) {
                    $finalresults[$key] = $child;
                }
            }
        }
        return $finalresults;
    }
287897
public function loadRoleAssignmentForUser($userId, $roleId, Request $request)
    {
        $user = $this->userService->loadUser($userId);
        $roleAssignments = $this->roleService->getRoleAssignmentsForUser($user);

        foreach ($roleAssignments as $roleAssignment) {
            if ($roleAssignment->getRole()->id == $roleId) {
                return new Values\RestUserRoleAssignment($roleAssignment, $userId);
            }
        }

        throw new Exceptions\NotFoundException("Role assignment not found: '{$request->getPathInfo()}'.");
    }
112254
public function noteListAction($resourceId, $page, User $user)
    {
        $notesQB = $this->getNoteActionManager()->getNotesForPagination($resourceId, $user);
        $pager = $this->paginateQuery($notesQB, $page);

        return array('pager' => $pager, 'resourceId' => $resourceId);
    }
1008252
public static function getRoles($userId)
    {
        global $PPHP;
        $db = $PPHP['db'];
        $roles = $db->selectList("SELECT role FROM users_roles WHERE userId=? ORDER BY role ASC", array($userId));
        return $roles !== false ? $roles : array();
    }
924196
public function viewAction(Request $request, Role $role, int $policyPage = 1, int $assignmentPage = 1): Response
    {
        $deleteForm = $this->formFactory->deleteRole(
            new RoleDeleteData($role)
        );

        // If user has no permission to content/read than he should see empty table.
        try {
            $assignments = $this->roleService->getRoleAssignments($role);
        } catch (UnauthorizedException $e) {
            $assignments = [];
        }

        return $this->render('@ezdesign/admin/role/view.html.twig', [
            'role' => $role,
            'assignments' => $assignments,
            'delete_form' => $deleteForm->createView(),
            'route_name' => $request->get('_route'),
            'policyPage' => $policyPage,
            'assignmentPage' => $assignmentPage,
        ]);
    }
904694
public function UserCacheRoles($UserID, $RoleIDs) {
      if (is_null($UserID) || !$UserID) return FALSE;
      
      $Cached = TRUE;
      
      $UserRolesKey = FormatString(self::USERROLES_KEY, array('UserID' => $UserID));
      $Cached = $Cached & Gdn::Cache()->Store($UserRolesKey, $RoleIDs);
      return $Cached;
   }
794068
public function edit(User $user, Role $role)
    {
        $this->authorize(UsersPolicy::PERMISSION_UPDATE);

        $user->load(['roles', 'roles.permissions']);
        $roles = $role->all();

        $this->setTitle($title = trans('auth::users.titles.edit-user'));
        $this->addBreadcrumb($title);

        return $this->view('admin.users.edit', compact('user', 'roles'));
    }
435342
public function assignRole($roleId = null)
    {
        $roles = $this->roles;

        if (! $roles->contains($roleId)) {
            return $this->roles()->attach($roleId);
        }

        return false;
    }
454584
public function Edit($UserID) {
      $this->Permission('Garden.Users.Edit');
      
      // Page setup
      $this->AddJsFile('user.js');
      $this->Title(T('Edit User'));
      $this->AddSideMenu('dashboard/user');

      // By default, people with access here can freely assign all roles
      $RoleModel = new RoleModel();
      $RoleData = $AllRoles = $RoleModel->GetArray();

      // Hide personal info roles
      if (!CheckPermission('Garden.PersonalInfo.View')) {
         $RoleData = array_filter($RoleData, 'RoleModel::FilterPersonalInfo');
      }

      $UserModel = new UserModel();
      $User = $UserModel->GetID($UserID, DATASET_TYPE_ARRAY);
      
      // Determine if username can be edited
      $CanEditUsername = (bool)C("Garden.Profile.EditUsernames") || Gdn::Session()->CheckPermission('Garden.Users.Edit');
      $this->SetData('_CanEditUsername', $CanEditUsername);
      
      // Determine if emails can be edited
      $CanEditEmail = (
              Gdn::Session()->CheckPermission('Garden.Users.Edit') && 
              Gdn::Session()->CheckPermission('Garden.PersonalInfo.View')
           );
      $this->SetData('_CanEditEmail', $CanEditEmail);
      
      // Decide if they have ability to confirm users
      $Confirmed = (bool)GetValueR('Confirmed', $User);
      $CanConfirmEmail = (
              UserModel::RequireConfirmEmail() &&
              Gdn::Session()->CheckPermission('Garden.Users.Edit') && 
              Gdn::Session()->CheckPermission('Garden.PersonalInfo.View'));
      $this->SetData('_CanConfirmEmail', $CanConfirmEmail);
      $this->SetData('_EmailConfirmed', $Confirmed);
      $User['ConfirmEmail'] = (int)$Confirmed;

      // Set the model on the form.
      $this->Form->SetModel($UserModel);

      // Make sure the form knows which item we are editing.
      $this->Form->AddHidden('UserID', $UserID);

      try {
         
         $AllowEditing = TRUE;
         $this->EventArguments['AllowEditing'] = &$AllowEditing;
         $this->EventArguments['TargetUser'] = &$User;
         
         // These are all the 'effective' roles for this edit action. This list can
         // be trimmed down from the real list to allow subsets of roles to be
         // edited.
         $this->EventArguments['RoleData'] = &$RoleData;
         
         $UserRoleData = $UserModel->GetRoles($UserID)->ResultArray();
         $RoleIDs = ConsolidateArrayValuesByKey($UserRoleData, 'RoleID');
         $RoleNames = ConsolidateArrayValuesByKey($UserRoleData, 'Name');
         $UserRoleData = ArrayCombine($RoleIDs, $RoleNames);
         $this->EventArguments['UserRoleData'] = &$UserRoleData;
         
         $this->FireEvent("BeforeUserEdit");
         $this->SetData('AllowEditing', $AllowEditing);
         
         $this->Form->SetData($User);
         if ($this->Form->AuthenticatedPostBack()) {
            
            if (!$CanEditUsername)
               $this->Form->SetFormValue("Name", $User['Name']);
            
            // Allow mods to confirm/unconfirm emails
            $this->Form->RemoveFormValue('Confirmed');
            $Confirmation = $this->Form->GetFormValue('ConfirmEmail', null);
            $Confirmation = !is_null($Confirmation) ? (bool)$Confirmation : null;

            if ($CanConfirmEmail && is_bool($Confirmation))
               $this->Form->SetFormValue('Confirmed', (int)$Confirmation);
            
            // If a new password was specified, add it to the form's collection
            $ResetPassword = $this->Form->GetValue('ResetPassword', FALSE);
            $NewPassword = $this->Form->GetValue('NewPassword', '');
            if ($ResetPassword == 'Manual') 
               $this->Form->SetFormValue('Password', $NewPassword);
            
            // Role changes
            
            // These are the new roles the editing user wishes to apply to the target
            // user, adjusted for his ability to affect those roles
            $RequestedRoles = $this->Form->GetFormValue('RoleID');
            
            if (!is_array($RequestedRoles)) $RequestedRoles = array();
            $RequestedRoles = array_flip($RequestedRoles);
            $UserNewRoles = array_intersect_key($RoleData, $RequestedRoles);
            
            // These roles will stay turned on regardless of the form submission contents 
            // because the editing user does not have permission to modify them
            $ImmutableRoles = array_diff_key($AllRoles, $RoleData);
            $UserImmutableRoles = array_intersect_key($ImmutableRoles, $UserRoleData);
            
            // Apply immutable roles
            foreach ($UserImmutableRoles as $IMRoleID => $IMRoleName)
               $UserNewRoles[$IMRoleID] = $IMRoleName;
            
            // Put the data back into the forum object as if the user had submitted 
            // this themselves
            $this->Form->SetFormValue('RoleID', array_keys($UserNewRoles));
            
            if ($this->Form->Save(array('SaveRoles' => TRUE)) !== FALSE) {
               if ($this->Form->GetValue('ResetPassword', '') == 'Auto') {
                  $UserModel->PasswordRequest($User['Email']);
                  $UserModel->SetField($UserID, 'HashMethod', 'Reset'); 
               }

               $this->InformMessage(T('Your changes have been saved.'));
            }
            
            $UserRoleData = $UserNewRoles;
         }
      } catch (Exception $Ex) {
         $this->Form->AddError($Ex);
      }
      
      $this->SetData('User', $User);
      $this->SetData('Roles', $RoleData);
      $this->SetData('UserRoles', $UserRoleData);
      
      $this->Render();
   }
435052
public function addRoleForUser(UserEntity $user, $role)
    {
        $roles = $user->getRoles();

        if (! in_array($role, $roles)) {
            $this->userRolePivotMapper->addRoleForUser($user->getId(), $role);

            array_push($roles, $role);

            $user->setRoles($roles);
        }
    }
78737
public function removeRole($roleId, $pageId = 0)
    {
        $this->roles()
            ->wherePivot(self::PIVOT_ATTR_ROLE_ID, '=', $roleId)
            ->wherePivot(self::PIVOT_ATTR_PAGE_ID, '=', $pageId)
            ->detach();

        return $this;
    }
908100
public function getErrors(ResourceNode $resourceNode, array $userRoles): array
    {
        if (!$this->isGranted($resourceNode, $userRoles)) {
            // return restrictions details
            $errors = [
                'noRights' => !$this->hasRights($resourceNode, $userRoles),
                'deleted' => !$resourceNode->isActive(),
                'notPublished' => !$resourceNode->isPublished(),
            ];

            // optional restrictions
            // we return them only if they are enabled
            if (!empty($resourceNode->getAccessCode())) {
                $errors['locked'] = !$this->isUnlocked($resourceNode);
            }

            if (!empty($resourceNode->getAccessibleFrom()) || !empty($resourceNode->getAccessibleUntil())) {
                $errors['notStarted'] = !$this->isStarted($resourceNode);
                $errors['startDate'] = $resourceNode->getAccessibleFrom() ?
                    $resourceNode->getAccessibleFrom()->format('d/m/Y') :
                    null;
                $errors['ended'] = $this->isEnded($resourceNode);
            }

            if (!empty($resourceNode->getAllowedIps())) {
                $errors['invalidLocation'] = !$this->isIpAuthorized($resourceNode);
            }

            return $errors;
        }

        return [];
    }