4 * @file src/Core/Session.php
6 namespace Friendica\Core;
9 use Friendica\Core\Session\CacheSessionHandler;
10 use Friendica\Core\Session\DatabaseSessionHandler;
11 use Friendica\Database\DBA;
12 use Friendica\Model\Contact;
13 use Friendica\Util\Strings;
16 * High-level Session service class
18 * @author Hypolite Petovan <hypolite@mrpetovan.com>
22 public static $exists = false;
23 public static $expire = 180000;
25 public static function init()
27 ini_set('session.gc_probability', 50);
28 ini_set('session.use_only_cookies', 1);
29 ini_set('session.cookie_httponly', 1);
31 if (Config::get('system', 'ssl_policy') == App\BaseURL::SSL_POLICY_FULL) {
32 ini_set('session.cookie_secure', 1);
35 $session_handler = Config::get('system', 'session_handler', 'database');
36 if ($session_handler != 'native') {
37 if ($session_handler == 'cache' && Config::get('system', 'cache_driver', 'database') != 'database') {
38 $SessionHandler = new CacheSessionHandler();
40 $SessionHandler = new DatabaseSessionHandler();
43 session_set_save_handler($SessionHandler);
47 public static function exists($name)
49 return isset($_SESSION[$name]);
53 * Retrieves a key from the session super global or the defaults if the key is missing or the value is falsy.
55 * Handle the case where session_start() hasn't been called and the super global isn't available.
58 * @param mixed $defaults
61 public static function get($name, $defaults = null)
63 return $_SESSION[$name] ?? $defaults;
67 * Sets a single session variable.
68 * Overrides value of existing key.
73 public static function set($name, $value)
75 $_SESSION[$name] = $value;
79 * Sets multiple session variables.
80 * Overrides values for existing keys.
82 * @param array $values
84 public static function setMultiple(array $values)
86 $_SESSION = $values + $_SESSION;
90 * Removes a session variable.
91 * Ignores missing keys.
95 public static function remove($name)
97 unset($_SESSION[$name]);
101 * Clears the current session array
103 public static function clear()
111 * Returns contact ID for given user ID
113 * @param integer $uid User ID
114 * @return integer Contact ID of visitor for given user ID
116 public static function getRemoteContactID($uid)
118 if (empty($_SESSION['remote'][$uid])) {
122 return $_SESSION['remote'][$uid];
126 * Returns User ID for given contact ID of the visitor
128 * @param integer $cid Contact ID
129 * @return integer User ID for given contact ID of the visitor
131 public static function getUserIDForVisitorContactID($cid)
133 if (empty($_SESSION['remote'])) {
137 return array_search($cid, $_SESSION['remote']);
141 * Set the session variable that contains the contact IDs for the visitor's contact URL
143 * @param string $url Contact URL
145 public static function setVisitorsContacts()
147 $_SESSION['remote'] = [];
149 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($_SESSION['my_url']), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
150 while ($contact = DBA::fetch($remote_contacts)) {
151 if (($contact['uid'] == 0) || Contact::isBlockedByUser($contact['id'], $contact['uid'])) {
155 $_SESSION['remote'][$contact['uid']] = $contact['id'];
157 DBA::close($remote_contacts);
161 * Returns if the current visitor is authenticated
163 * @return boolean "true" when visitor is either a local or remote user
165 public static function isAuthenticated()
167 if (empty($_SESSION['authenticated'])) {
171 return $_SESSION['authenticated'];
175 * @brief Calculate the hash that is needed for the "Friendica" cookie
177 * @param array $user Record from "user" table
179 * @return string Hashed data
180 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
182 private static function getCookieHashForUser($user)
186 hash_hmac("sha256", $user["password"], $user["prvkey"]),
187 Config::get("system", "site_prvkey")
192 * @brief Set the "Friendica" cookie
195 * @param array $user Record from "user" table
196 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
198 public static function setCookie($time, $user = [])
201 $time = $time + time();
205 $value = json_encode([
206 "uid" => $user["uid"],
207 "hash" => self::getCookieHashForUser($user),
208 "ip" => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
214 setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == App\BaseURL::SSL_POLICY_FULL), true);
218 * @brief Checks if the "Friendica" cookie is set
220 * @param string $hash
221 * @param array $user Record from "user" table
223 * @return boolean True, if the cookie is set
225 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227 public static function checkCookie(string $hash, array $user)
230 self::getCookieHashForUser($user),
236 * @brief Kills the "Friendica" cookie and all session data
238 public static function delete()
240 self::setCookie(-3600); // make sure cookie is deleted on browser close, as a security measure