May be used to revert accidentally granted acceptance for another user

@param int $policyversionid
@param int $userid
@param null $note
334630
public static function revoke_acceptance($policyversionid, $userid, $note = null) {
        global $DB, $USER;
        if (!$userid) {
            $userid = $USER->id;
        }
        self::can_accept_policies([$policyversionid], $userid, true);

        if ($currentacceptance = $DB->get_record('tool_policy_acceptances',
                ['policyversionid' => $policyversionid, 'userid' => $userid])) {
            $realuser = manager::get_realuser();
            $updatedata = ['id' => $currentacceptance->id, 'status' => 0, 'timemodified' => time(),
                'usermodified' => $realuser->id, 'note' => $note];
            $DB->update_record('tool_policy_acceptances', $updatedata);
            acceptance_updated::create_from_record((object)($updatedata + (array)$currentacceptance))->trigger();
        }

        static::update_policyagreed($userid);
    }
637647
public function update($userId, $payload)
    {
        if (isset($payload['meta']) && ! isset($payload['meta']['terms_and_cond'])) {
            throw new Exception("You must agree to the terms and conditions.", 1);
        }

        try {
            return DB::transaction(function () use ($userId, $payload) {
                $user = $this->model->find($userId);

                if (isset($payload['meta']['marketing']) && ($payload['meta']['marketing'] == 1 || $payload['meta']['marketing'] == 'on')) {
                    $payload['meta']['marketing'] = 1;
                } else {
                    $payload['meta']['marketing'] = 0;
                }

                if (isset($payload['meta']['terms_and_cond']) && ($payload['meta']['terms_and_cond'] == 1 || $payload['meta']['terms_and_cond'] == 'on')) {
                    $payload['meta']['terms_and_cond'] = 1;
                } else {
                    $payload['meta']['terms_and_cond'] = 0;
                }

                $userMetaResult = (isset($payload['meta'])) ? $user->meta->update($payload['meta']) : true;

                $user->update($payload);

                if (isset($payload['roles'])) {
                    $this->unassignAllRoles($userId);
                    $this->assignRole($payload['roles'], $userId);
                }

                return $user;
            });
        } catch (Exception $e) {
            throw new Exception("We were unable to update your profile", 1);
        }
    }
377485
public static function delete($versionid) {
        global $DB;

        $version = static::get_policy_version($versionid);
        if (!self::can_delete_version($version)) {
            // Current version can not be deleted.
            return;
        }

        $DB->delete_records('tool_policy_versions', ['id' => $versionid]);

        if (!$DB->record_exists('tool_policy_versions', ['policyid' => $version->policyid])) {
            // This is a single version in a policy. Delete the policy.
            $DB->delete_records('tool_policy', ['id' => $version->policyid]);
        }
    }
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;
    }
1013229
public function loadPoliciesByUserId($userId)
    {
        try {
            return $this->innerGateway->loadPoliciesByUserId($userId);
        } catch (DBALException $e) {
            throw new RuntimeException('Database error', 0, $e);
        } catch (PDOException $e) {
            throw new RuntimeException('Database error', 0, $e);
        }
    }
339889
public static function getRoleIdByAppIdAndUserId($app_id, $user_id)
    {
        $cacheKey = static::makeRoleIdCacheKey($app_id, $user_id);
        $result = \Cache::remember($cacheKey, \Config::get('df.default_cache_ttl'),
            function () use ($app_id, $user_id) {
                try {
                    return static::whereAppId($app_id)->whereUserId($user_id)->value('role_id');
                } catch (ModelNotFoundException $ex) {
                    return null;
                }
            });

        return $result;
    }
4481
public function addHistoryEntry($employeeId, $requestId, string $date, string $note)
    {
        $xml = "
            <history>
                <date>{$date}</date>
                <eventType>used</eventType>
                <timeOffRequestId>{$requestId}</timeOffRequestId>
                <note>{$note}</note>
            </history>
        ";

        $this->put("employees/{$employeeId}/time_off/history", $xml);
    }
50836
public function addPolicyByRoleDraft($roleId, Policy $policy)
    {
        $legacyPolicy = clone $policy;
        $legacyPolicy->originalId = $policy->id;
        $this->limitationConverter->toLegacy($legacyPolicy);

        $this->roleGateway->addPolicy($roleId, $legacyPolicy);
        $policy->id = $legacyPolicy->id;
        $policy->originalId = $legacyPolicy->originalId;
        $policy->roleId = $legacyPolicy->roleId;

        return $policy;
    }
280975
public static function transform_standard_log_record_for_userid($record, $userid) {

        // Restore the event to try to get the name, description and other field.
        $restoredevent = static::restore_event_from_standard_record($record);
        if ($restoredevent) {
            $name = $restoredevent->get_name();
            $description = $restoredevent->get_description();
            $other = $restoredevent->other;

        } else {
            $name = $record->eventname;
            $description = "Unknown event ({$name})";
            $other = \tool_log\helper\reader::decode_other($record->other);
        }

        $realuserid = $record->realuserid;
        $isauthor = $record->userid == $userid;
        $isrelated = $record->relateduserid == $userid;
        $isrealuser = $realuserid == $userid;
        $ismasqueraded = $realuserid !== null && $record->userid != $realuserid;
        $ismasquerading = $isrealuser && !$isauthor;
        $isanonymous = $record->anonymous;

        $data = [
            'name' => $name,
            'description' => $description,
            'timecreated' => transform::datetime($record->timecreated),
            'origin' => static::transform_origin($record->origin),
            'ip' => $isauthor ? $record->ip : '',
            'other' => $other ? $other : []
        ];

        if ($isanonymous) {
            $data['action_was_done_anonymously'] = transform::yesno($isanonymous);
        }
        if ($isauthor || !$isanonymous) {
            $data['authorid'] = transform::user($record->userid);
            $data['author_of_the_action_was_you'] = transform::yesno($isauthor);
        }

        if ($record->relateduserid) {
            $data['relateduserid'] = transform::user($record->relateduserid);
            $data['related_user_was_you'] = transform::yesno($isrelated);
        }

        if ($ismasqueraded) {
            $data['author_of_the_action_was_masqueraded'] = transform::yesno(true);
            if ($ismasquerading || !$isanonymous) {
                $data['masqueradinguserid'] = transform::user($realuserid);
                $data['masquerading_user_was_you'] = transform::yesno($ismasquerading);
            }
        }

        return $data;
    }
398041
public function revoke($itemName,$userId)
	{
		if(isset($this->_assignments[$userId][$itemName]))
		{
			unset($this->_assignments[$userId][$itemName]);
			return true;
		}
		else
			return false;
	}
205539
private void initializeUserStoreAndCheckVersion() throws Exception {

    int i = 0;
    String version = com.evernote.edam.userstore.Constants.EDAM_VERSION_MAJOR + "."
        + com.evernote.edam.userstore.Constants.EDAM_VERSION_MINOR;

    for (String url : mBootstrapServerUrls) {
      i++;
      try {
        EvernoteUserStoreClient userStoreClient = mEvernoteSession.getEvernoteClientFactory().getUserStoreClient(getUserStoreUrl(url), null);

        if (!userStoreClient.checkVersion(EvernoteUtil.generateUserAgentString(mEvernoteSession.getApplicationContext()),
                com.evernote.edam.userstore.Constants.EDAM_VERSION_MAJOR,
                com.evernote.edam.userstore.Constants.EDAM_VERSION_MINOR)) {
          throw new ClientUnsupportedException(version);
        }

        mBootstrapServerUsed = url;
        return;
      } catch (ClientUnsupportedException cue) {

        Log.e(LOGTAG, "Invalid Version", cue);
        throw cue;
      } catch (Exception e) {
        if (i < mBootstrapServerUrls.size()) {
          Log.e(LOGTAG, "Error contacting bootstrap server=" + url, e);
        } else {
          throw e;
        }
      }
    }
  }
917954
protected function accept_and_revoke_policies() {
        global $USER;

        if ($this->isexistinguser) {
            // Existing user.
            if (!empty($this->action) && confirm_sesskey()) {
                // The form has been sent, update policies acceptances.
                $lang = current_language();
                // Accept / revoke policies.
                $acceptversionids = [];
                $declineversionids = [];

                foreach ($this->policies as $policy) {
                    if (in_array($policy->id, $this->listdocs)) {
                        if (in_array($policy->id, $this->agreedocs)) {
                            $acceptversionids[] = $policy->id;
                        } else if (in_array($policy->id, $this->declinedocs)) {
                            $declineversionids[] = $policy->id;
                        } else {
                            // If the policy was displayed but not answered, revoke the eventually given acceptance.
                            api::revoke_acceptance($policy->id, $this->behalfid);
                        }
                    }
                }

                api::accept_policies($acceptversionids, $this->behalfid, null, $lang);
                api::decline_policies($declineversionids, $this->behalfid, null, $lang);

                // Show a message to let know the user he/she must agree all the policies.
                if ((count($acceptversionids) + count($declineversionids)) != count($this->policies)) {
                    $message = (object) [
                        'type' => 'error',
                        'text' => get_string('mustagreetocontinue', 'tool_policy')
                    ];
                } else {
                    $message = (object) [
                        'type' => 'success',
                        'text' => get_string('acceptancessavedsucessfully', 'tool_policy')
                    ];
                }
                $this->messages[] = $message;
            } else if (!empty($this->policies) && empty($USER->policyagreed)) {
                // Inform users they must agree to all policies before continuing.
                $message = (object) [
                    'type' => 'error',
                    'text' => get_string('mustagreetocontinue', 'tool_policy')
                ];
                $this->messages[] = $message;
            }
        } else {
            // New user.
            if (!empty($this->action) && confirm_sesskey()) {
                $currentpolicyversionids = [];
                $presignupcache = \cache::make('core', 'presignup');
                $acceptances = $presignupcache->get('tool_policy_policyversionidsagreed');
                if (!$acceptances) {
                    $acceptances = [];
                }
                foreach ($this->policies as $policy) {
                    $currentpolicyversionids[] = $policy->id;
                    if (in_array($policy->id, $this->listdocs)) {
                        if (in_array($policy->id, $this->agreedocs)) {
                            $acceptances[] = $policy->id;
                        } else {
                            $acceptances = array_values(array_diff($acceptances, [$policy->id]));
                        }
                    }
                }
                // If the user has accepted all the policies, add it to the session to let continue with the signup process.
                $this->signupuserpolicyagreed = empty(array_diff($currentpolicyversionids, $acceptances));
                $presignupcache->set('tool_policy_userpolicyagreed', $this->signupuserpolicyagreed);
                $presignupcache->set('tool_policy_policyversionidsagreed', $acceptances);
            } else if (empty($this->policies)) {
                // There are no policies to agree to. Update the policyagreed value to avoid show empty consent page.
                \cache::make('core', 'presignup')->set('tool_policy_userpolicyagreed', 1);
            }
            if (!empty($this->policies) && !$this->signupuserpolicyagreed) {
                // During the signup process, inform users they must agree to all policies before continuing.
                $message = (object) [
                    'type' => 'error',
                    'text' => get_string('mustagreetocontinue', 'tool_policy')
                ];
                $this->messages[] = $message;
            }
        }
    }
838475
public function reset($userId = null, $code = null)
    {
        try {
            if (post('postback')) {
                return $this->reset_onSubmit();
            }

            if (!$userId || !$code) {
                throw new ApplicationException(trans('backend::lang.account.reset_error'));
            }
        }
        catch (Exception $ex) {
            Flash::error($ex->getMessage());
        }

        $this->vars['code'] = $code;
        $this->vars['id'] = $userId;
    }
649654
public function revert(BlockInterface $block, $version)
    {
        $block->accept(new RevertVisitor($this, $version));

        if ($block instanceof BlockContainerInterface) {
            self::treeAddMissingChildren($block);
            self::treeRemoveInvalidChildren($block);
            $block->accept(new SortVisitor());
        }
    }
175820
public function deleteRating($userId, $ratingId)
    {
        $rating = $this->getRatingById($ratingId);

        $this->validateUserPermissionsToManageRating($rating, $userId);

        $rating = $this->disableSubShopDeleteProtectionForRating($rating);
        $rating->delete();
    }
540015
public function acceptInvitation()
    {
        if ($this->isInvitationTokenAccepted()) {
            throw new UserInvitationAlreadyAcceptedException();
        }
        if ($this->isInvitationTokenExpired()) {
            throw new UserTokenExpiredException();
        }
        $this->invitationToken = null;
        $this->updatedOn = new \DateTimeImmutable();
        $this->publish(
            new UserRegistered(
                $this->id(),
                $this->email()
            )
        );
    }
519070
public function unassignUserFromUserGroup($userId, $groupPath)
    {
        $user = $this->userService->loadUser($userId);
        $userGroupLocation = $this->locationService->loadLocation(trim($groupPath, '/'));

        $userGroup = $this->userService->loadUserGroup(
            $userGroupLocation->contentId
        );

        try {
            $this->userService->unAssignUserFromUserGroup($user, $userGroup);
        } catch (ApiExceptions\InvalidArgumentException $e) {
            // User is not in the group
            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
        );
    }