]> git.mxchange.org Git - friendica.git/blob - src/Core/Authentication.php
Log function
[friendica.git] / src / Core / Authentication.php
1 <?php
2 /**
3  * @file /src/Core/Authentication.php
4  */
5
6 namespace Friendica\Core;
7
8 use Friendica\BaseObject;
9 use Friendica\Core\Addon;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\PConfig;
14 use Friendica\Database\DBA;
15 use Friendica\Util\DateTimeFormat;
16
17 /**
18 * Handle Authentification, Session and Cookies
19 */
20 class Authentication extends BaseObject
21 {
22         /**
23          * @brief Calculate the hash that is needed for the "Friendica" cookie
24          *
25          * @param array $user Record from "user" table
26          *
27          * @return string Hashed data
28          */
29         public static function getCookieHashForUser($user)
30         {
31                 return(hash("sha256", Config::get("system", "site_prvkey") .
32                                 $user["prvkey"] .
33                                 $user["password"]));
34         }
35
36         /**
37          * @brief Set the "Friendica" cookie
38          *
39          * @param int $time
40          * @param array $user Record from "user" table
41          */
42         public static  function setCookie($time, $user = [])
43         {
44                 if ($time != 0) {
45                         $time = $time + time();
46                 }
47
48                 if ($user) {
49                         $value = json_encode(["uid" => $user["uid"],
50                                 "hash" => self::getCookieHashForUser($user),
51                                 "ip" => defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0')]);
52                 } else {
53                         $value = "";
54                 }
55
56                 setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL), true);
57         }
58
59         /**
60          * @brief Sets the provided user's authenticated session
61          *
62          * @todo Should be moved to Friendica\Core\Session once it's created
63          *
64          * @param type $user_record
65          * @param type $login_initial
66          * @param type $interactive
67          * @param type $login_refresh
68          */
69         public static function setAuthenticatedSessionForUser($user_record, $login_initial = false, $interactive = false, $login_refresh = false)
70         {
71                 $a = self::getApp();
72
73                 $_SESSION['uid'] = $user_record['uid'];
74                 $_SESSION['theme'] = $user_record['theme'];
75                 $_SESSION['mobile-theme'] = PConfig::get($user_record['uid'], 'system', 'mobile_theme');
76                 $_SESSION['authenticated'] = 1;
77                 $_SESSION['page_flags'] = $user_record['page-flags'];
78                 $_SESSION['my_url'] = $a->getbaseUrl() . '/profile/' . $user_record['nickname'];
79                 $_SESSION['my_address'] = $user_record['nickname'] . '@' . substr($a->getbaseUrl(), strpos($a->getbaseUrl(), '://') + 3);
80                 $_SESSION['addr'] = defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0');
81
82                 $a->user = $user_record;
83
84                 if ($interactive) {
85                         if ($a->user['login_date'] <= DBA::NULL_DATETIME) {
86                                 $_SESSION['return_path'] = 'profile_photo/new';
87                                 $a->module = 'profile_photo';
88                                 info(L10n::t("Welcome ") . $a->user['username'] . EOL);
89                                 info(L10n::t('Please upload a profile photo.') . EOL);
90                         } else {
91                                 info(L10n::t("Welcome back ") . $a->user['username'] . EOL);
92                         }
93                 }
94
95                 $member_since = strtotime($a->user['register_date']);
96                 if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
97                         $_SESSION['new_member'] = true;
98                 } else {
99                         $_SESSION['new_member'] = false;
100                 }
101                 if (strlen($a->user['timezone'])) {
102                         date_default_timezone_set($a->user['timezone']);
103                         $a->timezone = $a->user['timezone'];
104                 }
105
106                 $master_record = $a->user;
107
108                 if ((x($_SESSION, 'submanage')) && intval($_SESSION['submanage'])) {
109                         $user = DBA::selectFirst('user', [], ['uid' => $_SESSION['submanage']]);
110                         if (DBA::isResult($user)) {
111                                 $master_record = $user;
112                         }
113                 }
114
115                 if ($master_record['parent-uid'] == 0) {
116                         // First add our own entry
117                         $a->identities = [['uid' => $master_record['uid'],
118                                         'username' => $master_record['username'],
119                                         'nickname' => $master_record['nickname']]];
120
121                         // Then add all the children
122                         $r = DBA::select('user', ['uid', 'username', 'nickname'],
123                                 ['parent-uid' => $master_record['uid'], 'account_removed' => false]);
124                         if (DBA::isResult($r)) {
125                                 $a->identities = array_merge($a->identities, DBA::toArray($r));
126                         }
127                 } else {
128                         // Just ensure that the array is always defined
129                         $a->identities = [];
130
131                         // First entry is our parent
132                         $r = DBA::select('user', ['uid', 'username', 'nickname'],
133                                 ['uid' => $master_record['parent-uid'], 'account_removed' => false]);
134                         if (DBA::isResult($r)) {
135                                 $a->identities = DBA::toArray($r);
136                         }
137
138                         // Then add all siblings
139                         $r = DBA::select('user', ['uid', 'username', 'nickname'],
140                                 ['parent-uid' => $master_record['parent-uid'], 'account_removed' => false]);
141                         if (DBA::isResult($r)) {
142                                 $a->identities = array_merge($a->identities, DBA::toArray($r));
143                         }
144                 }
145
146                 $r = DBA::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
147                         FROM `manage`
148                         INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
149                         WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
150                         $master_record['uid']
151                 );
152                 if (DBA::isResult($r)) {
153                         $a->identities = array_merge($a->identities, DBA::toArray($r));
154                 }
155
156                 if ($login_initial) {
157                         Logger::log('auth_identities: ' . print_r($a->identities, true), LOGGER_DEBUG);
158                 }
159                 if ($login_refresh) {
160                         Logger::log('auth_identities refresh: ' . print_r($a->identities, true), LOGGER_DEBUG);
161                 }
162
163                 $contact = DBA::selectFirst('contact', [], ['uid' => $_SESSION['uid'], 'self' => true]);
164                 if (DBA::isResult($contact)) {
165                         $a->contact = $contact;
166                         $a->cid = $contact['id'];
167                         $_SESSION['cid'] = $a->cid;
168                 }
169
170                 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] . '"');
171
172                 if ($login_initial || $login_refresh) {
173                         DBA::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $_SESSION['uid']]);
174
175                         // Set the login date for all identities of the user
176                         DBA::update('user', ['login_date' => DateTimeFormat::utcNow()],
177                                 ['parent-uid' => $master_record['uid'], 'account_removed' => false]);
178                 }
179
180                 if ($login_initial) {
181                         /*
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.
186                          */
187                         if (!empty($_SESSION['remember'])) {
188                                 Logger::log('Injecting cookie for remembered user ' . $a->user['nickname']);
189                                 self::setCookie(604800, $user_record);
190                                 unset($_SESSION['remember']);
191                         }
192                 }
193
194                 if ($login_initial) {
195                         Addon::callHooks('logged_in', $a->user);
196
197                         if (($a->module !== 'home') && isset($_SESSION['return_path'])) {
198                                 $a->internalRedirect($_SESSION['return_path']);
199                         }
200                 }
201         }
202
203         /**
204          * @brief Kills the "Friendica" cookie and all session data
205          */
206         public static function deleteSession()
207         {
208                 self::setCookie(-3600); // make sure cookie is deleted on browser close, as a security measure
209                 session_unset();
210                 session_destroy();
211         }
212 }
213