/**
* 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 implemented.
*
* @param Gdn_SQLDriver $sql Local clone of the sql driver.
* @param string $valueToStash The value of the stash to set.
*
* @return bool|Gdn_DataSet Current session.
*/
private function getStashSession($sql, $valueToStash)
{
$cookieName = c('Garden.Cookie.Name', 'Vanilla');
$name = $cookieName . '-sid';
// Grab the entire session record.
$sessionID = val($name, $_COOKIE, '');
// If there is no session, and no value for saving, return.
if ($sessionID == '' && $valueToStash == '') {
return false;
}
$session = $sql->select()->from('Session')->where('SessionID', $sessionID)->get()->firstRow();
if (!$session) {
$sessionID = betterRandomString(32);
$transientKey = substr(md5(mt_rand()), 0, 11) . '!';
// Save the session information to the database.
$sql->insert('Session', ['SessionID' => $sessionID, 'UserID' => Gdn::session()->UserID, 'TransientKey' => $transientKey, 'DateInserted' => Gdn_Format::toDateTime(), 'DateUpdated' => Gdn_Format::toDateTime()]);
trace("Inserting session stash {$sessionID}");
$session = $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 = '';
}
safeCookie($name, $sessionID, $expire, $path, $domain);
$_COOKIE[$name] = $sessionID;
}
$session->Attributes = dbdecode($session->Attributes);
if (!$session->Attributes) {
$session->Attributes = [];
}
return $session;
}