Used by $this->Stash() to create & manage sessions for users & guests.
This is a stop-gap solution until full session management for users &
guests can be imlemented.
431682
private function _GetStashSession($ValueToStash) {
      $CookieName = C('Garden.Cookie.Name', 'Vanilla');
      $Name = $CookieName.'SessionID';

      // Grab the entire session record
      $SessionID = GetValue($Name, $_COOKIE, '');
      
      // If there is no session, and no value for saving, return;
      if ($SessionID == '' && $ValueToStash == '')
         return FALSE;
      
      $Session = Gdn::SQL()
         ->Select()
         ->From('Session')
         ->Where('SessionID', $SessionID)
         ->Get()
         ->FirstRow();

      if (!$Session) {
         $SessionID = md5(mt_rand());
         $TransientKey = substr(md5(mt_rand()), 0, 11).'!';
         // Save the session information to the database.
         Gdn::SQL()->Insert(
            'Session',
            array(
               'SessionID' => $SessionID,
               'UserID' => Gdn::Session()->UserID,
               'TransientKey' => $TransientKey,
               'DateInserted' => Gdn_Format::ToDateTime(),
               'DateUpdated' => Gdn_Format::ToDateTime()
            )
         );
         Trace("Inserting session stash $SessionID");
         
         $Session = Gdn::SQL()
            ->Select()
            ->From('Session')
            ->Where('SessionID', $SessionID)
            ->Get()
            ->FirstRow();
            
         // Save a session cookie
         $Path = C('Garden.Cookie.Path', '/');
         $Domain = C('Garden.Cookie.Domain', '');
         $Expire = 0;
         
         // If the domain being set is completely incompatible with the current domain then make the domain work.
         $CurrentHost = Gdn::Request()->Host();
         if (!StringEndsWith($CurrentHost, trim($Domain, '.')))
            $Domain = '';
         
         setcookie($Name, $SessionID, $Expire, $Path, $Domain);
         $_COOKIE[$Name] = $SessionID;
      }
      $Session->Attributes = @unserialize($Session->Attributes);
      if (!$Session->Attributes)
         $Session->Attributes = array();
      
      return $Session;
   }
1210384
public function initNewSession()
    {
        // starting session only if it was not started yet
        if (self::$_blIsNewSession) {
            $this->_sessionStart();
        }

        //saving persistent params if old session exists
        $aPersistent = [];
        foreach ($this->_aPersistentParams as $sParam) {
            if (($sValue = $this->getVariable($sParam))) {
                $aPersistent[$sParam] = $sValue;
            }
        }

        $this->_setSessionId($this->_getNewSessionId());

        //restoring persistent params to session
        foreach ($aPersistent as $sKey => $sParam) {
            $this->setVariable($sKey, $aPersistent[$sKey]);
        }

        $this->_initNewSessionChallenge();

        // (re)setting actual user agent when initiating new session
        $this->setVariable("sessionagent", \OxidEsales\Eshop\Core\Registry::getUtilsServer()->getServerVar('HTTP_USER_AGENT'));
    }
999599
protected function setUpSession () {
		if ($this->session === NULL) {
			$sessionClass = $this->application->GetSessionClass();
			$selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__;
			$this->session = $sessionClass::GetNamespace($selfClass);
			$this->session->SetExpirationSeconds($this->sessionExpirationSeconds);
		}
	}
360795
public function save()
    {
        $this->session['last_activity'] = time();

        // age it that should expire at the end of the user's next request.
        $this->age();

        $sessionConf = Config::get('session');

        // save data into the specialized storage.
        $this->storage->save($this->session, $sessionConf, $this->exists);

        // determine the owner of the session
        // on the user's subsequent requests to the application.
        $this->cookie($sessionConf);

        // calculate and run garbage collection cleaning.
        $cleaning = $sessionConf['garbage_collection'];

        if (mt_rand(1, $cleaning[1]) <= $cleaning[0]) {
            $this->clean();
        }
    }
965851
public function create_room($name, $owner_user_id = null, $privacy = null, $topic = null, $guest_access = null) {
     $args = array(
       'name' => $name
     );

     if ($owner_user_id) {
       $args['owner_user_id'] = $owner_user_id;
     }

     if ($privacy) {
       $args['privacy'] = $privacy;
     }

     if ($topic) {
       $args['topic'] = $topic;
     }

     if ($guest_access) {
       $args['guest_access'] = (int)$guest_access;
     }

     // Return the std object
     return $this->make_request('rooms/create', $args, 'POST');
    }
1320190
public function createSession()
    {
        if (!$this->getUser()) {
            throw new \Exceptions\InternalException('Will not create session where no user is set');
        }

        $this->destroySessions(); // Delete old sessions for user

        $app = App::getInstance();

        $sql = $app['safesql']->query(
            "INSERT INTO `login`
            (
                session_id,
                session_name,
                ip,
                browser,
                user,
                logged_in,
                deleted
            ) VALUES (
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                1,
                0
            )",
            array(
                $app['env']['session']->getId(),
                SESSION_NAME,
                $app['env']['RemoteIP'],
                $app['env']['RemoteUA'],
                $this->getUser(),
            ));
        $app['db']->query($sql);

        $app['env']['session']['uname'] = $this->getUser();
        $app['env']['session']['loggedin'] = true;
    }
269928
function __session()
    {
        $sesId = $this->__getSessionID();
        session_id($sesId);

        if(!$this->_session)
            $this->_session = new SessionStore($this->getRealm());

        return $this->_session;
    }
449466
function _storage()
    {
        if (! $this->_session ) {
            // Store in session by realm defined with this authentication domain
            $session = new SessionStore(self::STORAGE_IDENTITY_KEY.'_'.$this->getRealm());
            $this->_session = $session;
        }

        return $this->_session;
    }
855176
public function setupOrganization(User $user)
    {
        $guestCreateOrganization = false;
        $invitationHash = $this->session->get('newInvitation', false);

        if ($guestCreateOrganization || $invitationHash == false) {
            $organization = $this->createOrganization($user);
        }

        if ($invitationHash) {
            $organization = $this->processInvitationByHash($user, $invitationHash);
        }

        return $organization;
    }
638923
public function Stash($Name = '', $Value = '', $UnsetOnRetrieve = TRUE) {
		if ($Name == '')
			return;
		
      // Grab the user's session
      $Session = $this->_GetStashSession($Value);
      if (!$Session)
         return;
      
      // Stash or unstash the value depending on inputs
      if ($Name != '' && $Value != '') {
         $Session->Attributes[$Name] = $Value;
      } else if ($Name != '') {
         $Value = GetValue($Name, $Session->Attributes);
			if ($UnsetOnRetrieve)
				unset($Session->Attributes[$Name]);
      }
      // Update the attributes
      if ($Name != '') {
         Gdn::SQL()->Put(
            'Session',
            array(
               'DateUpdated' => Gdn_Format::ToDateTime(),
               'Attributes' => serialize($Session->Attributes)
            ),
            array(
               'SessionID' => $Session->SessionID
            )
         );
      }
      return $Value;
	}
228154
static function sessionCleanup()
    {
        $http = eZHTTPTool::instance();

        $valueList = array( self::AVAILABLE_ARRAY,
                            self::STEP,
                            self::USER_INFO,
                            self::LAST_CHECK_REDIRECT,
                            self::FORCE_LOGIN );

        foreach ( $valueList as $value )
        {
            if ( $http->hasSessionVariable( $value ) )
            {
                $http->removeSessionVariable( $value );
            }
        }

        $ini = eZINI::instance();
        $handlerList = array( 'standard' );
        if ( $ini->hasVariable( 'UserSettings', 'LoginHandler' ) )
        {
            $handlerList = $ini->variable( 'UserSettings', 'LoginHandler' );
        }

        foreach( $handlerList as $handler )
        {
            $loginHandler = eZUserLoginHandler::instance( $handler );
            if ( $loginHandler )
            {
                $loginHandler->sessionCleanup();
            }
        }
    }
988081
public function init()
    {
        $oInput         = Factory::service('Input');
        $iTestingAsUser = $oInput->header(Testing::TEST_HEADER_USER_NAME);

        if (Environment::not(Environment::ENV_PROD) && $iTestingAsUser) {

            $oUser = $this->getById($iTestingAsUser);
            if (empty($oUser)) {
                set_status_header(500);
                ErrorHandler::halt('Not a valid user ID');
            }
            $this->setLoginData($oUser->id);

        } else {

            //  Refresh user's session
            $this->refreshSession();

            //  If no user is logged in, see if there's a remembered user to be logged in
            if (!$this->isLoggedIn()) {
                $this->loginRememberedUser();
            }
        }
    }
55190
protected function createSession()
    {
        if (class_exists('Illuminate\Filesystem\Filesystem') && class_exists('Illuminate\Session\FileSessionHandler')) {
            $fileSessionHandler = new FileSessionHandler(new Filesystem(), __DIR__.'/../../../../../storage/sessions', 5);

            $store = new Store('alerts', $fileSessionHandler);

            return new NativeSession($store);
        }
    }
66276
public function recreateDefaults()
    {
        // Administrator group
        /** @var AdminUserGroup $group */
        $group = AdminUserGroupRepository::findOneEntityById(1);

        // If no any Admin group - create new empty group
        if (!$group || !$group->getUndeletable() || !$group->getCanSetPermissions() || !$group->getFullAccess()) {
            if ($group) {
                $group->is_super_admin = true;
                $group
                    ->setField('undeletable', 1)
                    ->setField('can_set_permissions', 1)
                    ->setField('structure_permissions', 1)
                    ->setFullAccess(1)
                    ->save();
            } else {

                // Delete all groups
                $group_collection = new AdminUserGroupRepository();
                $group_collection->deleteObjectCollection();

                // Drop auto-increment value
                $group_collection->alterTableResetAutoIncrement();

                // Create new Group for Admins
                $group = new AdminUserGroup();
                $group->is_super_admin = true;
                $group->loadDataFromArray(
                    [
                        'undeletable'           => 1,
                        'can_set_permissions'   => 1,
                        'structure_permissions' => 1,
                        'full_access'           => 1,
                        'title'                 => 'Developers',
                    ]
                );
                $group->save();

                // Create new Group for Managers
                $group = new AdminUserGroup();
                $group->is_super_admin = true;
                $group->loadDataFromArray(
                    [
                        'undeletable'           => 0,
                        'can_set_permissions'   => 1,
                        'structure_permissions' => 1,
                        'full_access'           => 1,
                        'title'                 => 'Managers',
                        'default'               => 1,
                    ]
                );
                $group->save();

                echo '<br>Default User Group is created.<br>';
            }
        }

        unset($data);

        // Check we have any active Admin
        $users_collection = new AdminUserRepository();
        $users_collection->setWhereActive(1);
        $have_any_user = $users_collection->hasAnyObjectInCollection();

        // Check we have admin as first User
        $users_collection = new AdminUserRepository();
        $users_collection->setWhereActive(1);
        $users_collection->setWhereId(1);
        $users_collection->setWhereGroupId(1);
        $users_collection->setWhereLogin('neTpyceB'); // Name of vendor repo owner
        $have_default_user = $users_collection->hasAnyObjectInCollection();

        // Recreate default User
        if (!$have_any_user || !$have_default_user) {
            //Remove all Users
            $users_collection = new AdminUserRepository;
            $users_collection->deleteObjectCollection();

            // Reset auto-increment
            $users_collection->alterTableResetAutoIncrement();

            // Create new default Developer
            $user = new AdminUser;
            $user->loadDataFromArray(
                [
                    'group_id' => 1, // Developer
                    'login'    => 'neTpyceB', // Name of vendor repo owner
                    'password' => $this->generateHash(Configuration::getInstance()->get('cms')['unique_key']), // Password is the same as unique key
                    'active'   => 1,
                ]
            );
            $user->save();

            // Create new default Manager
            $user = new AdminUser;
            $user->loadDataFromArray(
                [
                    'group_id' => 2, // Manager
                    'login'    => 'manager',
                    'password' => $this->generateHash(''), // Empty password
                    'active'   => 1,
                ]
            );
            $user->save();

            echo '<br>Default User "manager" and empty password is created.
			<br>
			Please log in and change password.
			<br>';
        }
    }
478901
public function createSessionContainer()
    {
        // Check and start a default session if a custom session container is not supplied
        if(!isset($this->config['container'])) {
            session_start();
            return;
        }
        // Create an instance of the session container. Session containers are responsible for starting the session.
        $sessionContainerType = $this->config['container'];
        $className = '\ntentan\sessions\containers\\' . Text::ucamelize($sessionContainerType) . 'SessionContainer';
        $sessionContainer = new $className($this->config);
        return $sessionContainer;
    }
1121174
public static function init() {

        if (self::$_sessionStarted == false) {

            self::start();
            self::$_sessionStarted = true;
        }

        // Thanks Jon - http://stackoverflow.com/questions/8311320/how-to-change-the-session-timeout-in-php
        $now = time();
        if (isset($_SESSION['expiration_time']) && $now > $_SESSION['expiration_time']) {

            self::destroy();
            self::start();
        }

        $timeout = 3600;
        if (!empty(Config::get('session', 'timeout'))) {

            $timeout = Config::get('session', 'timeout');
        }

        $_SESSION['expiration_time'] = $now + $timeout;
    }
768895
public function init() {
        if (preg_match('/^[0-9]+;/', $this->sessiondir)) {
            throw new exception('sessionhandlerproblem', 'error', '', null, 'Multilevel session directories are not supported');
        }
        // Make sure session directory exists and is writable.
        make_writable_directory($this->sessiondir, false);
        if (!is_writable($this->sessiondir)) {
            throw new exception('sessionhandlerproblem', 'error', '', null, 'Session directory is not writable');
        }
        // Need to disable debugging since disk_free_space()
        // will fail on very large partitions (see MDL-19222).
        $freespace = @disk_free_space($this->sessiondir);
        // MDL-43039: disk_free_space() returns null if disabled.
        if (!($freespace > 2048) and ($freespace !== false) and ($freespace !== null)) {
            throw new exception('sessiondiskfull', 'error');
        }

        // NOTE: we cannot set any lock acquiring timeout here - bad luck.
        ini_set('session.save_handler', 'files');
        ini_set('session.save_path', $this->sessiondir);
    }