@param $userId

@throws \DreamFactory\Core\Exceptions\ForbiddenException
768803
protected static function checkRole($userId)
    {
        $appId = static::get('app.id', null);

        if (!empty($appId) && !empty($userId)) {
            $roleId = UserAppRole::getRoleIdByAppIdAndUserId($appId, $userId);
            $roleInfo = ($roleId) ? Role::getCachedInfo($roleId) : null;
            if (!empty($roleInfo) && !array_get($roleInfo, 'is_active', false)) {
                throw new ForbiddenException('Role is not active.');
            }
        }
    }
132745
public static function export_user_preferences(int $userid) {
        $draweropennavpref = get_user_preferences(self::DRAWER_OPEN_NAV, null, $userid);

        if (isset($draweropennavpref)) {
            $preferencestring = get_string('privacy:drawernavclosed', 'theme_boost');
            if ($draweropennavpref == 'true') {
                $preferencestring = get_string('privacy:drawernavopen', 'theme_boost');
            }
            \core_privacy\local\request\writer::export_user_preference(
                'theme_boost',
                self::DRAWER_OPEN_NAV,
                $draweropennavpref,
                $preferencestring
            );
        }
    }
357644
public function saveSubscription(int $userId = null) : void
    {
        $json = \file_get_contents('php://input');

        if (!$json)
        {
            return;
        }

        $data = \json_decode($json, true);

        if (!$data || empty($data['endpoint']) || empty($data['publicKey']) || empty($data['authToken']))
        {
            return;
        }

        $row = $this->subscriptionTable->findActive()->where('endpoint', $data['endpoint'])->fetch();

        switch ($this->request->getMethod()) {
            case 'POST':
            case 'PUT':
            {
                if ($row)
                {
                    $row->update([
                        'user_id' => $userId ?: $row->user_id ?: null,
                        'key' => $data['publicKey'],
                        'token' => $data['authToken'],
                        'encoding' => $data['contentEncoding']
                    ]);
                    
                    return;
                }

                $row = $this->subscriptionTable->insert([
                    'user_id' => $userId,
                    'endpoint' => $data['endpoint'],
                    'key' => $data['publicKey'],
                    'token' => $data['authToken'],
                    'encoding' => $data['contentEncoding']
                ]);

                $this->sendNotification($row, 'Notifications enabled!', true);

                return;
            }
            case 'DELETE':
            {
                if ($row)
                {
                    $row->update([
                        'active' => 0
                    ]);
                }

                return;
            }
            default:
                throw new \Nette\Application\BadRequestException();
        }
    }
151881
public function getPermissionByUserId($userId)
    {
        $prefix = $this->getConfig('prefix');
        $permission = Db::name('permission')->setConnection($this->getConnection())->alias('p')
            ->join(["{$prefix}role_permission" => 'rp'], 'p.id = rp.permission_id')
            ->join(["{$prefix}user_role" => 'ur'], 'rp.role_id = ur.role_id')
            ->where('ur.user_id', $userId)->select();
        return $permission;
    }
601656
public function update($userId)
    {
        try
        {
            $permissions = Input::get('permissions', array());
            $this->users->updatePermissions($userId,$permissions);

            return Redirect::route('cpanel.users.index')
                ->with('success', Lang::get('cpanel::users.permissions_update_success'));
        }
        catch ( UserNotFoundException $e)
        {
            return Redirect::route('cpanel.users.permissions')
                ->with('error', $e->getMessage());
        }

    }
206164
public function deleteUser($userId)
    {
        $query = $this->handler->createDeleteQuery();
        $query
            ->deleteFrom($this->handler->quoteTable('ezuser_setting'))
            ->where(
                $query->expr->eq(
                    $this->handler->quoteColumn('user_id'),
                    $query->bindValue($userId, null, \PDO::PARAM_INT)
                )
            );
        $query->prepare()->execute();

        $query = $this->handler->createDeleteQuery();
        $query
            ->deleteFrom($this->handler->quoteTable('ezuser'))
            ->where(
                $query->expr->eq(
                    $this->handler->quoteColumn('contentobject_id'),
                    $query->bindValue($userId, null, \PDO::PARAM_INT)
                )
            );
        $query->prepare()->execute();
    }
262338
private function createAuthorization($userId, $instanceId)
    {
        $apiAll = $this->getNavitiaApiAllId();
        $this->call($this->tyrUrl . '/' . $this->version . '/users/' . $userId . '/authorizations/?api_id=' . $apiAll->id . '&instance_id=' . $instanceId, 'POST');

        return true;
    }
460684
public function index($userId)
    {
        try
        {
            $user = $this->users->findById($userId);
            $userPermissions = $user->getPermissions();
            $genericPermissions = $this->permissions->generic();
            $modulePermissions = $this->permissions->module();

            return View::make(Config::get('cpanel::views.users_permission'))
                ->with('user',$user)
                ->with('userPermissions',$userPermissions)
                ->with('genericPermissions',$genericPermissions)
                ->with('modulePermissions',$modulePermissions);
        }
        catch ( UserNotFoundException $e)
        {
            return Redirect::route('cpanel.users.index')
                ->with('error', $e->getMessage());
        }
    }
926779
public function assignUserToUserGroup($userId, Request $request)
    {
        $user = $this->userService->loadUser($userId);

        try {
            $userGroupLocation = $this->locationService->loadLocation(
                $this->extractLocationIdFromPath($request->query->get('group'))
            );
        } catch (ApiExceptions\NotFoundException $e) {
            throw new Exceptions\ForbiddenException($e->getMessage());
        }

        try {
            $userGroup = $this->userService->loadUserGroup(
                $userGroupLocation->contentId
            );
        } catch (ApiExceptions\NotFoundException $e) {
            throw new Exceptions\ForbiddenException($e->getMessage());
        }

        try {
            $this->userService->assignUserToUserGroup($user, $userGroup);
        } catch (ApiExceptions\NotFoundException $e) {
            throw new Exceptions\ForbiddenException($e->getMessage());
        }

        $userGroups = $this->userService->loadUserGroupsOfUser($user);
        $restUserGroups = array();
        foreach ($userGroups as $userGroup) {
            $userGroupContentInfo = $userGroup->getVersionInfo()->getContentInfo();
            $userGroupLocation = $this->locationService->loadLocation($userGroupContentInfo->mainLocationId);
            $contentType = $this->contentTypeService->loadContentType($userGroupContentInfo->contentTypeId);

            $restUserGroups[] = new Values\RestUserGroup(
                $userGroup,
                $contentType,
                $userGroupContentInfo,
                $userGroupLocation,
                $this->contentService->loadRelations($userGroup->getVersionInfo())
            );
        }

        return new Values\UserGroupRefList(
            $restUserGroups,
            $this->router->generate(
                'ezpublish_rest_loadUserGroupsOfUser',
                array('userId' => $userId)
            ),
            $userId
        );
    }
860320
public function loginUsingId($userId)
    {
        // Find the user using the user id
        try {
            $user = Sentry::findUserById($userId);

            // Log the user in
            Sentry::login($user);

            return $user;
        } catch (UserNotFoundException $e) {
            return null;
        }
    }
402026
public function actionSwitch($id = null)
    {
        if (!$this->module->enableImpersonateUser) {
            throw new ForbiddenHttpException(Yii::t('user', 'Impersonate user is disabled in the application configuration'));
        }

        if(!$id && Yii::$app->session->has(self::ORIGINAL_USER_SESSION_KEY)) {
            $user = $this->findModel(Yii::$app->session->get(self::ORIGINAL_USER_SESSION_KEY));

            Yii::$app->session->remove(self::ORIGINAL_USER_SESSION_KEY);
        } else {
            if (!Yii::$app->user->identity->isAdmin) {
                throw new ForbiddenHttpException;
            }

            $user = $this->findModel($id);
            Yii::$app->session->set(self::ORIGINAL_USER_SESSION_KEY, Yii::$app->user->id);
        }

        $event = $this->getUserEvent($user);

        $this->trigger(self::EVENT_BEFORE_IMPERSONATE, $event);
        
        Yii::$app->user->switchIdentity($user, 3600);
        
        $this->trigger(self::EVENT_AFTER_IMPERSONATE, $event);

        return $this->goHome();
    }
618525
public function removeUserById($userId)
    {
        $updtableProperties = Updatable::getInstance()
            ->table($this->getUserPropertiesDefinition()->table())
            ->where(
                "{$this->getUserPropertiesDefinition()->getUserid()} = :id",
                [
                    "id" => $userId
                ]
            );
        $this->propertiesRepository->deleteByQuery($updtableProperties);

        $this->userRepository->delete($userId);

        return true;
    }
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();
   }
888845
final function throttle(string $userID) {
        if(empty($this->throttling) || $this->client->isOwner($userID)) {
            return null;
        }
        
        if(!$this->throttles->has($userID)) {
            $this->throttles->set($userID, array(
                'start' => \time(),
                'usages' => 0,
                'timeout' => $this->client->addTimer($this->throttling['duration'], function () use ($userID) {
                    $this->throttles->delete($userID);
                })
            ));
        }
        
        return $this->throttles->get($userID);
    }
1237856
public function setUserId( $userId )
    {
        $this->_user    = null;
        $this->userId   = ( (int) $userId ) ?: null;
        return $this;
    }
1211780
protected static function export_user_data_blocked_users(int $userid) {
        global $DB;

        $context = \context_user::instance($userid);

        if ($blockedusers = $DB->get_records('message_users_blocked', ['userid' => $userid], 'id ASC')) {
            $blockedusersdata = [];
            foreach ($blockedusers as $blockeduser) {
                $blockedusersdata[] = (object) [
                    'blockeduser' => transform::user($blockeduser->blockeduserid)
                ];
            }
            writer::with_context($context)->export_data([get_string('blockedusers', 'core_message')], (object) $blockedusersdata);
        }
    }
1154569
public function delete($id)
    {
        if ($id === '1') {
            throw new ForbiddenException();
        }
        if (!$this->request->is(['post'])) {
            throw new MethodNotAllowedException();
        }

        /** @var Connection $connection */
        $connection = $this->Groups->connection();

        $connection->begin();
        $group = $this->Groups->get($id);

        $users = $this->Groups->UsersGroups->Users->find()
            ->matching('UsersGroups', function (Query $q) use ($id) {
                return $q->where(['UsersGroups.group_id' => $id]);
            });

        // Filter the resulting users to match only users assigned to more than one user group.
        $skipUserIds = $this->Groups->UsersGroups->findUserIdsWithOnlyOneGroup();
        if (!empty($skipUserIds)) {
            $users->where([
                $this->Groups->Users->aliasField('id') . ' IN' => $skipUserIds
            ]);
        }

        $userCount = $users->all()->count();
        $groupCanBeDeleted = ($userCount === 0);

        if (($alternativeGroupIds = $this->request->data('alternative_group_id')) !== null) {
            // check if a valid alternative group has been selected for every user
            $valid = true;
            $validAlternativeGroupIds = [];
            foreach ($users as $user) {
                if (!isset($alternativeGroupIds[$user->id]) ||
                    (int)$alternativeGroupIds[$user->id] === (int)$id ||
                    !$this->Groups->exists(['id' => $alternativeGroupIds[$user->id]])
                ) {
                    $valid = false;
                } else {
                    $validAlternativeGroupIds[$user->id] = (int)$alternativeGroupIds[$user->id];
                }
            }
            if ($valid) {
                // move existing users of the group to the submitted alternative group
                $groupCanBeDeleted = (bool)$this->Groups->moveUsersToAlternativeGroups($validAlternativeGroupIds);
            } else {
                $this->Flash->error(__d('wasabi_core', 'Please select an alternative user group for every listed user.'));
            }
        }

        if ($groupCanBeDeleted === true) {
            if ($this->Groups->delete($group)) {
                $connection->commit();
                if ($userCount > 0) {
                    $this->Flash->success(__d('wasabi_core', 'The group <strong>{0}</strong> has been deleted. Prior <strong>{1}</strong> group member(s) ha(s/ve) been moved to another group.', $group->name, $userCount));
                } else {
                    $this->Flash->success(__d('wasabi_core', 'The group <strong>{0}</strong> has been deleted.', $group->name));
                }
            } else {
                $connection->rollback();
                $this->Flash->error($this->dbErrorMessage);
            }
            $this->redirect($this->Filter->getBacklink(['action' => 'index'], $this->request));
            return;
        } else {
            $connection->rollback();
            $this->Flash->warning(__d('wasabi_core', 'The group <strong>{0}</strong> has <strong>{1}</strong> member(s) that need to be moved to another group.', $group->name, $userCount));
            $this->set([
                'users' => $users,
                'group' => $group,
                'groups' => $this->Groups->find('list')->where(['not' => ['id' => $id]])
            ]);
        }
    }