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\Model\User;
14 use Friendica\Util\DateTimeFormat;
15 use Friendica\Util\Strings;
18 * High-level Session service class
20 * @author Hypolite Petovan <hypolite@mrpetovan.com>
24 public static $exists = false;
25 public static $expire = 180000;
27 public static function init()
29 ini_set('session.gc_probability', 50);
30 ini_set('session.use_only_cookies', 1);
31 ini_set('session.cookie_httponly', 1);
33 if (Config::get('system', 'ssl_policy') == App\BaseURL::SSL_POLICY_FULL) {
34 ini_set('session.cookie_secure', 1);
37 $session_handler = Config::get('system', 'session_handler', 'database');
38 if ($session_handler != 'native') {
39 if ($session_handler == 'cache' && Config::get('system', 'cache_driver', 'database') != 'database') {
40 $SessionHandler = new CacheSessionHandler();
42 $SessionHandler = new DatabaseSessionHandler();
45 session_set_save_handler($SessionHandler);
49 public static function exists($name)
51 return isset($_SESSION[$name]);
55 * Retrieves a key from the session super global or the defaults if the key is missing or the value is falsy.
57 * Handle the case where session_start() hasn't been called and the super global isn't available.
60 * @param mixed $defaults
63 public static function get($name, $defaults = null)
65 return $_SESSION[$name] ?? $defaults;
69 * Sets a single session variable.
70 * Overrides value of existing key.
75 public static function set($name, $value)
77 $_SESSION[$name] = $value;
81 * Sets multiple session variables.
82 * Overrides values for existing keys.
84 * @param array $values
86 public static function setMultiple(array $values)
88 $_SESSION = $values + $_SESSION;
92 * Removes a session variable.
93 * Ignores missing keys.
97 public static function remove($name)
99 unset($_SESSION[$name]);
103 * Clears the current session array
105 public static function clear()
111 * @brief Sets the provided user's authenticated session
114 * @param array $user_record
115 * @param bool $login_initial
116 * @param bool $interactive
117 * @param bool $login_refresh
118 * @throws \Friendica\Network\HTTPException\ForbiddenException
119 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
121 public static function setAuthenticatedForUser(App $a, array $user_record, $login_initial = false, $interactive = false, $login_refresh = false)
124 'uid' => $user_record['uid'],
125 'theme' => $user_record['theme'],
126 'mobile-theme' => PConfig::get($user_record['uid'], 'system', 'mobile_theme'),
127 'authenticated' => 1,
128 'page_flags' => $user_record['page-flags'],
129 'my_url' => $a->getBaseURL() . '/profile/' . $user_record['nickname'],
130 'my_address' => $user_record['nickname'] . '@' . substr($a->getBaseURL(), strpos($a->getBaseURL(), '://') + 3),
131 'addr' => defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0')
134 self::setVisitorsContacts();
136 $member_since = strtotime($user_record['register_date']);
137 self::set('new_member', time() < ($member_since + ( 60 * 60 * 24 * 14)));
139 if (strlen($user_record['timezone'])) {
140 date_default_timezone_set($user_record['timezone']);
141 $a->timezone = $user_record['timezone'];
144 $masterUid = $user_record['uid'];
146 if (self::get('submanage')) {
147 $user = DBA::selectFirst('user', ['uid'], ['uid' => self::get('submanage')]);
148 if (DBA::isResult($user)) {
149 $masterUid = $user['uid'];
153 $a->identities = User::identities($masterUid);
155 if ($login_initial) {
156 $a->getLogger()->info('auth_identities: ' . print_r($a->identities, true));
159 if ($login_refresh) {
160 $a->getLogger()->info('auth_identities refresh: ' . print_r($a->identities, true));
163 $contact = DBA::selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
164 if (DBA::isResult($contact)) {
165 $a->contact = $contact;
166 $a->cid = $contact['id'];
167 self::set('cid', $a->cid);
170 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
172 if ($login_initial || $login_refresh) {
173 DBA::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
175 // Set the login date for all identities of the user
176 DBA::update('user', ['login_date' => DateTimeFormat::utcNow()],
177 ['parent-uid' => $masterUid, 'account_removed' => false]);
180 if ($login_initial) {
182 * If the user specified to remember the authentication, then set a cookie
183 * that expires after one week (the default is when the browser is closed).
184 * The cookie will be renewed automatically.
185 * The week ensures that sessions will expire after some inactivity.
188 if (self::get('remember')) {
189 $a->getLogger()->info('Injecting cookie for remembered user ' . $user_record['nickname']);
190 Authentication::setCookie(604800, $user_record);
191 self::remove('remember');
195 Authentication::twoFactorCheck($user_record['uid'], $a);
198 if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
199 info(L10n::t('Welcome %s', $user_record['username']));
200 info(L10n::t('Please upload a profile photo.'));
201 $a->internalRedirect('profile_photo/new');
203 info(L10n::t("Welcome back %s", $user_record['username']));
207 $a->user = $user_record;
209 if ($login_initial) {
210 Hook::callAll('logged_in', $a->user);
212 if ($a->module !== 'home' && self::exists('return_path')) {
213 $a->internalRedirect(self::get('return_path'));
219 * Returns contact ID for given user ID
221 * @param integer $uid User ID
222 * @return integer Contact ID of visitor for given user ID
224 public static function getRemoteContactID($uid)
226 if (empty($_SESSION['remote'][$uid])) {
230 return $_SESSION['remote'][$uid];
234 * Returns User ID for given contact ID of the visitor
236 * @param integer $cid Contact ID
237 * @return integer User ID for given contact ID of the visitor
239 public static function getUserIDForVisitorContactID($cid)
241 if (empty($_SESSION['remote'])) {
245 return array_search($cid, $_SESSION['remote']);
249 * Set the session variable that contains the contact IDs for the visitor's contact URL
251 * @param string $url Contact URL
253 public static function setVisitorsContacts()
255 $_SESSION['remote'] = [];
257 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($_SESSION['my_url']), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
258 while ($contact = DBA::fetch($remote_contacts)) {
259 if (($contact['uid'] == 0) || Contact::isBlockedByUser($contact['id'], $contact['uid'])) {
263 $_SESSION['remote'][$contact['uid']] = $contact['id'];
265 DBA::close($remote_contacts);
269 * Returns if the current visitor is authenticated
271 * @return boolean "true" when visitor is either a local or remote user
273 public static function isAuthenticated()
275 if (empty($_SESSION['authenticated'])) {
279 return $_SESSION['authenticated'];