4 use Friendica\Core\Config;
5 use Friendica\Core\PConfig;
6 use Friendica\Core\System;
7 use Friendica\Database\DBM;
8 use Friendica\Model\Group;
11 * @brief Calculate the hash that is needed for the "Friendica" cookie
13 * @param array $user Record from "user" table
15 * @return string Hashed data
17 function cookie_hash($user)
19 return(hash("sha256", Config::get("system", "site_prvkey") .
25 * @brief Set the "Friendica" cookie
28 * @param array $user Record from "user" table
30 function new_cookie($time, $user = array())
33 $time = $time + time();
37 $value = json_encode(array("uid" => $user["uid"],
38 "hash" => cookie_hash($user),
39 "ip" => $_SERVER['REMOTE_ADDR']));
44 setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL), true);
48 * @brief Sets the provided user's authenticated session
50 * @todo Should be moved to Friendica\Core\Session once it's created
52 * @param type $user_record
53 * @param type $login_initial
54 * @param type $interactive
55 * @param type $login_refresh
57 function authenticate_success($user_record, $login_initial = false, $interactive = false, $login_refresh = false)
61 $_SESSION['uid'] = $user_record['uid'];
62 $_SESSION['theme'] = $user_record['theme'];
63 $_SESSION['mobile-theme'] = PConfig::get($user_record['uid'], 'system', 'mobile_theme');
64 $_SESSION['authenticated'] = 1;
65 $_SESSION['page_flags'] = $user_record['page-flags'];
66 $_SESSION['my_url'] = System::baseUrl() . '/profile/' . $user_record['nickname'];
67 $_SESSION['my_address'] = $user_record['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
68 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
70 $a->user = $user_record;
73 if ($a->user['login_date'] <= NULL_DATE) {
74 $_SESSION['return_url'] = 'profile_photo/new';
75 $a->module = 'profile_photo';
76 info(t("Welcome ") . $a->user['username'] . EOL);
77 info(t('Please upload a profile photo.') . EOL);
79 info(t("Welcome back ") . $a->user['username'] . EOL);
83 $member_since = strtotime($a->user['register_date']);
84 if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
85 $_SESSION['new_member'] = true;
87 $_SESSION['new_member'] = false;
89 if (strlen($a->user['timezone'])) {
90 date_default_timezone_set($a->user['timezone']);
91 $a->timezone = $a->user['timezone'];
94 $master_record = $a->user;
96 if ((x($_SESSION, 'submanage')) && intval($_SESSION['submanage'])) {
97 $r = dba::fetch_first("SELECT * FROM `user` WHERE `uid` = ? LIMIT 1",
98 intval($_SESSION['submanage'])
100 if (DBM::is_result($r)) {
105 $r = dba::select('user', array('uid', 'username', 'nickname'),
106 array('password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false));
107 if (DBM::is_result($r)) {
108 $a->identities = dba::inArray($r);
110 $a->identities = array();
113 $r = dba::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
115 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
116 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
117 $master_record['uid']
119 if (DBM::is_result($r)) {
120 $a->identities = array_merge($a->identities, dba::inArray($r));
123 if ($login_initial) {
124 logger('auth_identities: ' . print_r($a->identities, true), LOGGER_DEBUG);
126 if ($login_refresh) {
127 logger('auth_identities refresh: ' . print_r($a->identities, true), LOGGER_DEBUG);
130 $r = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `self` LIMIT 1", $_SESSION['uid']);
131 if (DBM::is_result($r)) {
134 $_SESSION['cid'] = $a->cid;
137 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] . '"');
139 if ($login_initial || $login_refresh) {
140 dba::update('user', array('login_date' => datetime_convert()), array('uid' => $_SESSION['uid']));
142 // Set the login date for all identities of the user
143 dba::update('user', array('login_date' => datetime_convert()),
144 array('password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false));
147 if ($login_initial) {
148 // If the user specified to remember the authentication, then set a cookie
149 // that expires after one week (the default is when the browser is closed).
150 // The cookie will be renewed automatically.
151 // The week ensures that sessions will expire after some inactivity.
152 if ($_SESSION['remember']) {
153 logger('Injecting cookie for remembered user ' . $_SESSION['remember_user']['nickname']);
154 new_cookie(604800, $user_record);
155 unset($_SESSION['remember']);
159 if ($login_initial) {
160 call_hooks('logged_in', $a->user);
162 if (($a->module !== 'home') && isset($_SESSION['return_url'])) {
163 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
168 function can_write_wall($owner)
170 static $verified = 0;
172 if (!local_user() && !remote_user()) {
177 if ($uid == $owner) {
182 // use remembered decision and avoid a DB lookup for each and every display item
183 // DO NOT use this function if there are going to be multiple owners
184 // We have a contact-id for an authenticated remote user, this block determines if the contact
185 // belongs to this page owner, and has the necessary permissions to post content
187 if ($verified === 2) {
189 } elseif ($verified === 1) {
194 if (is_array($_SESSION['remote'])) {
195 foreach ($_SESSION['remote'] as $visitor) {
196 if ($visitor['uid'] == $owner) {
197 $cid = $visitor['cid'];
207 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `user`.`uid` = `contact`.`uid`
208 WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
209 AND `user`.`blockwall` = 0 AND `readonly` = 0 AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
212 intval(CONTACT_IS_SHARING),
213 intval(CONTACT_IS_FRIEND),
214 intval(PAGE_COMMUNITY)
217 if (DBM::is_result($r)) {
229 function permissions_sql($owner_id, $remote_verified = false, $groups = null)
231 $local_user = local_user();
232 $remote_user = remote_user();
235 * Construct permissions
237 * default permissions - anonymous user
239 $sql = " AND allow_cid = ''
246 * Profile owner - everything is visible
248 if ($local_user && $local_user == $owner_id) {
250 } elseif ($remote_user) {
252 * Authenticated visitor. Unless pre-verified,
253 * check that the contact belongs to this $owner_id
254 * and load the groups the visitor belongs to.
255 * If pre-verified, the caller is expected to have already
256 * done this and passed the groups into this function.
259 if (!$remote_verified) {
260 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
261 intval($remote_user),
264 if (DBM::is_result($r)) {
265 $remote_verified = true;
266 $groups = Group::getIdsByContactId($remote_user);
270 if ($remote_verified) {
271 $gs = '<<>>'; // should be impossible to match
273 if (is_array($groups) && count($groups)) {
274 foreach ($groups as $g)
275 $gs .= '|<' . intval($g) . '>';
279 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
280 AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
283 intval($remote_user),
285 intval($remote_user),
293 function item_permissions_sql($owner_id, $remote_verified = false, $groups = null)
295 $local_user = local_user();
296 $remote_user = remote_user();
299 * Construct permissions
301 * default permissions - anonymous user
303 $sql = " AND `item`.allow_cid = ''
304 AND `item`.allow_gid = ''
305 AND `item`.deny_cid = ''
306 AND `item`.deny_gid = ''
307 AND `item`.private = 0
310 // Profile owner - everything is visible
311 if ($local_user && ($local_user == $owner_id)) {
313 } elseif ($remote_user) {
315 * Authenticated visitor. Unless pre-verified,
316 * check that the contact belongs to this $owner_id
317 * and load the groups the visitor belongs to.
318 * If pre-verified, the caller is expected to have already
319 * done this and passed the groups into this function.
321 if (!$remote_verified) {
322 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
323 intval($remote_user),
326 if (DBM::is_result($r)) {
327 $remote_verified = true;
328 $groups = Group::getIdsByContactId($remote_user);
331 if ($remote_verified) {
333 $gs = '<<>>'; // should be impossible to match
335 if (is_array($groups) && count($groups)) {
336 foreach ($groups as $g) {
337 $gs .= '|<' . intval($g) . '>';
342 " AND ( `item`.private = 0 OR ( `item`.private in (1,2) AND `item`.`wall` = 1
343 AND ( NOT (`item`.deny_cid REGEXP '<%d>' OR `item`.deny_gid REGEXP '%s')
344 AND ( `item`.allow_cid REGEXP '<%d>' OR `item`.allow_gid REGEXP '%s' OR ( `item`.allow_cid = '' AND `item`.allow_gid = '')))))
346 intval($remote_user),
348 intval($remote_user),
358 * Functions used to protect against Cross-Site Request Forgery
359 * 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.
360 * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
361 * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
362 * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
363 * A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
364 * If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
365 * Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
366 * 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).
368 function get_form_security_token($typename = '')
373 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
375 return $timestamp . '.' . $sec_hash;
378 function check_form_security_token($typename = '', $formname = 'form_security_token')
380 if (!x($_REQUEST, $formname)) {
384 /// @TODO Careful, not secured!
385 $hash = $_REQUEST[$formname];
387 $max_livetime = 10800; // 3 hours
391 $x = explode('.', $hash);
392 if (time() > (IntVal($x[0]) + $max_livetime)) {
396 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
398 return ($sec_hash == $x[1]);
401 function check_form_security_std_err_msg()
403 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;
406 function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token')
408 if (!check_form_security_token($typename, $formname)) {
410 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
411 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
412 notice(check_form_security_std_err_msg());
413 goaway(System::baseUrl() . $err_redirect);
417 function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token')
419 if (!check_form_security_token($typename, $formname)) {
421 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
422 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
423 header('HTTP/1.1 403 Forbidden');
429 * @brief Kills the "Friendica" cookie and all session data
431 function nuke_session()
433 new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure