]> git.mxchange.org Git - friendica.git/blob - src/Core/Session.php
Merge pull request #7514 from MrPetovan/bug/7507-allow-protocolless
[friendica.git] / src / Core / Session.php
1 <?php
2
3 /**
4  * @file src/Core/Session.php
5  */
6 namespace Friendica\Core;
7
8 use Friendica\App;
9 use Friendica\Core\Session\CacheSessionHandler;
10 use Friendica\Core\Session\DatabaseSessionHandler;
11 use Friendica\Database\DBA;
12 use Friendica\Model\User;
13 use Friendica\Util\DateTimeFormat;
14
15 /**
16  * High-level Session service class
17  *
18  * @author Hypolite Petovan <hypolite@mrpetovan.com>
19  */
20 class Session
21 {
22         public static $exists = false;
23         public static $expire = 180000;
24
25         public static function init()
26         {
27                 ini_set('session.gc_probability', 50);
28                 ini_set('session.use_only_cookies', 1);
29                 ini_set('session.cookie_httponly', 1);
30
31                 if (Config::get('system', 'ssl_policy') == App\BaseURL::SSL_POLICY_FULL) {
32                         ini_set('session.cookie_secure', 1);
33                 }
34
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();
39                         } else {
40                                 $SessionHandler = new DatabaseSessionHandler();
41                         }
42
43                         session_set_save_handler($SessionHandler);
44                 }
45         }
46
47         public static function exists($name)
48         {
49                 return isset($_SESSION[$name]);
50         }
51
52         /**
53          * Retrieves a key from the session super global or the defaults if the key is missing or the value is falsy.
54          * 
55          * Handle the case where session_start() hasn't been called and the super global isn't available.
56          *
57          * @param string $name
58          * @param mixed $defaults
59          * @return mixed
60          */
61         public static function get($name, $defaults = null)
62         {
63                 return $_SESSION[$name] ?? $defaults;
64         }
65
66         /**
67          * Sets a single session variable.
68          * Overrides value of existing key.
69          *
70          * @param string $name
71          * @param mixed $value
72          */
73         public static function set($name, $value)
74         {
75                 $_SESSION[$name] = $value;
76         }
77
78         /**
79          * Sets multiple session variables.
80          * Overrides values for existing keys.
81          *
82          * @param array $values
83          */
84         public static function setMultiple(array $values)
85         {
86                 $_SESSION = $values + $_SESSION;
87         }
88
89         /**
90          * Removes a session variable.
91          * Ignores missing keys.
92          *
93          * @param $name
94          */
95         public static function remove($name)
96         {
97                 unset($_SESSION[$name]);
98         }
99
100         /**
101          * @brief Sets the provided user's authenticated session
102          *
103          * @param App   $a
104          * @param array $user_record
105          * @param bool  $login_initial
106          * @param bool  $interactive
107          * @param bool  $login_refresh
108          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
109          */
110         public static function setAuthenticatedForUser(App $a, array $user_record, $login_initial = false, $interactive = false, $login_refresh = false)
111         {
112                 self::setMultiple([
113                         'uid'           => $user_record['uid'],
114                         'theme'         => $user_record['theme'],
115                         'mobile-theme'  => PConfig::get($user_record['uid'], 'system', 'mobile_theme'),
116                         'authenticated' => 1,
117                         'page_flags'    => $user_record['page-flags'],
118                         'my_url'        => $a->getBaseURL() . '/profile/' . $user_record['nickname'],
119                         'my_address'    => $user_record['nickname'] . '@' . substr($a->getBaseURL(), strpos($a->getBaseURL(), '://') + 3),
120                         'addr'          => defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0'),
121                 ]);
122
123                 $member_since = strtotime($user_record['register_date']);
124                 self::set('new_member', time() < ($member_since + ( 60 * 60 * 24 * 14)));
125
126                 if (strlen($user_record['timezone'])) {
127                         date_default_timezone_set($user_record['timezone']);
128                         $a->timezone = $user_record['timezone'];
129                 }
130
131                 $masterUid = $user_record['uid'];
132
133                 if (self::get('submanage')) {
134                         $user = DBA::selectFirst('user', ['uid'], ['uid' => self::get('submanage')]);
135                         if (DBA::isResult($user)) {
136                                 $masterUid = $user['uid'];
137                         }
138                 }
139
140                 $a->identities = User::identities($masterUid);
141
142                 if ($login_initial) {
143                         $a->getLogger()->info('auth_identities: ' . print_r($a->identities, true));
144                 }
145
146                 if ($login_refresh) {
147                         $a->getLogger()->info('auth_identities refresh: ' . print_r($a->identities, true));
148                 }
149
150                 $contact = DBA::selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
151                 if (DBA::isResult($contact)) {
152                         $a->contact = $contact;
153                         $a->cid = $contact['id'];
154                         self::set('cid', $a->cid);
155                 }
156
157                 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
158
159                 if ($login_initial || $login_refresh) {
160                         DBA::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
161
162                         // Set the login date for all identities of the user
163                         DBA::update('user', ['login_date' => DateTimeFormat::utcNow()],
164                                 ['parent-uid' => $masterUid, 'account_removed' => false]);
165                 }
166
167                 if ($login_initial) {
168                         /*
169                          * If the user specified to remember the authentication, then set a cookie
170                          * that expires after one week (the default is when the browser is closed).
171                          * The cookie will be renewed automatically.
172                          * The week ensures that sessions will expire after some inactivity.
173                          */
174                         ;
175                         if (self::get('remember')) {
176                                 $a->getLogger()->info('Injecting cookie for remembered user ' . $user_record['nickname']);
177                                 Authentication::setCookie(604800, $user_record);
178                                 self::remove('remember');
179                         }
180                 }
181
182                 Authentication::twoFactorCheck($user_record['uid'], $a);
183
184                 if ($interactive) {
185                         if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
186                                 info(L10n::t('Welcome %s', $user_record['username']));
187                                 info(L10n::t('Please upload a profile photo.'));
188                                 $a->internalRedirect('profile_photo/new');
189                         } else {
190                                 info(L10n::t("Welcome back %s", $user_record['username']));
191                         }
192                 }
193
194                 $a->user = $user_record;
195
196                 if ($login_initial) {
197                         Hook::callAll('logged_in', $a->user);
198
199                         if ($a->module !== 'home' && self::exists('return_path')) {
200                                 $a->internalRedirect(self::get('return_path'));
201                         }
202                 }
203         }
204 }