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