Issue a badge to user.

@param int $userid User who earned the badge
@param bool $nobake Not baking actual badges (for testing purposes)
500827
public function issue($userid, $nobake = false) {
        global $DB, $CFG;

        $now = time();
        $issued = new stdClass();
        $issued->badgeid = $this->id;
        $issued->userid = $userid;
        $issued->uniquehash = sha1(rand() . $userid . $this->id . $now);
        $issued->dateissued = $now;

        if ($this->can_expire()) {
            $issued->dateexpire = $this->calculate_expiry($now);
        } else {
            $issued->dateexpire = null;
        }

        // Take into account user badges privacy settings.
        // If none set, badges default visibility is set to public.
        $issued->visible = get_user_preferences('badgeprivacysetting', 1, $userid);

        $result = $DB->insert_record('badge_issued', $issued, true);

        if ($result) {
            // Trigger badge awarded event.
            $eventdata = array (
                'context' => $this->get_context(),
                'objectid' => $this->id,
                'relateduserid' => $userid,
                'other' => array('dateexpire' => $issued->dateexpire, 'badgeissuedid' => $result)
            );
            \core\event\badge_awarded::create($eventdata)->trigger();

            // Lock the badge, so that its criteria could not be changed any more.
            if ($this->status == BADGE_STATUS_ACTIVE) {
                $this->set_status(BADGE_STATUS_ACTIVE_LOCKED);
            }

            // Update details in criteria_met table.
            $compl = $this->get_criteria_completions($userid);
            foreach ($compl as $c) {
                $obj = new stdClass();
                $obj->id = $c->id;
                $obj->issuedid = $result;
                $DB->update_record('badge_criteria_met', $obj, true);
            }

            if (!$nobake) {
                // Bake a badge image.
                $pathhash = badges_bake($issued->uniquehash, $this->id, $userid, true);

                // Notify recipients and badge creators.
                badges_notify_badge_award($this, $userid, $issued->uniquehash, $pathhash);
            }
        }
    }
164838
protected function add_attempt($userid) {
        require_capability('mod/assign:grade', $this->context);

        if ($this->get_instance()->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_NONE) {
            return false;
        }

        if ($this->get_instance()->teamsubmission) {
            $oldsubmission = $this->get_group_submission($userid, 0, false);
        } else {
            $oldsubmission = $this->get_user_submission($userid, false);
        }

        if (!$oldsubmission) {
            return false;
        }

        // No more than max attempts allowed.
        if ($this->get_instance()->maxattempts != ASSIGN_UNLIMITED_ATTEMPTS &&
            $oldsubmission->attemptnumber >= ($this->get_instance()->maxattempts - 1)) {
            return false;
        }

        // Create the new submission record for the group/user.
        if ($this->get_instance()->teamsubmission) {
            if (isset($this->mostrecentteamsubmission)) {
                // Team submissions can end up in this function for each user (via save_grade). We don't want to create
                // more than one attempt for the whole team.
                if ($this->mostrecentteamsubmission->attemptnumber == $oldsubmission->attemptnumber) {
                    $newsubmission = $this->get_group_submission($userid, 0, true, $oldsubmission->attemptnumber + 1);
                } else {
                    $newsubmission = $this->get_group_submission($userid, 0, false, $oldsubmission->attemptnumber);
                }
            } else {
                debugging('Please use set_most_recent_team_submission() before calling add_attempt', DEBUG_DEVELOPER);
                $newsubmission = $this->get_group_submission($userid, 0, true, $oldsubmission->attemptnumber + 1);
            }
        } else {
            $newsubmission = $this->get_user_submission($userid, true, $oldsubmission->attemptnumber + 1);
        }

        // Set the status of the new attempt to reopened.
        $newsubmission->status = ASSIGN_SUBMISSION_STATUS_REOPENED;

        // Give each submission plugin a chance to process the add_attempt.
        $plugins = $this->get_submission_plugins();
        foreach ($plugins as $plugin) {
            if ($plugin->is_enabled() && $plugin->is_visible()) {
                $plugin->add_attempt($oldsubmission, $newsubmission);
            }
        }

        $this->update_submission($newsubmission, $userid, false, $this->get_instance()->teamsubmission);
        $flags = $this->get_user_flags($userid, false);
        if (isset($flags->locked) && $flags->locked) { // May not exist.
            $this->process_unlock_submission($userid);
        }
        return true;
    }
1265174
public function execute($sourceId = null, $userId = null)
    {
        $batch  = $this->getBatch();
        $source = $this->loader->getTracker()->getSource($sourceId);

        if (is_null($userId)) {
            $userId = $this->loader->getCurrentUser()->getUserId();
        }

        $surveyCount = $batch->addToCounter('sourceSyncSources');
        $batch->setMessage('sourceSyncSources', sprintf(
                $this->plural('Check %s source', 'Check %s sources', $surveyCount),
                $surveyCount
                ));

        $source->synchronizeSurveyBatch($batch, $userId);
    }
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();
        }
    }
1002621
public function getCredentialObject($userId = null)
    {
        if ($userId == null && array_key_exists($this->defaultAccountName, $this->credentialHashmap)) {
            $credObj = $this->credentialHashmap[$this->defaultAccountName];
        } else if (array_key_exists($userId, $this->credentialHashmap)) {
            $credObj = $this->credentialHashmap[$userId];
        }

        if (empty($credObj)) {
            throw new BlockCypherInvalidCredentialException("Credential not found for " . ($userId ? $userId : " default user") .
                ". Please make sure your configuration/APIContext has credential information");
        }
        return $credObj;
    }
1114980
public function setReceptionCode($newCode, $userId)
    {
        // Get the code object
        $code    = $this->util->getReceptionCode($newCode);

        // Use the token function as that cascades the consent code
        $changed = $this->token->setReceptionCode($code, $this->formData['gto_comment'], $userId);

        if ($code->isSuccess()) {
            $this->addMessage(sprintf($this->_('Token %s restored.'), $this->token->getTokenId()));
        } else {
            $this->addMessage(sprintf($this->_('Token %s deleted.'), $this->token->getTokenId()));

            if ($code->hasRedoCode()) {
                $newComment = sprintf($this->_('Redo of token %s.'), $this->token->getTokenId());
                if ($this->formData['gto_comment']) {
                    $newComment .= "\n\n";
                    $newComment .= $this->_('Old comment:');
                    $newComment .= "\n";
                    $newComment .= $this->formData['gto_comment'];
                }

                $this->_replacementTokenId = $this->token->createReplacement($newComment, $userId);

                // Create a link for the old token
                $oldToken = strtoupper($this->token->getTokenId());
                $menuItem = $this->menu->findAllowedController('track', 'show');
                if ($menuItem) {
                    $paramSource['gto_id_token']       = $this->token->getTokenId();
                    $paramSource[\Gems_Model::ID_TYPE] = 'token';

                    $href = $menuItem->toHRefAttribute($paramSource);
                    if ($href) {
                        // \MUtil_Echo::track($oldToken);
                        $link = \MUtil_Html::create('a', $href, $oldToken);

                        $oldToken = $link->setView($this->view);
                    }
                }

                // Tell what the user what happened
                $this->addMessage(new \MUtil_Html_Raw(sprintf(
                        $this->_('Created this token %s as replacement for token %s.'),
                        strtoupper($this->_replacementTokenId),
                        $oldToken
                        )));

                // Lookup token
                $newToken = $this->loader->getTracker()->getToken($this->_replacementTokenId);

                // Make sure the Next token is set right
                $this->token->setNextToken($newToken);

                // Copy answers when requested.
                /* Copy moved to \Gems_Track_Token->getUrl()
                if ($code->hasRedoCopyCode()) {
                    $newToken->setRawAnswers($this->token->getRawAnswers());
                }
                */
            }
        }

        $respTrack = $this->token->getRespondentTrack();
        if ($nextToken = $this->token->getNextToken()) {
            if ($recalc = $respTrack->checkTrackTokens($userId, $nextToken)) {
                $this->addMessage(sprintf($this->plural(
                        '%d token changed by recalculation.',
                        '%d tokens changed by recalculation.',
                        $recalc
                        ), $recalc));
            }
        }

        return $changed;
    }
1166398
public function execute($userId = 0)
    {
        $batch = $this->getBatch();
        if ($batch->getCounter('movestarted') === 0) {
            $batch->addToCounter('movestarted');
            $select = $this->loader->getTracker()->getTokenSelect(['total' => new \Zend_Db_Expr('count(*)')])->andReceptionCodes([])->onlyCompleted()->onlySucces()->forSurveyId($this->sourceSurveyId)->getSelect();
            $count = $this->db->fetchOne($select);
            $batch->addStepCount($count - 1);   // For progressbar
            $batch->resetCounter('movesteps');
            $batch->addToCounter('movesteps', $count);
        }
        $this->executeIteration($userId);
    }
480274
public function handleTrackCalculation($userId)
    {
        // Process any events
        $trackEngine = $this->getTrackEngine();

        // Places here instead of only in handle field update so it will run on new tracks too
        $this->assignTokensToRelations();

        if ($event = $trackEngine->getTrackCalculationEvent()) {
            return $event->processTrackCalculation($this, $userId);
        }

        return 0;
    }
231114
public static function unlock_submissions($assignmentid, $userids) {
        global $CFG;

        $params = self::validate_parameters(self::unlock_submissions_parameters(),
                        array('assignmentid' => $assignmentid,
                              'userids' => $userids));

        list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);

        $warnings = array();
        foreach ($params['userids'] as $userid) {
            if (!$assignment->unlock_submission($userid)) {
                $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
                $warnings[] = self::generate_warning($params['assignmentid'],
                                                     'couldnotunlock',
                                                     $detail);
            }
        }

        return $warnings;
    }
742132
public function grantBadge($badge, $users)
	{
		if (!$this->credentialsSet())
		{
			throw new Exception('You need to set the credentials first.');
		}

		if (!is_array($users))
		{
			$users = array($users);
		}

		$assertions = array();

		foreach ($users as $user)
		{
			$data = array();

			$data['BadgeId']      = $badge->id;
			$data['EvidenceUrl']  = $badge->evidenceUrl;
			$data['EmailAddress'] = $user;
			$data['ClientId']     = $this->credentials->clientId;

			$assertions[] = $data;
			unset($data);
		}

		$assertionsData = json_encode($assertions);

		if ($this->request_type == 'oauth' && is_a($this->request, 'oauth'))
		{
			$this->request->setAuthType(OAUTH_AUTH_TYPE_AUTHORIZATION);
			try
			{
				$this->request->fetch(self::PASSPORT_API_ENDPOINT . "assertions/", $assertionsData, OAUTH_HTTP_METHOD_POST, array('Content-Type' => 'application/json'));
			}
			catch (Exception $e)
			{
				throw new Exception('Badge grant request failed.');
			}

			$assertion = json_decode($this->request->getLastResponse());
		}
		else if ($this->request_type == 'curl' && get_resource_type($this->request) == 'curl')
		{
			curl_setopt($this->request, CURLOPT_URL, self::PASSPORT_API_ENDPOINT . "assertions/");
			curl_setopt($this->request, CURLOPT_POSTFIELDS, $assertionsData);
			curl_setopt($this->request, CURLOPT_RETURNTRANSFER, true);

			$response  = curl_exec($this->request);
			$assertion = json_decode($response);
		}
		else
		{
			throw new Exception('Unsupported request type');
		}

		foreach ($assertion as $ass)
		{
			if (empty($ass->Id) || !$ass->Id)
			{
				throw new Exception($ass->message);
			}
		}
	}
722010
public function create($userId, $username, $hash, $rawKey): AuthenticationRecordInterface
    {
        return new Authentication($userId, $username, $hash, $rawKey);
    }
83140
public function deleteReview($userId, $reviewId)
    {
        $review = $this->getReviewById($reviewId);

        $this->validateUserPermissionsToManageReview($review, $userId);

        $review->delete();
    }
70503
public function UpdateUser($UserID) {
      // Retrieve a draft count
      $CountDrafts = $this->GetCount($UserID);
      
      // Update CountDrafts column of user table fot this user
      Gdn::UserModel()->SetField($UserID, 'CountDrafts', $CountDrafts);
   }
976390
public static function instance($userid, $strictness = MUST_EXIST) {
        global $DB;

        if ($context = context::cache_get(CONTEXT_USER, $userid)) {
            return $context;
        }

        if (!$record = $DB->get_record('context', array('contextlevel' => CONTEXT_USER, 'instanceid' => $userid))) {
            if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) {
                $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
            }
        }

        if ($record) {
            $context = new context_user($record);
            context::cache_add($context);
            return $context;
        }

        return false;
    }
503941
public static function get_contexts_for_userid(int $userid) : \core_privacy\local\request\contextlist {
        $contextlist = new \core_privacy\local\request\contextlist();

        // Find the modifications we made on badges (course & system).
        $sql = "
            SELECT ctx.id
              FROM {badge} b
              JOIN {context} ctx
                ON (b.type = :typecourse AND b.courseid = ctx.instanceid AND ctx.contextlevel = :courselevel)
                OR (b.type = :typesite AND ctx.id = :syscontextid)
             WHERE b.usermodified = :userid1
                OR b.usercreated = :userid2";
        $params = [
            'courselevel' => CONTEXT_COURSE,
            'syscontextid' => SYSCONTEXTID,
            'typecourse' => BADGE_TYPE_COURSE,
            'typesite' => BADGE_TYPE_SITE,
            'userid1' => $userid,
            'userid2' => $userid,
        ];
        $contextlist->add_from_sql($sql, $params);

        // Find where we've manually awarded a badge (recipient user context).
        $sql = "
            SELECT ctx.id
              FROM {badge_manual_award} bma
              JOIN {context} ctx
                ON ctx.instanceid = bma.recipientid
               AND ctx.contextlevel = :userlevel
             WHERE bma.issuerid = :userid";
        $params = [
            'userlevel' => CONTEXT_USER,
            'userid' => $userid,
        ];
        $contextlist->add_from_sql($sql, $params);

        // Now find where there is real user data (user context).
        $sql = "
            SELECT ctx.id
              FROM {context} ctx
         LEFT JOIN {badge_manual_award} bma
                ON bma.recipientid = ctx.instanceid
         LEFT JOIN {badge_issued} bi
                ON bi.userid = ctx.instanceid
         LEFT JOIN {badge_criteria_met} bcm
                ON bcm.userid = ctx.instanceid
         LEFT JOIN {badge_backpack} bb
                ON bb.userid = ctx.instanceid
             WHERE ctx.contextlevel = :userlevel
               AND ctx.instanceid = :userid
               AND (bma.id IS NOT NULL
                OR bi.id IS NOT NULL
                OR bcm.id IS NOT NULL
                OR bb.id IS NOT NULL)";
        $params = [
            'userlevel' => CONTEXT_USER,
            'userid' => $userid,
        ];
        $contextlist->add_from_sql($sql, $params);

        return $contextlist;
    }
326403
public function setReceptionCode($newCode, $userId)
    {
        $oldCode = $this->respondentTrack->getReceptionCode();
        
        if (! $newCode instanceof \Gems_Util_ReceptionCode) {
            $newCode = $this->util->getReceptionCode($newCode);
        }

        // Use the repesondent track function as that cascades the consent code
        $changed = $this->respondentTrack->setReceptionCode($newCode, $this->formData['gr2t_comment'], $userId);

        if ($this->unDelete) {
            $this->addMessage($this->_('Track restored.'));

            if (isset($this->formData['restore_tokens']) && $this->formData['restore_tokens']) {                
                $count = $this->respondentTrack->restoreTokens($oldCode, $newCode);
                
                $this->addMessage(sprintf($this->plural(
                        '%d token reception codes restored.',
                        '%d tokens reception codes restored.',
                        $count
                        ), $count));
            }
        } else {
            if ($newCode->isStopCode()) {
                $this->addMessage($this->_('Track stopped.'));
            } else {
                $this->addMessage($this->_('Track deleted.'));
            }
        }

        return $changed;
    }
1104606
public function handleOpen(int $userId) : void
    {
        if ($this->presenter->isAjax())
        {
            if (!$this->presenter->user->isAllowed(UserAuthorizator::RES_EDIT_MODAL))
            {
                throw new ForbiddenRequestException;
            }

            $this->userId = $userId;

            $this->presenter->handleModalToggle('show', '#wakers_user_edit_modal', FALSE);

            $this->onOpen();
        }
    }