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