4 use Friendica\Core\System;
7 * @brief Calculate the hash that is needed for the "Friendica" cookie
9 * @param array $user Record from "user" table
11 * @return string Hashed data
13 function cookie_hash($user) {
14 return(hash("sha256", get_config("system", "site_prvkey").
20 * @brief Set the "Friendica" cookie
23 * @param array $user Record from "user" table
25 function new_cookie($time, $user = array()) {
28 $time = $time + time();
32 $value = json_encode(array("uid" => $user["uid"],
33 "hash" => cookie_hash($user),
34 "ip" => $_SERVER['REMOTE_ADDR']));
40 setcookie("Friendica", $value, $time, "/", "",
41 (get_config('system', 'ssl_policy') == SSL_POLICY_FULL), true);
45 function authenticate_success($user_record, $login_initial = false, $interactive = false, $login_refresh = false) {
49 $_SESSION['uid'] = $user_record['uid'];
50 $_SESSION['theme'] = $user_record['theme'];
51 $_SESSION['mobile-theme'] = get_pconfig($user_record['uid'], 'system', 'mobile_theme');
52 $_SESSION['authenticated'] = 1;
53 $_SESSION['page_flags'] = $user_record['page-flags'];
54 $_SESSION['my_url'] = System::baseUrl() . '/profile/' . $user_record['nickname'];
55 $_SESSION['my_address'] = $user_record['nickname'] . '@' . substr(System::baseUrl(),strpos(System::baseUrl(),'://')+3);
56 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
58 $a->user = $user_record;
61 if ($a->user['login_date'] <= NULL_DATE) {
62 $_SESSION['return_url'] = 'profile_photo/new';
63 $a->module = 'profile_photo';
64 info( t("Welcome ") . $a->user['username'] . EOL);
65 info( t('Please upload a profile photo.') . EOL);
67 info( t("Welcome back ") . $a->user['username'] . EOL);
71 $member_since = strtotime($a->user['register_date']);
72 if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
73 $_SESSION['new_member'] = true;
75 $_SESSION['new_member'] = false;
77 if (strlen($a->user['timezone'])) {
78 date_default_timezone_set($a->user['timezone']);
79 $a->timezone = $a->user['timezone'];
82 $master_record = $a->user;
84 if ((x($_SESSION,'submanage')) && intval($_SESSION['submanage'])) {
85 $r = dba::fetch_first("SELECT * FROM `user` WHERE `uid` = ? LIMIT 1",
86 intval($_SESSION['submanage'])
88 if (dbm::is_result($r)) {
93 $r = dba::select('user', array('uid', 'username', 'nickname'),
94 array('password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false));
95 if (dbm::is_result($r)) {
96 $a->identities = dba::inArray($r);
98 $a->identities = array();
101 $r = dba::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
103 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
104 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
105 $master_record['uid']
107 if (dbm::is_result($r)) {
108 $a->identities = array_merge($a->identities, dba::inArray($r));
111 if ($login_initial) {
112 logger('auth_identities: ' . print_r($a->identities,true), LOGGER_DEBUG);
114 if ($login_refresh) {
115 logger('auth_identities refresh: ' . print_r($a->identities,true), LOGGER_DEBUG);
118 $r = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `self` LIMIT 1", $_SESSION['uid']);
119 if (dbm::is_result($r)) {
122 $_SESSION['cid'] = $a->cid;
125 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] .'"');
127 if ($login_initial || $login_refresh) {
128 dba::update('user', array('login_date' => datetime_convert()), array('uid' => $_SESSION['uid']));
130 // Set the login date for all identities of the user
131 dba::update('user', array('login_date' => datetime_convert()),
132 array('password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false));
135 if ($login_initial) {
136 // If the user specified to remember the authentication, then set a cookie
137 // that expires after one week (the default is when the browser is closed).
138 // The cookie will be renewed automatically.
139 // The week ensures that sessions will expire after some inactivity.
140 if ($_SESSION['remember']) {
141 logger('Injecting cookie for remembered user '. $_SESSION['remember_user']['nickname']);
142 new_cookie(604800, $user_record);
143 unset($_SESSION['remember']);
147 if ($login_initial) {
148 call_hooks('logged_in', $a->user);
150 if (($a->module !== 'home') && isset($_SESSION['return_url'])) {
151 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
158 function can_write_wall(App $a, $owner) {
160 static $verified = 0;
162 if ((! (local_user())) && (! (remote_user()))) {
168 if (($uid) && ($uid == $owner)) {
174 // use remembered decision and avoid a DB lookup for each and every display item
175 // DO NOT use this function if there are going to be multiple owners
177 // We have a contact-id for an authenticated remote user, this block determines if the contact
178 // belongs to this page owner, and has the necessary permissions to post content
180 if ($verified === 2) {
182 } elseif ($verified === 1) {
187 if (is_array($_SESSION['remote'])) {
188 foreach ($_SESSION['remote'] as $visitor) {
189 if ($visitor['uid'] == $owner) {
190 $cid = $visitor['cid'];
200 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `user`.`uid` = `contact`.`uid`
201 WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
202 AND `user`.`blockwall` = 0 AND `readonly` = 0 AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
205 intval(CONTACT_IS_SHARING),
206 intval(CONTACT_IS_FRIEND),
207 intval(PAGE_COMMUNITY)
210 if (dbm::is_result($r)) {
224 function permissions_sql($owner_id, $remote_verified = false, $groups = null) {
226 $local_user = local_user();
227 $remote_user = remote_user();
230 * Construct permissions
232 * default permissions - anonymous user
234 $sql = " AND allow_cid = ''
241 * Profile owner - everything is visible
244 if (($local_user) && ($local_user == $owner_id)) {
246 } elseif ($remote_user) {
248 * Authenticated visitor. Unless pre-verified,
249 * check that the contact belongs to this $owner_id
250 * and load the groups the visitor belongs to.
251 * If pre-verified, the caller is expected to have already
252 * done this and passed the groups into this function.
255 if (! $remote_verified) {
256 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
257 intval($remote_user),
260 if (dbm::is_result($r)) {
261 $remote_verified = true;
262 $groups = init_groups_visitor($remote_user);
265 if ($remote_verified) {
267 $gs = '<<>>'; // should be impossible to match
269 if (is_array($groups) && count($groups)) {
270 foreach ($groups as $g)
271 $gs .= '|<' . intval($g) . '>';
275 * @TODO old-lost code found?
277 " AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' )
278 AND ( deny_cid = '' OR NOT deny_cid REGEXP '<%d>' )
279 AND ( allow_gid = '' OR allow_gid REGEXP '%s' )
280 AND ( deny_gid = '' OR NOT deny_gid REGEXP '%s')
282 intval($remote_user),
283 intval($remote_user),
289 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
290 AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
293 intval($remote_user),
295 intval($remote_user),
304 function item_permissions_sql($owner_id, $remote_verified = false, $groups = null) {
306 $local_user = local_user();
307 $remote_user = remote_user();
310 * Construct permissions
312 * default permissions - anonymous user
314 $sql = " AND `item`.allow_cid = ''
315 AND `item`.allow_gid = ''
316 AND `item`.deny_cid = ''
317 AND `item`.deny_gid = ''
318 AND `item`.private = 0
322 * Profile owner - everything is visible
324 if ($local_user && ($local_user == $owner_id)) {
326 } elseif ($remote_user) {
328 * Authenticated visitor. Unless pre-verified,
329 * check that the contact belongs to this $owner_id
330 * and load the groups the visitor belongs to.
331 * If pre-verified, the caller is expected to have already
332 * done this and passed the groups into this function.
334 if (! $remote_verified) {
335 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
336 intval($remote_user),
339 if (dbm::is_result($r)) {
340 $remote_verified = true;
341 $groups = init_groups_visitor($remote_user);
344 if ($remote_verified) {
346 $gs = '<<>>'; // should be impossible to match
348 if (is_array($groups) && count($groups)) {
349 foreach ($groups as $g) {
350 $gs .= '|<' . intval($g) . '>';
355 /*" AND ( private = 0 OR ( private in (1,2) AND wall = 1 AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' )
356 AND ( deny_cid = '' OR NOT deny_cid REGEXP '<%d>' )
357 AND ( allow_gid = '' OR allow_gid REGEXP '%s' )
358 AND ( deny_gid = '' OR NOT deny_gid REGEXP '%s')))
360 intval($remote_user),
361 intval($remote_user),
365 " AND ( `item`.private = 0 OR ( `item`.private in (1,2) AND `item`.`wall` = 1
366 AND ( NOT (`item`.deny_cid REGEXP '<%d>' OR `item`.deny_gid REGEXP '%s')
367 AND ( `item`.allow_cid REGEXP '<%d>' OR `item`.allow_gid REGEXP '%s' OR ( `item`.allow_cid = '' AND `item`.allow_gid = '')))))
369 intval($remote_user),
371 intval($remote_user),
382 * Functions used to protect against Cross-Site Request Forgery
383 * 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.
384 * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
385 * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
386 * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
387 * A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
388 * If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
389 * Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
390 * 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).
392 function get_form_security_token($typename = '') {
396 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
398 return $timestamp . '.' . $sec_hash;
401 function check_form_security_token($typename = '', $formname = 'form_security_token') {
402 if (!x($_REQUEST, $formname)) {
406 /// @TODO Careful, not secured!
407 $hash = $_REQUEST[$formname];
409 $max_livetime = 10800; // 3 hours
413 $x = explode('.', $hash);
414 if (time() > (IntVal($x[0]) + $max_livetime)) {
418 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
420 return ($sec_hash == $x[1]);
423 function check_form_security_std_err_msg() {
424 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;
426 function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token') {
427 if (!check_form_security_token($typename, $formname)) {
429 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
430 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
431 notice( check_form_security_std_err_msg() );
432 goaway(System::baseUrl() . $err_redirect );
435 function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token') {
436 if (!check_form_security_token($typename, $formname)) {
438 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
439 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
440 header('HTTP/1.1 403 Forbidden');
445 // Returns an array of group id's this contact is a member of.
446 // This array will only contain group id's related to the uid of this
447 // DFRN contact. They are *not* neccessarily unique across the entire site.
450 if (! function_exists('init_groups_visitor')) {
451 function init_groups_visitor($contact_id) {
453 $r = q("SELECT `gid` FROM `group_member`
454 WHERE `contact-id` = %d ",
457 if (dbm::is_result($r)) {
459 $groups[] = $rr['gid'];