Insert new empty session record.
@param int $userid
@return \stdClass the new record
195264
protected static function add_session_record($userid) {
        global $DB;
        $record = new \stdClass();
        $record->state       = 0;
        $record->sid         = session_id();
        $record->sessdata    = null;
        $record->userid      = $userid;
        $record->timecreated = $record->timemodified = time();
        $record->firstip     = $record->lastip = getremoteaddr();

        $record->id = $DB->insert_record('sessions', $record);

        return $record;
    }
325931
public function newInstance(
        string $createdByUserId,
        string $createdReason = Tracking::UNKNOWN_REASON
    ) {
        /** @var PluginWrapper $new */
        $new = parent::newInstance(
            $createdByUserId,
            $createdReason
        );

        // if no id, then it has not been save and can be returned
        if (empty($new->pluginWrapperId)) {
            return $new;
        }

        $new->pluginWrapperId = null;

        // @deprecated <deprecated-site-wide-plugin>
        //if (!$new->instance->isSiteWide()) {
            $pluginInstance = $new->instance->newInstance(
                $createdByUserId,
                $createdReason
            );
            $new->instance = $pluginInstance;
        //}

        return $new;
    }
833937
public function load($userId)
    {
        $query = $this->handler->createSelectQuery();
        $query->select(
            $this->handler->quoteColumn('contentobject_id', 'ezuser'),
            $this->handler->quoteColumn('login', 'ezuser'),
            $this->handler->quoteColumn('email', 'ezuser'),
            $this->handler->quoteColumn('password_hash', 'ezuser'),
            $this->handler->quoteColumn('password_hash_type', 'ezuser'),
            $this->handler->quoteColumn('is_enabled', 'ezuser_setting'),
            $this->handler->quoteColumn('max_login', 'ezuser_setting')
        )->from(
            $this->handler->quoteTable('ezuser')
        )->leftJoin(
            $this->handler->quoteTable('ezuser_setting'),
            $query->expr->eq(
                $this->handler->quoteColumn('user_id', 'ezuser_setting'),
                $this->handler->quoteColumn('contentobject_id', 'ezuser')
            )
        )->where(
            $query->expr->eq(
                $this->handler->quoteColumn('contentobject_id', 'ezuser'),
                $query->bindValue($userId, null, \PDO::PARAM_INT)
            )
        );

        $statement = $query->prepare();
        $statement->execute();

        return $statement->fetchAll(\PDO::FETCH_ASSOC);
    }
417575
public function unenrol_user(stdClass $instance, $userid) {
        global $DB;

        // Get the tool associated with this instance. Note - it may not exist if we have deleted
        // the tool. This is fine because we have already cleaned the 'enrol_lti_users' table.
        if ($tool = $DB->get_record('enrol_lti_tools', array('enrolid' => $instance->id), 'id')) {
            // Need to remove the user from the users table.
            $DB->delete_records('enrol_lti_users', array('userid' => $userid, 'toolid' => $tool->id));
        }

        parent::unenrol_user($instance, $userid);
    }
1043512
public static function getSessionWithUserId($userid)
	{
		// get list of all sessions
		$sessions = \App::get('session')->getStore()->all(array(
			'guest'    => 0,
			'distinct' => 1
		));

		// see if any session matches our userid
		foreach ($sessions as $session)
		{
			if ($session->userid == $userid)
			{
				return $session;
			}
		}

		// nothing found
		return null;
	}
988407
protected function toResponseDatabase($userId)
    {
        $responseDb = $this->project->getResponseDatabase();

        // WHY EXPLANATION!!
        //
        // For some reason mysql prepared parameters do nothing with a \Zend_Db_Expr
        // object and that causes an error when using CURRENT_TIMESTAMP
        $current = \MUtil_Date::now()->toString(\Gems_Tracker::DB_DATETIME_FORMAT);
        $rValues = array(
            'gdr_id_token'   => $this->_tokenId,
            'gdr_changed'    => $current,
            'gdr_changed_by' => $userId,
            'gdr_created'    => $current,
            'gdr_created_by' => $userId,
        );
        $responses = $this->getRawAnswers();
        unset($responses['token'], $responses['id'], $responses['lastpage'],
                $responses['startlanguage'], $responses['submitdate'], $responses['startdate'],
                $responses['datestamp']);

        // first read current responses to differentiate between insert and update
        $responseSelect = $responseDb->select()->from('gemsdata__responses', array('gdr_answer_id', 'gdr_response'))
                ->where('gdr_id_token = ?', $this->_tokenId);
        $currentResponses = $responseDb->fetchPairs($responseSelect);

        if (! $currentResponses) {
            $currentResponses = array();
        }
        // \MUtil_Echo::track($currentResponses, $responses);

        // Prepare sql
        $sql = "UPDATE gemsdata__responses
            SET `gdr_response` = ?, `gdr_changed` = ?, `gdr_changed_by` = ?
            WHERE gdr_id_token = ? AND gdr_answer_id = ? AND gdr_answer_row = 1";
        $statement = $responseDb->prepare($sql);

        $inserts = array();
        foreach ($responses as $fieldName => $response) {
            $rValues['gdr_answer_id']  = $fieldName;
            if (is_array($response)) {
                $response = join('|', $response);
            }
            $rValues['gdr_response']  = $response;

            if (array_key_exists($fieldName, $currentResponses)) {    // Already exists, do update
                // But only if value changed
                if ($currentResponses[$fieldName] != $response) {
                    try {
                        // \MUtil_Echo::track($sql, $rValues['gdr_id_token'], $fieldName, $response);
                        $statement->execute(array(
                            $response,
                            $rValues['gdr_changed'],
                            $rValues['gdr_changed_by'],
                            $rValues['gdr_id_token'],
                            $fieldName
                        ));
                    } catch (\Zend_Db_Statement_Exception $e) {
                        error_log($e->getMessage());
                        \Gems_Log::getLogger()->logError($e);
                    }
                }
            } else {
                // We add the inserts together in the next prepared statement to improve speed
                $inserts[$fieldName] = $rValues;
            }
        }

        if (count($inserts)>0) {
            // \MUtil_Echo::track($inserts);
            try {
                $fields = array_keys(reset($inserts));
                $fields = array_map(array($responseDb, 'quoteIdentifier'), $fields);
                $sql = 'INSERT INTO gemsdata__responses (' .
                        implode(', ', $fields) . ') VALUES (' .
                        implode(', ', array_fill(1, count($fields), '?')) . ')';

                // \MUtil_Echo::track($sql);
                $statement = $responseDb->prepare($sql);

                foreach($inserts as $insert) {
                    // \MUtil_Echo::track($insert);
                    $statement->execute($insert);
                }

            } catch (\Zend_Db_Statement_Exception $e) {
                error_log($e->getMessage());
                \Gems_Log::getLogger()->logError($e);
            }
        }
    }
1120860
public UserEntity createNewUser(String userId) {
    checkAuthorization(Permissions.CREATE, Resources.USER, null);
    return new UserEntity(userId);
  }
599934
public function userIdToOpenid(string $userId, int $agentId = null)
    {
        $params = [
            'userid' => $userId,
            'agentid' => $agentId,
        ];

        return $this->httpPostJson('cgi-bin/user/convert_to_openid', $params);
    }
377124
public function generateRecoveryToken($userId)
	{
		$token = SELF::generateToken();

		$update = array(
			'reset_password_token' => Passwords::hash($token),
			'reset_password_requested_at' => new DateTime(),
		);

		$this->repository->update($userId, $update);

		return $token;
	}
461259
public function generate($userId)
    {
        $metadata = $this->metadata();
        $this->setIdent(bin2hex(random_bytes(16)));
        $this->setToken(bin2hex(random_bytes(32)));
        $this->setUserId($userId);
        $this->setExpiry('now + '.$metadata['cookieDuration']);

        return $this;
    }
547845
public function newInstance(
        string $createdByUserId,
        string $createdReason = Tracking::UNKNOWN_REASON
    ) {
        /** @var static $new */
        $new = parent::newInstance(
            $createdByUserId,
            $createdReason
        );

        // if no id, then it has not been save and can be returned
        if (empty($new->pageId)) {
            return $new;
        }

        $new->pageId = null;
        $new->name = null;
        $new->parent = null;

        return $new;
    }
1331271
private function buildBatch($userId)
    {
        $batch = array();

        while ($method = $this->getQueue()->dequeue(MethodInterface::SERVER_PLATFORM)) {
            $batch[] = $this->getMethodData($method, $userId);
        }

        return $batch;
    }
317368
public function deleteUser($userId)
    {
        // Forget remembered users.
        $this->userEntities = [];

        $query = $this->deleteUserQuery($userId);

        return $query->execute();
    }
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);
    }
577967
public function GetByUserID($UserID) {
      return $this->SQL->Select()
         ->From('Role')
         ->Join('UserRole', 'Role.RoleID = UserRole.RoleID')
         ->Where('UserRole.UserID', $UserID)
         ->Get();
   }
481728
public function newInstance(
        string $createdByUserId,
        string $createdReason = Tracking::UNKNOWN_REASON
    ) {
        /** @var ContainerInterface|ContainerAbstract $new */
        $new = parent::newInstance(
            $createdByUserId,
            $createdReason
        );

        $new->lastPublished = new \DateTime();

        $new->revisions = new ArrayCollection();

        if (!empty($new->publishedRevision)) {
            $revision = $new->publishedRevision->newInstance(
                $createdByUserId,
                $createdReason
            );
            $new->removePublishedRevision();
            $new->revisions->add($revision);
            $new->setStagedRevision($revision);
        } elseif (!empty($new->stagedRevision)) {
            $revision = $new->stagedRevision->newInstance(
                $createdByUserId,
                $createdReason
            );
            $new->setStagedRevision($revision);
            $new->revisions->add($revision);
        }

        return $new;
    }
887041
public function startSession($user_id)
    {
        $this->deleteOldSessions();

        $user_id = (int)$user_id;
        $sid = $this->generateUserSid($user_id);

        $session = UsersSessionEntityRepository::findOneEntityByCriteria([
            'sid'     => $sid,
            'user_id' => $user_id,
        ]);
        if (!$session) {
            $session = new UsersSessionEntity();
        }
        $session->setSid($sid);
        $session->setUserId($user_id);
        $session->save();

        return $sid;
    }