Save or update subscriber information.
@throws \Nette\Application\BadRequestException
@param int $userId
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();
        }
    }
1237856
public function setUserId( $userId )
    {
        $this->_user    = null;
        $this->userId   = ( (int) $userId ) ?: null;
        return $this;
    }
1197864
public function dislike($userId = null)
    {
        app(LikeableServiceContract::class)->addLikeTo($this, LikeType::DISLIKE, $userId);
    }
1236864
public function isUnread($userId)
    {
        try {
            $participant = $this->getParticipantFromUser($userId);
            if ($this->updated_at > $participant->last_read) {
                return true;
            }
        } catch (ModelNotFoundException $e) {
            // do nothing
        }

        return false;
    }
850433
public function archive($userId, $callId)
    {

        /** @var StateStorage $stateStorage */
        $stateStorage = $this->getServiceManager()->get(StateStorage::SERVICE_ID);

        $state = $stateStorage->get($userId, $callId);

        return (!is_null($state)) ? $this->getFileSystem()->write($this->generateSerial($userId, $callId), $state) : false;
    }
286375
public function updateUser(User $user)
    {
        $this->find("id", $user->id);
        $this->setUserData($user);
        $this->save();
    }
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;
    }
610844
public function save(Request $request, UserInterface $user)
    {
        $eid = $request->get('eid');
        $language = $request->get('language');
        $tid = $request->get('tid');
        $teaserId = $request->get('teaser_id');
        $isPublish = $request->get('isPublish');
        $values = $request->get('values');
        $publishComment = $request->get('publishComment');

        if ($values) {
            $values = json_decode($values, true);
        }

        $element = $this->elementService->findElement($eid);
        $elementtype = $this->elementService->findElementtype($element);
        $elementtypeStructure = $elementtype->getStructure();

        $oldElementVersion = $this->elementService->findLatestElementVersion($element);
        $oldElementStructure = $this->elementService->findElementStructure($oldElementVersion, 'de');
        $oldVersion = $oldElementVersion->getVersion();
        $isMaster = $element->getMasterLanguage() === $language;

        $tree = $this->treeManager->getByNodeId($tid);
        $node = $tree->get($tid);

        $teaser = null;
        if ($teaserId) {
            $teaser = $this->teaserManager->find($teaserId);
        }

        $comment = null;
        if ($request->get('comment')) {
            $comment = $request->get('comment');
        }

        if ($language === $element->getMasterLanguage()) {
            $elementStructure = new ElementStructure();
            if ($oldElementStructure->getDataId()) {
                $elementStructure
                    ->setDataId($oldElementStructure->getDataId())
                    ->setDsId($oldElementStructure->getDsId())
                    ->setType('root')
                    ->setName($oldElementStructure->getName());
            } else {
                $elementStructure
                    ->setDataId(UuidUtil::generate())
                    ->setDsId($elementtypeStructure->getRootDsId())
                    ->setType('root')
                    ->setName($elementtypeStructure->getRootNode()->getName());
            }
            $map = $this->applyStructure($elementStructure, $elementtypeStructure, $values, $language, $oldElementStructure);
            $this->applyOldValues($elementStructure, $oldElementStructure, $elementtypeStructure, $language);
            $this->applyValues($elementStructure, $elementtypeStructure, $values, $language, $map, null);
        } else {
            $elementStructure = clone $oldElementStructure;
            $this->applyValues($elementStructure, $elementtypeStructure, $values, $language, null, $element->getMasterLanguage());
        }

        $elementStructure->setId(null);

        $rii = new \RecursiveIteratorIterator($elementStructure->getIterator(), \RecursiveIteratorIterator::SELF_FIRST);
        foreach ($rii as $structure) {
            /* @var $structure ElementStructure */
            $structure->setId(null);
        }

        $elementVersion = $this->elementService->createElementVersion($element, $elementStructure, $language, $user->getId(), $comment);

        if ($teaser) {
            $this->saveTeaserData($teaser, $language, $request);
        } else {
            $this->saveNodeData($node, $language, $request);
        }

        // TODO: available languages
        $this->saveMeta($elementVersion, $language, $isMaster, ['de'], $request);

        $event = new SaveElementEvent($element, $language, $oldVersion);
        $this->eventDispatcher->dispatch(ElementEvents::SAVE_ELEMENT, $event);

        $publishSlaves = [];
        if ($isPublish) {
            $publishSlaves = $this->checkPublishSlaves($elementVersion, $node, $teaser, $language);
            if ($teaser) {
                $this->publishTeaser($elementVersion, $teaser, $language, $user->getId(), $publishComment, $publishSlaves);
            } else {
                $this->publishTreeNode($elementVersion, $node, $language, $user->getId(), $publishComment, $publishSlaves);
            }
        }

        $status = '';
        if ($teaser) {
            if ($this->teaserManager->isPublished($teaser, $language)) {
                $status = $this->teaserManager->isAsync($teaser, $language) ? 'async' : 'online';
            }
        } else {
            if ($tree->isPublished($node, $language)) {
                $status = $tree->isAsync($node, $language) ? 'async' : 'online';
            }
        }

        return [$elementVersion, $node, $teaser, $publishSlaves, $status];
    }
1219355
public static function set_user_id($user_id) {
	if (self::is_active() == false) {
		$exception = bootstrap::get_library('exception');
		throw new $exception('inactive session');
	}
	
	$_SESSION['_session_user_id'] = $user_id;
}
768891
public function add_user_context(int $userid) : contextlist {
        $sql = "SELECT DISTINCT ctx.id
                  FROM {context} ctx
                 WHERE ctx.contextlevel = :contextlevel
                   AND ctx.instanceid = :instanceid";
        return $this->add_from_sql($sql, ['contextlevel' => CONTEXT_USER, 'instanceid' => $userid]);
    }
431455
public function edit($id)
    {
        if (!$this->request->is(['get', 'put'])) {
            throw new MethodNotAllowedException();
        }

        /** @var User $user */
        $user = $this->Users->getUserAndGroups($id);

        if ($this->request->is('put')) {
            $user = $this->Users->patchEntity($user, $this->request->data, ['associated' => 'Groups']);
            $userActivated = ($user->dirty('active') && $user->active);
            if ($userActivated) {
                // do not allow a user to be activated if his email address is not verified
                if (!$user->verified) {
                    $user->active = false;
                    $userActivated = false;
                } else {
                    $user->activate();
                }
            }
            $userDeactivated = ($user->dirty('active') && !$user->active);
            if ($userDeactivated) {
                // do not allow a user to deactivate his own account
                if ($user->id === Wasabi::user()->id) {
                    $user->active = true;
                    $userDeactivated = false;
                } else {
                    $user->deactivate();
                }
            }
            if ($this->Users->save($user, ['associated' => 'Groups'])) {
                if ($user->id === Wasabi::user()->id) {
                    $updateUser = $this->Users->get($user->id);
                    $updateUser->group_id = $this->Users->UsersGroups->getGroupIds($updateUser->id);
                    $this->Auth->setUser($updateUser->toArray());
                    Wasabi::user($updateUser);
                }
                if ($userActivated && $user->verified) {
                    $this->getMailer('Wasabi/Core.User')->send('activatedEmail', [$user]);
                }
                if ($userDeactivated && $user->verified) {
                    $this->getMailer('Wasabi/Core.User')->send('deactivatedEmail', [$user]);
                }
                $this->Flash->success(__d('pb', 'The user <strong>{0}</strong> has been updated.', $user->fullName()));
                $this->redirect($this->Filter->getBacklink(['action' => 'index'], $this->request));
                return;
            } else {
                $this->Flash->error($this->formErrorMessage);
            }
        }

        $groups = $this->Users->Groups->find('list')->order('id ASC');

        // users that are no admin, may not select the admin group
        if (Wasabi::user()->hasAccessLevel(Permission::OWN)) {
            $groups->where(['id <>' => 1]);
        }

        $this->set([
            'user' => $user,
            'groups' => $groups,
            'languages' => Hash::map(Configure::read('languages.backend'), '{n}', function ($language) {
                return [
                    'value' => $language->id,
                    'text' => $language->name
                ];
            })
        ]);

        $this->render('add');
    }
717227
protected function updateUser($user_id)
    {
        if (!$this->isError() && !$this->user->update($user_id, $this->getSubmitted())) {
            $this->errorAndExit($this->text('Unexpected result'));
        }
    }
55420
protected static function delete_user_data(int $userid) {
        global $DB;
        // Delete this user's subscriptions first.
        subscription_manager::delete_user_subscriptions($userid);
        // Because we only use user contexts the instance ID is the user ID.
        // Get the rules and check if this user has the capability to delete them.
        $rules = $DB->get_records('tool_monitor_rules', ['userid' => $userid]);
        foreach ($rules as $ruledata) {
            $rule = rule_manager::get_rule($ruledata);
            // If no-one is suscribed to the rule then it is safe to delete.
            if ($rule->can_manage_rule($userid) && subscription_manager::count_rule_subscriptions($rule->id) == 0) {
                $rule->delete_rule();
            }
        }
    }
637490
public static function unlock($userId)
    {
        $model = self::findOne(['user_id' => $userId]);
    
        if ($model) {
            $model->updateAttributes([
                'last_timestamp' => time(),
                'lock_table' => '',
                'lock_pk' => '',
                'lock_translation' => '',
                'lock_translation_args' => '',
            ]);
        }
    }
339899
protected function saving($name, $userId, $value = null, $isNew = true)
    {
        $meta = $this->getModel()->search($name, $userId)->first();

        if (is_null($value) || $value === ':to-be-deleted:') {
            !is_null($meta) && $meta->delete();
            return;
        }

        if (true === $isNew && is_null($meta)) {
            $meta = $this->getModel();

            $meta->name    = $name;
            $meta->user_id = $userId;
        }

        $meta->value = serialize($value);
        $meta->save();
    }
817061
public static function fill_subscription_cache_for_course($courseid, $userid) {
        global $DB;

        if (!isset(self::$forumcache[$userid])) {
            self::$forumcache[$userid] = array();
        }

        $sql = "SELECT
                    f.id AS forumid,
                    s.id AS subscriptionid
                FROM {forum} f
                LEFT JOIN {forum_subscriptions} s ON (s.forum = f.id AND s.userid = :userid)
                WHERE f.course = :course
                AND f.forcesubscribe <> :subscriptionforced";

        $subscriptions = $DB->get_recordset_sql($sql, array(
            'course' => $courseid,
            'userid' => $userid,
            'subscriptionforced' => FORUM_FORCESUBSCRIBE,
        ));

        foreach ($subscriptions as $id => $data) {
            self::$forumcache[$userid][$id] = !empty($data->subscriptionid);
        }
        $subscriptions->close();
    }
369259
public function updateUser($userId, Request $request)
    {
        $user = $this->userService->loadUser($userId);

        $updateStruct = $this->inputDispatcher->parse(
            new Message(
                array(
                    'Content-Type' => $request->headers->get('Content-Type'),
                    // @todo Needs refactoring! Temporary solution so parser has access to URL
                    'Url' => $request->getPathInfo(),
                ),
                $request->getContent()
            )
        );

        if ($updateStruct->sectionId !== null) {
            $section = $this->sectionService->loadSection($updateStruct->sectionId);
            $this->sectionService->assignSection(
                $user->getVersionInfo()->getContentInfo(),
                $section
            );
        }

        $updatedUser = $this->userService->updateUser($user, $updateStruct->userUpdateStruct);
        $updatedContentInfo = $updatedUser->getVersionInfo()->getContentInfo();
        $mainLocation = $this->locationService->loadLocation($updatedContentInfo->mainLocationId);
        $contentType = $this->contentTypeService->loadContentType($updatedContentInfo->contentTypeId);

        return new Values\RestUser(
            $updatedUser,
            $contentType,
            $updatedContentInfo,
            $mainLocation,
            $this->contentService->loadRelations($updatedUser->getVersionInfo())
        );
    }