4 use Friendica\Core\Addon;
5 use Friendica\Core\Config;
6 use Friendica\Core\PConfig;
7 use Friendica\Core\System;
8 use Friendica\Database\DBM;
9 use Friendica\Model\Group;
12 * @brief Calculate the hash that is needed for the "Friendica" cookie
14 * @param array $user Record from "user" table
16 * @return string Hashed data
18 function cookie_hash($user)
20 return(hash("sha256", Config::get("system", "site_prvkey") .
26 * @brief Set the "Friendica" cookie
29 * @param array $user Record from "user" table
31 function new_cookie($time, $user = [])
34 $time = $time + time();
38 $value = json_encode(["uid" => $user["uid"],
39 "hash" => cookie_hash($user),
40 "ip" => $_SERVER['REMOTE_ADDR']]);
45 setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL), true);
49 * @brief Sets the provided user's authenticated session
51 * @todo Should be moved to Friendica\Core\Session once it's created
53 * @param type $user_record
54 * @param type $login_initial
55 * @param type $interactive
56 * @param type $login_refresh
58 function authenticate_success($user_record, $login_initial = false, $interactive = false, $login_refresh = false)
62 $_SESSION['uid'] = $user_record['uid'];
63 $_SESSION['theme'] = $user_record['theme'];
64 $_SESSION['mobile-theme'] = PConfig::get($user_record['uid'], 'system', 'mobile_theme');
65 $_SESSION['authenticated'] = 1;
66 $_SESSION['page_flags'] = $user_record['page-flags'];
67 $_SESSION['my_url'] = System::baseUrl() . '/profile/' . $user_record['nickname'];
68 $_SESSION['my_address'] = $user_record['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
69 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
71 $a->user = $user_record;
74 if ($a->user['login_date'] <= NULL_DATE) {
75 $_SESSION['return_url'] = 'profile_photo/new';
76 $a->module = 'profile_photo';
77 info(t("Welcome ") . $a->user['username'] . EOL);
78 info(t('Please upload a profile photo.') . EOL);
80 info(t("Welcome back ") . $a->user['username'] . EOL);
84 $member_since = strtotime($a->user['register_date']);
85 if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
86 $_SESSION['new_member'] = true;
88 $_SESSION['new_member'] = false;
90 if (strlen($a->user['timezone'])) {
91 date_default_timezone_set($a->user['timezone']);
92 $a->timezone = $a->user['timezone'];
95 $master_record = $a->user;
97 if ((x($_SESSION, 'submanage')) && intval($_SESSION['submanage'])) {
98 $r = dba::fetch_first("SELECT * FROM `user` WHERE `uid` = ? LIMIT 1",
99 intval($_SESSION['submanage'])
101 if (DBM::is_result($r)) {
106 $r = dba::select('user', ['uid', 'username', 'nickname'],
107 ['password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false]);
108 if (DBM::is_result($r)) {
109 $a->identities = dba::inArray($r);
114 $r = dba::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
116 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
117 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
118 $master_record['uid']
120 if (DBM::is_result($r)) {
121 $a->identities = array_merge($a->identities, dba::inArray($r));
124 if ($login_initial) {
125 logger('auth_identities: ' . print_r($a->identities, true), LOGGER_DEBUG);
127 if ($login_refresh) {
128 logger('auth_identities refresh: ' . print_r($a->identities, true), LOGGER_DEBUG);
131 $r = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `self` LIMIT 1", $_SESSION['uid']);
132 if (DBM::is_result($r)) {
135 $_SESSION['cid'] = $a->cid;
138 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] . '"');
140 if ($login_initial || $login_refresh) {
141 dba::update('user', ['login_date' => datetime_convert()], ['uid' => $_SESSION['uid']]);
143 // Set the login date for all identities of the user
144 dba::update('user', ['login_date' => datetime_convert()],
145 ['password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false]);
148 if ($login_initial) {
149 // If the user specified to remember the authentication, then set a cookie
150 // that expires after one week (the default is when the browser is closed).
151 // The cookie will be renewed automatically.
152 // The week ensures that sessions will expire after some inactivity.
153 if ($_SESSION['remember']) {
154 logger('Injecting cookie for remembered user ' . $_SESSION['remember_user']['nickname']);
155 new_cookie(604800, $user_record);
156 unset($_SESSION['remember']);
160 if ($login_initial) {
161 Addon::callHooks('logged_in', $a->user);
163 if (($a->module !== 'home') && isset($_SESSION['return_url'])) {
164 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
169 function can_write_wall($owner)
171 static $verified = 0;
173 if (!local_user() && !remote_user()) {
178 if ($uid == $owner) {
183 // use remembered decision and avoid a DB lookup for each and every display item
184 // DO NOT use this function if there are going to be multiple owners
185 // We have a contact-id for an authenticated remote user, this block determines if the contact
186 // belongs to this page owner, and has the necessary permissions to post content
188 if ($verified === 2) {
190 } elseif ($verified === 1) {
195 if (is_array($_SESSION['remote'])) {
196 foreach ($_SESSION['remote'] as $visitor) {
197 if ($visitor['uid'] == $owner) {
198 $cid = $visitor['cid'];
208 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `user`.`uid` = `contact`.`uid`
209 WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
210 AND `user`.`blockwall` = 0 AND `readonly` = 0 AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
213 intval(CONTACT_IS_SHARING),
214 intval(CONTACT_IS_FRIEND),
215 intval(PAGE_COMMUNITY)
218 if (DBM::is_result($r)) {
230 function permissions_sql($owner_id, $remote_verified = false, $groups = null)
232 $local_user = local_user();
233 $remote_user = remote_user();
236 * Construct permissions
238 * default permissions - anonymous user
240 $sql = " AND allow_cid = ''
247 * Profile owner - everything is visible
249 if ($local_user && $local_user == $owner_id) {
251 } elseif ($remote_user) {
253 * Authenticated visitor. Unless pre-verified,
254 * check that the contact belongs to this $owner_id
255 * and load the groups the visitor belongs to.
256 * If pre-verified, the caller is expected to have already
257 * done this and passed the groups into this function.
260 if (!$remote_verified) {
261 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
262 intval($remote_user),
265 if (DBM::is_result($r)) {
266 $remote_verified = true;
267 $groups = Group::getIdsByContactId($remote_user);
271 if ($remote_verified) {
272 $gs = '<<>>'; // should be impossible to match
274 if (is_array($groups) && count($groups)) {
275 foreach ($groups as $g)
276 $gs .= '|<' . intval($g) . '>';
280 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
281 AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
284 intval($remote_user),
286 intval($remote_user),
294 function item_permissions_sql($owner_id, $remote_verified = false, $groups = null)
296 $local_user = local_user();
297 $remote_user = remote_user();
300 * Construct permissions
302 * default permissions - anonymous user
304 $sql = " AND `item`.allow_cid = ''
305 AND `item`.allow_gid = ''
306 AND `item`.deny_cid = ''
307 AND `item`.deny_gid = ''
308 AND `item`.private = 0
311 // Profile owner - everything is visible
312 if ($local_user && ($local_user == $owner_id)) {
314 } elseif ($remote_user) {
316 * Authenticated visitor. Unless pre-verified,
317 * check that the contact belongs to this $owner_id
318 * and load the groups the visitor belongs to.
319 * If pre-verified, the caller is expected to have already
320 * done this and passed the groups into this function.
322 if (!$remote_verified) {
323 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
324 intval($remote_user),
327 if (DBM::is_result($r)) {
328 $remote_verified = true;
329 $groups = Group::getIdsByContactId($remote_user);
332 if ($remote_verified) {
334 $gs = '<<>>'; // should be impossible to match
336 if (is_array($groups) && count($groups)) {
337 foreach ($groups as $g) {
338 $gs .= '|<' . intval($g) . '>';
343 " AND ( `item`.private = 0 OR ( `item`.private in (1,2) AND `item`.`wall` = 1
344 AND ( NOT (`item`.deny_cid REGEXP '<%d>' OR `item`.deny_gid REGEXP '%s')
345 AND ( `item`.allow_cid REGEXP '<%d>' OR `item`.allow_gid REGEXP '%s' OR ( `item`.allow_cid = '' AND `item`.allow_gid = '')))))
347 intval($remote_user),
349 intval($remote_user),
359 * Functions used to protect against Cross-Site Request Forgery
360 * The security token has to base on at least one value that an attacker can't know - here it's the session ID and the private key.
361 * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
362 * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
363 * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
364 * A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
365 * If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
366 * Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
367 * so this mechanism brings in some damage control (the attacker would be able to forge a request to a form of this type, but not to forms of other types).
369 function get_form_security_token($typename = '')
374 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
376 return $timestamp . '.' . $sec_hash;
379 function check_form_security_token($typename = '', $formname = 'form_security_token')
381 if (!x($_REQUEST, $formname)) {
385 /// @TODO Careful, not secured!
386 $hash = $_REQUEST[$formname];
388 $max_livetime = 10800; // 3 hours
392 $x = explode('.', $hash);
393 if (time() > (IntVal($x[0]) + $max_livetime)) {
397 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
399 return ($sec_hash == $x[1]);
402 function check_form_security_std_err_msg()
404 return t('The form security token was not correct. This probably happened because the form has been opened for too long (>3 hours) before submitting it.') . EOL;
407 function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token')
409 if (!check_form_security_token($typename, $formname)) {
411 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
412 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
413 notice(check_form_security_std_err_msg());
414 goaway(System::baseUrl() . $err_redirect);
418 function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token')
420 if (!check_form_security_token($typename, $formname)) {
422 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
423 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
424 header('HTTP/1.1 403 Forbidden');
430 * @brief Kills the "Friendica" cookie and all session data
432 function nuke_session()
434 new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure