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