Add a basic filter to query only rows belonging to a given user and not having status ARCHIVED or CANCELLED.

@param string $userId
@param bool $archivedAllowed
@param bool $cancelledAvailable
@return $this
770109
public function addAvailableFilters($userId, $archivedAllowed = false, $cancelledAvailable = false)
    {
        if (!$archivedAllowed) {
            $this->neq(TaskLogBrokerInterface::COLUMN_STATUS, TaskLogInterface::STATUS_ARCHIVED);
        }

        if (!$cancelledAvailable) {
            $this->neq(TaskLogBrokerInterface::COLUMN_STATUS, TaskLogInterface::STATUS_CANCELLED);
        }

        if ($userId !== TaskLogInterface::SUPER_USER) {
            $this->eq(TaskLogBrokerInterface::COLUMN_OWNER, $userId);
        }

        return $this;
    }
156911
public function checkAccess($userId, $permissionName)
    {
        if (ValidatorHelper::isInteger($userId) == false) {
            throw new InvalidArgumentException('User identifier must be number.');
        }

        /** @var integer $permissionId */
        $permissionId = $this->repositoryRegistry
            ->getPermissionRepository()
            ->getPermissionIdByName($permissionName);

        if (ValidatorHelper::isInteger($permissionId)) {

            /** @var integer[] $rootRoleIds */
            $rootRoleIds = $this->repositoryRegistry
                ->getUserRoleRepository()
                ->getUserRoleIds($userId);

            if (count($rootRoleIds) > 0) {

                /** @var integer[] $allRoleIds */
                $allRoleIds = $this->repositoryRegistry
                    ->getRoleHierarchyRepository()
                    ->getAllRoleIdsHierarchy($rootRoleIds);

                return $this->repositoryRegistry
                    ->getRolePermissionRepository()
                    ->isPermissionAssigned($permissionId, $allRoleIds);
            }
        }

        return false;
    }
1142702
public void setReadAccess(String userId, boolean allowed) {
    if (StringUtil.isEmpty(userId)) {
      throw new IllegalArgumentException("cannot setRead/WriteAccess for null userId");
    }
    boolean writePermission = getWriteAccess(userId);
    setPermissionsIfNonEmpty(userId, allowed, writePermission);
  }
296414
public void setWriteAccess(String userId, boolean allowed) {
    if (StringUtil.isEmpty(userId)) {
      throw new IllegalArgumentException("cannot setRead/WriteAccess for null userId");
    }
    boolean readPermission = getReadAccess(userId);
    setPermissionsIfNonEmpty(userId, readPermission, allowed);
  }
116074
public function handleRemove(int $userId) : void
    {
        if ($this->presenter->isAjax())
        {
            $this->userEntity = $this->userRepository->findOneById($userId);

            $allowRemove = (
                (
                    !$this->userEntity->isInRole(UserAuthorizator::ROLE_ADMIN)
                    || $this->presenter->user->isAllowed(UserAuthorizator::RES_EDIT_ADMINS)
                )
                && $this->presenter->user->isAllowed(UserAuthorizator::RES_REMOVE_HANDLE)
                && $userId !== $this->presenter->user->getId()
            );

            if (!$allowRemove)
            {
                throw new ForbiddenRequestException;
            }

            $this->userManager->delete($this->userEntity);

            $this->presenter->notificationAjax(
                'Uživatel odstaněn.',
                "Uživatel {$this->userEntity->getEmail()} byl úspěšně odstaněn.",
                    'info',
                    FALSE
                );

            $this->presenter->handleModalToggle('hide', '#wakers_user_remove_modal', FALSE);

            $this->onRemove();
        }
    }
688158
function enforce($Permission, $UserID = null)
	{
	if ($UserID === null)
                throw new \RbacUserNotProvidedException ("\$UserID is a required argument.");

		if (! $this->check($Permission, $UserID)) {
            header('HTTP/1.1 403 Forbidden');
            die("<strong>Forbidden</strong>: You do not have permission to access this resource.");
        }

        return true;
	}
832026
public function findByUserId($userId)
    {
        $select = $this->getSelect();
        $select->where(array('user_id' => $userId));

        return $this->select($select);
    }
1326590
public static function delete_data_for_users(approved_userlist $userlist) {
        $context = $userlist->get_context();

        if (!$context instanceof \context_user) {
            return;
        }

        // Remove invalid users. If it ends up empty then early return.
        $userids = array_filter($userlist->get_userids(), function($userid) use($context) {
            return $context->instanceid == $userid;
        });

        if (empty($userids)) {
            return;
        }

        static::delete_user_data($context->instanceid);
    }
201110
public static function is_user_gradable_in_course($courseid, $userid) {
        global $CFG;

        $gradableuser = false;
        $coursecontext = \context_course::instance($courseid);
        if (is_enrolled($coursecontext, $userid, '', false)) {
            $roles = get_user_roles($coursecontext, $userid);
            $gradebookroles = explode(',', $CFG->gradebookroles);
            foreach ($roles as $role) {
                foreach ($gradebookroles as $gradebookrole) {
                    if ($role->roleid = $gradebookrole) {
                        $gradableuser = true;
                    }
                }
            }
        }

        return $gradableuser;
    }
397277
public static function unblock_user(int $userid, int $usertounblockid) {
        global $DB;

        if ($blockeduser = $DB->get_record('message_users_blocked',
                ['userid' => $userid, 'blockeduserid' => $usertounblockid])) {
            $DB->delete_records('message_users_blocked', ['id' => $blockeduser->id]);

            // Trigger event for unblocking a contact.
            $event = \core\event\message_user_unblocked::create(array(
                'objectid' => $blockeduser->id,
                'userid' => $userid,
                'relateduserid' => $usertounblockid,
                'context' => \context_user::instance($userid)
            ));
            $event->add_record_snapshot('message_users_blocked', $blockeduser);
            $event->trigger();
        }
    }
482067
private function createRateLimitData($applicationId, $userId)
	{
		// data needed to create record
		$ipAddress    = \Request::ip();
		$countShort   = 0;
		$countLong    = 0;
		$limitShort   = $this->config['short']['limit'];
		$limitLong    = $this->config['long']['limit'];
		$created      = with(new Date('now'))->toSql();
		$expiresShort = $this->getNewExpiresDateString('short');
		$expiresLong  = $this->getNewExpiresDateString('long');

		// create initial limit record
		return $this->storage->createRateLimitData(
			$applicationId,
			$userId,
			$ipAddress,
			$limitShort,
			$limitLong,
			$countShort,
			$countLong,
			$expiresShort,
			$expiresLong,
			$created
		);
	}
1072369
public function GetByUser($UserID, $Limit, $Offset = 0) {
      // Get category permissions
      $Perms = DiscussionModel::CategoryPermissions();
      
      // Build main query
      $this->CommentQuery(TRUE, FALSE);
      $this->FireEvent('BeforeGet');
      $this->SQL
			->Select('d.Name', '', 'DiscussionName')
			->Join('Discussion d', 'c.DiscussionID = d.DiscussionID')
         ->Where('c.InsertUserID', $UserID)
			->OrderBy('c.CommentID', 'desc')
         ->Limit($Limit, $Offset);
      
      // Verify permissions (restricting by category if necessary)
      if($Perms !== TRUE) {
         $this->SQL
            ->Join('Category ca', 'd.CategoryID = ca.CategoryID', 'left')
            ->WhereIn('d.CategoryID', $Perms);
      }
      
      //$this->OrderBy($this->SQL);

      $Data = $this->SQL->Get();
      Gdn::UserModel()->JoinUsers($Data, array('InsertUserID', 'UpdateUserID'));
      
      return $Data;
      
   }
334750
public static function cancel_data_request($requestid) {
        global $USER;

        $warnings = [];
        $params = external_api::validate_parameters(self::cancel_data_request_parameters(), [
            'requestid' => $requestid
        ]);
        $requestid = $params['requestid'];

        // Validate context and access to manage the registry.
        $context = context_user::instance($USER->id);
        self::validate_context($context);

        // Ensure the request exists.
        $select = 'id = :id AND (userid = :userid OR requestedby = :requestedby)';
        $params = ['id' => $requestid, 'userid' => $USER->id, 'requestedby' => $USER->id];
        $requests = data_request::get_records_select($select, $params);
        $requestexists = count($requests) === 1;

        $result = false;
        if ($requestexists) {
            $request = reset($requests);
            $datasubject = $request->get('userid');

            if ($datasubject !== $USER->id) {
                // The user is not the subject. Check that they can cancel this request.
                if (!api::can_create_data_request_for_user($datasubject)) {
                    $forusercontext = \context_user::instance($datasubject);
                    throw new required_capability_exception($forusercontext,
                            'tool/dataprivacy:makedatarequestsforchildren', 'nopermissions', '');
                }
            }

            // TODO: Do we want a request to be non-cancellable past a certain point? E.g. When it's already approved/processing.
            $result = api::update_request_status($requestid, api::DATAREQUEST_STATUS_CANCELLED);
        } else {
            $warnings[] = [
                'item' => $requestid,
                'warningcode' => 'errorrequestnotfound',
                'message' => get_string('errorrequestnotfound', 'tool_dataprivacy')
            ];
        }

        return [
            'result' => $result,
            'warnings' => $warnings
        ];
    }
519910
public static function delete_data_for_users(approved_userlist $userlist) {
        global $DB;
        $context = $userlist->get_context();

        // Sanity check that context is at the User context level, then get the userid.
        if ($context->contextlevel !== CONTEXT_USER) {
            return;
        }

        $userids = $userlist->get_userids();
        list($insql, $inparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
        $params = [
            'contextid' => $context->id,
            'contextuser' => CONTEXT_USER,
        ];
        $params = array_merge($params, $inparams);

        // Fetch the repository_onedrive_access IDs in the context for approved users.
        $sql = "SELECT roa.id
                  FROM {repository_onedrive_access} roa
                  JOIN {context} c ON c.instanceid = roa.usermodified
                   AND c.contextlevel = :contextuser
                   AND c.id = :contextid
                 WHERE roa.usermodified {$insql}";
        $accessids = $DB->get_fieldset_sql($sql, $params);

        // Delete the relevant repository_onedrive_access data.
        list($insql, $params) = $DB->get_in_or_equal($accessids, SQL_PARAMS_NAMED);
        $DB->delete_records_select('repository_onedrive_access', "id {$insql}", $params);
    }
676773
public function can_view_submission($userid) {
        global $USER;

        if (!$this->is_active_user($userid) && !has_capability('moodle/course:viewsuspendedusers', $this->context)) {
            return false;
        }
        if (!is_enrolled($this->get_course_context(), $userid)) {
            return false;
        }
        if (has_any_capability(array('mod/assign:viewgrades', 'mod/assign:grade'), $this->context)) {
            return true;
        }
        if ($userid == $USER->id && has_capability('mod/assign:submit', $this->context)) {
            return true;
        }
        return false;
    }
447778
public function canCancel($userId)
    {
        return $this->isOwner($userId) ||
            ($this->isIssuer($userId) && $this->isOnTimeToCancel()) ||
            ($this->isTarget($userId) && $this->isOnTimeToCancel());
    }
545677
public static function user_competency_cancel_review_request($userid, $competencyid) {
        static::require_enabled();
        $context = context_user::instance($userid);
        $uc = user_competency::get_record(array('userid' => $userid, 'competencyid' => $competencyid));
        if (!$uc || !$uc->can_read()) {
            throw new required_capability_exception($context, 'moodle/competency:usercompetencyview', 'nopermissions', '');
        } else if ($uc->get('status') != user_competency::STATUS_WAITING_FOR_REVIEW) {
            throw new coding_exception('The competency can not be cancel review request at this stage.');
        } else if (!$uc->can_request_review()) {
            throw new required_capability_exception($context, 'moodle/competency:usercompetencyrequestreview', 'nopermissions', '');
        }

        $uc->set('status', user_competency::STATUS_IDLE);
        $result = $uc->update();
        if ($result) {
            \core\event\competency_user_competency_review_request_cancelled::create_from_user_competency($uc)->trigger();
        }
        return $result;
    }