4 * @brief Calculate the hash that is needed for the "Friendica" cookie
6 * @param array $user Record from "user" table
8 * @return string Hashed data
10 function cookie_hash($user) {
11 return(hash("sha256", get_config("system", "site_prvkey").
17 * @brief Set the "Friendica" cookie
20 * @param array $user Record from "user" table
22 function new_cookie($time, $user = array()) {
25 $time = $time + time();
29 $value = json_encode(array("uid" => $user["uid"],
30 "hash" => cookie_hash($user),
31 "ip" => $_SERVER['REMOTE_ADDR']));
37 setcookie("Friendica", $value, $time, "/", "",
38 (get_config('system', 'ssl_policy') == SSL_POLICY_FULL), true);
42 function authenticate_success($user_record, $login_initial = false, $interactive = false, $login_refresh = false) {
46 $_SESSION['uid'] = $user_record['uid'];
47 $_SESSION['theme'] = $user_record['theme'];
48 $_SESSION['mobile-theme'] = get_pconfig($user_record['uid'], 'system', 'mobile_theme');
49 $_SESSION['authenticated'] = 1;
50 $_SESSION['page_flags'] = $user_record['page-flags'];
51 $_SESSION['my_url'] = App::get_baseurl() . '/profile/' . $user_record['nickname'];
52 $_SESSION['my_address'] = $user_record['nickname'] . '@' . substr(App::get_baseurl(),strpos(App::get_baseurl(),'://')+3);
53 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
55 $a->user = $user_record;
58 if ($a->user['login_date'] <= NULL_DATE) {
59 $_SESSION['return_url'] = 'profile_photo/new';
60 $a->module = 'profile_photo';
61 info( t("Welcome ") . $a->user['username'] . EOL);
62 info( t('Please upload a profile photo.') . EOL);
65 info( t("Welcome back ") . $a->user['username'] . EOL);
68 $member_since = strtotime($a->user['register_date']);
69 if(time() < ($member_since + ( 60 * 60 * 24 * 14)))
70 $_SESSION['new_member'] = true;
72 $_SESSION['new_member'] = false;
73 if(strlen($a->user['timezone'])) {
74 date_default_timezone_set($a->user['timezone']);
75 $a->timezone = $a->user['timezone'];
78 $master_record = $a->user;
80 if((x($_SESSION,'submanage')) && intval($_SESSION['submanage'])) {
81 $r = q("select * from user where uid = %d limit 1",
82 intval($_SESSION['submanage'])
84 if (dbm::is_result($r))
85 $master_record = $r[0];
88 $r = q("SELECT `uid`,`username`,`nickname` FROM `user` WHERE `password` = '%s' AND `email` = '%s' AND `account_removed` = 0 ",
89 dbesc($master_record['password']),
90 dbesc($master_record['email'])
92 if (dbm::is_result($r))
95 $a->identities = array();
97 $r = q("select `user`.`uid`, `user`.`username`, `user`.`nickname`
98 from manage INNER JOIN user on manage.mid = user.uid where `user`.`account_removed` = 0
99 and `manage`.`uid` = %d",
100 intval($master_record['uid'])
102 if (dbm::is_result($r))
103 $a->identities = array_merge($a->identities,$r);
106 logger('auth_identities: ' . print_r($a->identities,true), LOGGER_DEBUG);
108 logger('auth_identities refresh: ' . print_r($a->identities,true), LOGGER_DEBUG);
110 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
111 intval($_SESSION['uid']));
112 if (dbm::is_result($r)) {
114 $a->cid = $r[0]['id'];
115 $_SESSION['cid'] = $a->cid;
118 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] .'"');
120 if($login_initial || $login_refresh) {
122 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d",
123 dbesc(datetime_convert()),
124 intval($_SESSION['uid'])
127 // Set the login date for all identities of the user
128 q("UPDATE `user` SET `login_date` = '%s' WHERE `password` = '%s' AND `email` = '%s' AND `account_removed` = 0",
129 dbesc(datetime_convert()),
130 dbesc($master_record['password']),
131 dbesc($master_record['email'])
137 if ($login_initial) {
138 // If the user specified to remember the authentication, then set a cookie
139 // that expires after one week (the default is when the browser is closed).
140 // The cookie will be renewed automatically.
141 // The week ensures that sessions will expire after some inactivity.
142 if ($_SESSION['remember']) {
143 logger('Injecting cookie for remembered user '. $_SESSION['remember_user']['nickname']);
144 new_cookie(604800, $user_record);
145 unset($_SESSION['remember']);
151 if ($login_initial) {
152 call_hooks('logged_in', $a->user);
154 if (($a->module !== 'home') && isset($_SESSION['return_url'])) {
155 goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
163 function can_write_wall(App $a, $owner) {
165 static $verified = 0;
167 if ((! (local_user())) && (! (remote_user()))) {
173 if (($uid) && ($uid == $owner)) {
179 // use remembered decision and avoid a DB lookup for each and every display item
180 // DO NOT use this function if there are going to be multiple owners
182 // We have a contact-id for an authenticated remote user, this block determines if the contact
183 // belongs to this page owner, and has the necessary permissions to post content
185 if ($verified === 2) {
187 } elseif ($verified === 1) {
192 if (is_array($_SESSION['remote'])) {
193 foreach ($_SESSION['remote'] as $visitor) {
194 if ($visitor['uid'] == $owner) {
195 $cid = $visitor['cid'];
205 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `user`.`uid` = `contact`.`uid`
206 WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
207 AND `user`.`blockwall` = 0 AND `readonly` = 0 AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
210 intval(CONTACT_IS_SHARING),
211 intval(CONTACT_IS_FRIEND),
212 intval(PAGE_COMMUNITY)
215 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
240 $sql = " AND allow_cid = ''
247 * Profile owner - everything is visible
250 if(($local_user) && ($local_user == $owner_id)) {
255 * Authenticated visitor. Unless pre-verified,
256 * check that the contact belongs to this $owner_id
257 * and load the groups the visitor belongs to.
258 * If pre-verified, the caller is expected to have already
259 * done this and passed the groups into this function.
262 elseif($remote_user) {
264 if(! $remote_verified) {
265 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
266 intval($remote_user),
269 if (dbm::is_result($r)) {
270 $remote_verified = true;
271 $groups = init_groups_visitor($remote_user);
274 if($remote_verified) {
276 $gs = '<<>>'; // should be impossible to match
278 if(is_array($groups) && count($groups)) {
279 foreach($groups as $g)
280 $gs .= '|<' . intval($g) . '>';
284 " AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' )
285 AND ( deny_cid = '' OR NOT deny_cid REGEXP '<%d>' )
286 AND ( allow_gid = '' OR allow_gid REGEXP '%s' )
287 AND ( deny_gid = '' OR NOT deny_gid REGEXP '%s')
289 intval($remote_user),
290 intval($remote_user),
295 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
296 AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
299 intval($remote_user),
301 intval($remote_user),
310 function item_permissions_sql($owner_id,$remote_verified = false,$groups = null) {
312 $local_user = local_user();
313 $remote_user = remote_user();
316 * Construct permissions
318 * default permissions - anonymous user
321 $sql = " AND `item`.allow_cid = ''
322 AND `item`.allow_gid = ''
323 AND `item`.deny_cid = ''
324 AND `item`.deny_gid = ''
325 AND `item`.private = 0
329 * Profile owner - everything is visible
332 if($local_user && ($local_user == $owner_id)) {
337 * Authenticated visitor. Unless pre-verified,
338 * check that the contact belongs to this $owner_id
339 * and load the groups the visitor belongs to.
340 * If pre-verified, the caller is expected to have already
341 * done this and passed the groups into this function.
344 elseif($remote_user) {
346 if(! $remote_verified) {
347 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
348 intval($remote_user),
351 if (dbm::is_result($r)) {
352 $remote_verified = true;
353 $groups = init_groups_visitor($remote_user);
356 if($remote_verified) {
358 $gs = '<<>>'; // should be impossible to match
360 if(is_array($groups) && count($groups)) {
361 foreach($groups as $g)
362 $gs .= '|<' . intval($g) . '>';
366 /*" AND ( private = 0 OR ( private in (1,2) AND wall = 1 AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' )
367 AND ( deny_cid = '' OR NOT deny_cid REGEXP '<%d>' )
368 AND ( allow_gid = '' OR allow_gid REGEXP '%s' )
369 AND ( deny_gid = '' OR NOT deny_gid REGEXP '%s')))
371 intval($remote_user),
372 intval($remote_user),
376 " AND ( `item`.private = 0 OR ( `item`.private in (1,2) AND `item`.`wall` = 1
377 AND ( NOT (`item`.deny_cid REGEXP '<%d>' OR `item`.deny_gid REGEXP '%s')
378 AND ( `item`.allow_cid REGEXP '<%d>' OR `item`.allow_gid REGEXP '%s' OR ( `item`.allow_cid = '' AND `item`.allow_gid = '')))))
380 intval($remote_user),
382 intval($remote_user),
393 * Functions used to protect against Cross-Site Request Forgery
394 * 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.
395 * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
396 * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
397 * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
398 * A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
399 * If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
400 * Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
401 * 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).
403 function get_form_security_token($typename = '') {
407 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
409 return $timestamp . '.' . $sec_hash;
412 function check_form_security_token($typename = '', $formname = 'form_security_token') {
413 if (!x($_REQUEST, $formname)) return false;
414 $hash = $_REQUEST[$formname];
416 $max_livetime = 10800; // 3 hours
420 $x = explode('.', $hash);
421 if (time() > (IntVal($x[0]) + $max_livetime)) return false;
423 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
425 return ($sec_hash == $x[1]);
428 function check_form_security_std_err_msg() {
429 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;
431 function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token') {
432 if (!check_form_security_token($typename, $formname)) {
434 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
435 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
436 notice( check_form_security_std_err_msg() );
437 goaway(App::get_baseurl() . $err_redirect );
440 function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token') {
441 if (!check_form_security_token($typename, $formname)) {
443 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
444 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
445 header('HTTP/1.1 403 Forbidden');
450 // Returns an array of group id's this contact is a member of.
451 // This array will only contain group id's related to the uid of this
452 // DFRN contact. They are *not* neccessarily unique across the entire site.
455 if(! function_exists('init_groups_visitor')) {
456 function init_groups_visitor($contact_id) {
458 $r = q("SELECT `gid` FROM `group_member`
459 WHERE `contact-id` = %d ",
462 if (dbm::is_result($r)) {
464 $groups[] = $rr['gid'];