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