Check if the token should be enabled / disabled due to conditions

@param \GemS_Tracker_Token $token
@param array $round
@param int   $userId Id of the user who takes the action (for logging)
@return int The number of tokens changed by this code
504108
protected function checkTokenCondition(\GemS_Tracker_Token $token, $round, $userId)
    {        
        $skipCode = $this->util->getReceptionCodeLibrary()->getSkipString();

        // Only if we have a condition, the token is not yet completed and 
        // receptioncode is ok or skip we evaluate the condition
        if (empty($round['gro_condition']) ||
            $token->isCompleted() ||
            !($token->getReceptionCode()->isSuccess() || $token->getReceptionCode()->getCode() == $skipCode)) {
        
            return 0;            
        }

        $changed   = 0;
        $condition = $this->loader->getConditions()->loadCondition($round['gro_condition']);
        $newStatus = $condition->isRoundValid($token);
        $oldStatus = $token->getReceptionCode()->isSuccess();

        if ($newStatus !== $oldStatus) {
            $changed = 1;
            if ($newStatus == false) {
                $message = $this->_('Skipped by condition %s: %s');
                $newCode = $skipCode;
            } else {
                $message = $this->_('Activated by condition %s: %s');
                $newCode = $this->util->getReceptionCodeLibrary()->getOKString();
            }            

            $token->setReceptionCode($newCode,
                    sprintf($message, $condition->getName(), $condition->getRoundDisplay($token->getTrackId(), $token->getRoundId())),
                    $userId);

            if ($newStatus == true) {
                // Token was made valid, now calc the dates
                $this->checkTokenDates($token, $round, $userId);
            }
        }

        return $changed;
    }
929298
public function checkMissingUserId(): bool
    {
        if (!empty($this->id_user)) {
            return false;
        }

        $message = 'Can not perform action without set user id. Please set id via setIdUser() before calling this method.';

        if (!empty($this->logger)) {
            $this->logger->warning($message);
        }
        else {
            Throw new TokenException($message);
        }

        return true;
    }
1079990
public function getToken($tokenId)
    {
        $tracker = $this->loader->getTracker();
        $token = $tracker->getToken($tokenId);
        return $token;
    }
301020
private function _userId($userId)
    {
        if (!$userId) {
            $currentUser = Craft::$app->getUser()->getIdentity();
            if ($currentUser) {
                $userId = $currentUser->id;
            }
        }
        return (int)($userId);
    }
519063
public function processTokenInsertion(\Gems_Tracker_Token $token)
    {
        if ($token->hasSuccesCode() && (! $token->isCompleted())) {
            // Preparation for a more general object class
            $surveyId   = $token->getSurveyId();

            $next = $token->getRespondentTrack()->getFirstToken();
            while ($next) {

                if ($next->hasSuccesCode() && $next->isCompleted()) {
                    // Check first on survey id and when that does not work by name.
                    if ($next->getSurveyId() == $surveyId) {
                        return $next->getRawAnswers();
                    }
                }
                $next = $next->getNextToken();
            }
        }
    }
540120
public function getActiveRoundToken($roundId, \Gems_Tracker_Token $token = null)
    {
        if ((null !== $token) && $token->hasSuccesCode()) {
            // Cache the token
            //
            // WARNING: This may cause bugs for tracks where two tokens exists
            // with this roundId and a success reception code, but this does speed
            // this function with track engines where that should not occur.
            $this->_activeTokens[$token->getRoundId()] = $token;
        }

        // Nothing to find
        if (! $roundId) {
            return null;
        }

        // Use array_key_exists since there may not be a valid round
        if (! array_key_exists($roundId, $this->_activeTokens)) {
            $tokenSelect = $this->tracker->getTokenSelect();
            $tokenSelect->andReceptionCodes()
                    ->forRespondentTrack($this->_respTrackId)
                    ->forRound($roundId)
                    ->onlySucces();

            // \MUtil_Echo::track($tokenSelect->__toString());

            if ($tokenData = $tokenSelect->fetchRow()) {
                $this->_activeTokens[$roundId] = $this->tracker->getToken($tokenData);
            } else {
                $this->_activeTokens[$roundId] = null;
            }
        }

        return $this->_activeTokens[$roundId];
    }
939684
public function execute($tokenData = null, $userId = null)
    {
        $batch   = $this->getBatch();
        $tracker = $this->loader->getTracker();

        $batch->addToCounter('checkedTokens');
        $token = $tracker->getToken($tokenData);

        $wasAnswered = $token->isCompleted();

        if ($result = $token->checkTokenCompletion($userId)) {
            if ($result & \Gems_Tracker_Token::COMPLETION_DATACHANGE) {
                $i = $batch->addToCounter('resultDataChanges');
                $batch->setMessage('resultDataChanges', sprintf(
                        $this->_('Results and timing changed for %d tokens.'),
                        $i
                        ));

                if ($wasAnswered) {
                    $action  = 'token.data-changed';
                    $message = sprintf($this->_("Token '%s' data has changed."), $token->getTokenId());
                } else {
                    $action  = 'token.answered';
                    $message = sprintf($this->_("Token '%s' was answered."), $token->getTokenId());
                }
                if (! $this->request instanceof \Zend_Controller_Request_Abstract) {
                    $this->request = \Zend_Controller_Front::getInstance()->getRequest();
                }
                $this->accesslog->logEntry(
                        $this->request,
                        $action,
                        true,
                        $message,
                        $token->getArrayCopy(),
                        $token->getRespondentId()
                        );

            }
            if ($result & \Gems_Tracker_Token::COMPLETION_EVENTCHANGE) {
                $i = $batch->addToCounter('surveyCompletionChanges');
                $batch->setMessage('surveyCompletionChanges', sprintf(
                        $this->_('Answers changed by survey completion event for %d tokens.'),
                        $i
                        ));
            }
        }

        if ($token->isCompleted()) {
            $batch->setTask('Tracker_ProcessTokenCompletion', 'tokproc-' . $token->getTokenId(), $tokenData, $userId);
        }

        $batch->setMessage('checkedTokens', sprintf(
                $this->_('Checked %d tokens.'),
                $batch->getCounter('checkedTokens')
                ));

        // Free memory
        $tracker->removeToken($token);
    }
640347
public function verifyToken($messageId, $token)
    {
        try {
            $verification = $this->getTokenResult($messageId, $token);

            return ($verification->getStatusCode() === Verification::STATUS_SUCCESS);
        } catch (Exception $e) {
            return false;
        }
    }
683737
public function getLoginToken(UserInterface $user, UuidInterface $token) : LoginToken
    {
        return new LoginToken(
            $user->getId(),
            $token
        );
    }
1311229
public function deleteAccessToken($userId, AccessToken $accessToken)
    {
        self::requireSession();
        foreach ($this->getAccessTokenList($userId) as $k => $v) {
            if ($accessToken->getProviderId() === $v->getProviderId()) {
                if ($accessToken->getToken() === $v->getToken()) {
                    unset($_SESSION[\sprintf('_oauth2_token_%s', $userId)][$k]);
                }
            }
        }
    }
630666
private function checkView(TokenInterface $token, User $user)
    {
        return $this->isOrganizationManager($token, $user) ?
              VoterInterface::ACCESS_GRANTED : VoterInterface::ACCESS_DENIED;
    }
516174
public function inSource(\Gems_Tracker_Token $token, $surveyId, $sourceSurveyId = null)
    {
        $tokenInfo = $this->getTokenInfo($token, $surveyId, $sourceSurveyId);
        return (boolean) $tokenInfo;
    }
1293735
public function forNextTokenId($tokenId)
    {
        $this->sql_select->join('gems__tokens as ct',
                'gems__tokens.gto_id_respondent_track = ct.gto_id_respondent_track AND
                    gems__tokens.gto_id_token != ct.gto_id_token AND
                        ((gems__tokens.gto_round_order < ct.gto_round_order) OR
                            (gems__tokens.gto_round_order = ct.gto_round_order AND gems__tokens.gto_created < ct.gto_created))',
                array());

        $this->sql_select
                ->where('ct.gto_id_token = ?', $tokenId)
                ->order('gems__tokens.gto_round_order DESC')
                ->order('gems__tokens.gto_created DESC');

        return $this;
    }
1072908
public function is_tracked_user($userid) {
        return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
    }
155391
public function isInputtedTwoFactorAuthCodeCorrect($userId=null) {
        $inputted2faCode = $this->request->input('2facode');

        if (isset($userId)) {
            $sent2faCode     = $this->getUserSmsToken($userId);
        } else {
            $sent2faCode     = $this->request->session()->get('codeToInput');
        }


        if ($inputted2faCode == $sent2faCode) {
            return true;
        }

        return false;
    }
1158563
public static function existsValidToken($token_id, $user_id)
    {
        if (class_exists('\Illuminate\Support\Facades\DB')) {
            return (bool) \Illuminate\Support\Facades\DB::table('oauth_access_tokens')
                ->where('id', $token_id)
                ->where('user_id', $user_id)
                ->where('expires_at', '>=', date('Y-m-d H:i:s'))
                ->get();
        } else {
            return false;
        }
    }
97144
public function findByTokenApiCode($token_api)
	{
		$model = $this->createModel();

		$result = $model->newQuery()->where('token_api', '=', $token_api)->get();

		if (($count = $result->count()) > 1)
		{
			throw new \RuntimeException("Found [$count] users with the same token api.");
		}

		if ( ! $user = $result->first())
		{
			throw new UserNotFoundException("A user was not found with the given token api.");
		}

		return $user;
	}