6 * @brief Calculate the hash that is needed for the "Friendica" cookie
8 * @param array $user Record from "user" table
10 * @return string Hashed data
12 function cookie_hash($user) {
13 return(hash("sha256", get_config("system", "site_prvkey").
19 * @brief Set the "Friendica" cookie
22 * @param array $user Record from "user" table
24 function new_cookie($time, $user = array()) {
27 $time = $time + time();
31 $value = json_encode(array("uid" => $user["uid"],
32 "hash" => cookie_hash($user),
33 "ip" => $_SERVER['REMOTE_ADDR']));
39 setcookie("Friendica", $value, $time, "/", "",
40 (get_config('system', 'ssl_policy') == SSL_POLICY_FULL), true);
44 function authenticate_success($user_record, $login_initial = false, $interactive = false, $login_refresh = false) {
48 $_SESSION['uid'] = $user_record['uid'];
49 $_SESSION['theme'] = $user_record['theme'];
50 $_SESSION['mobile-theme'] = get_pconfig($user_record['uid'], 'system', 'mobile_theme');
51 $_SESSION['authenticated'] = 1;
52 $_SESSION['page_flags'] = $user_record['page-flags'];
53 $_SESSION['my_url'] = App::get_baseurl() . '/profile/' . $user_record['nickname'];
54 $_SESSION['my_address'] = $user_record['nickname'] . '@' . substr(App::get_baseurl(),strpos(App::get_baseurl(),'://')+3);
55 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
57 $a->user = $user_record;
60 if ($a->user['login_date'] <= NULL_DATE) {
61 $_SESSION['return_url'] = 'profile_photo/new';
62 $a->module = 'profile_photo';
63 info( t("Welcome ") . $a->user['username'] . EOL);
64 info( t('Please upload a profile photo.') . EOL);
66 info( t("Welcome back ") . $a->user['username'] . EOL);
70 $member_since = strtotime($a->user['register_date']);
71 if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
72 $_SESSION['new_member'] = true;
74 $_SESSION['new_member'] = false;
76 if (strlen($a->user['timezone'])) {
77 date_default_timezone_set($a->user['timezone']);
78 $a->timezone = $a->user['timezone'];
81 $master_record = $a->user;
83 if ((x($_SESSION,'submanage')) && intval($_SESSION['submanage'])) {
84 $r = dba::fetch_first("SELECT * FROM `user` WHERE `uid` = ? LIMIT 1",
85 intval($_SESSION['submanage'])
87 if (dbm::is_result($r)) {
92 $r = dba::select('user', array('uid', 'username', 'nickname'),
93 array('password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false));
94 if (dbm::is_result($r)) {
95 $a->identities = dba::inArray($r);
97 $a->identities = array();
100 $r = dba::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
102 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
103 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
104 $master_record['uid']
106 if (dbm::is_result($r)) {
107 $a->identities = array_merge($a->identities, dba::inArray($r));
110 if ($login_initial) {
111 logger('auth_identities: ' . print_r($a->identities,true), LOGGER_DEBUG);
113 if ($login_refresh) {
114 logger('auth_identities refresh: ' . print_r($a->identities,true), LOGGER_DEBUG);
117 $r = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `self` LIMIT 1", $_SESSION['uid']);
118 if (dbm::is_result($r)) {
121 $_SESSION['cid'] = $a->cid;
124 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] .'"');
126 if ($login_initial || $login_refresh) {
127 dba::update('user', array('login_date' => datetime_convert()), array('uid' => $_SESSION['uid']));
129 // Set the login date for all identities of the user
130 dba::update('user', array('login_date' => datetime_convert()),
131 array('password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false));
134 if ($login_initial) {
135 // If the user specified to remember the authentication, then set a cookie
136 // that expires after one week (the default is when the browser is closed).
137 // The cookie will be renewed automatically.
138 // The week ensures that sessions will expire after some inactivity.
139 if ($_SESSION['remember']) {
140 logger('Injecting cookie for remembered user '. $_SESSION['remember_user']['nickname']);
141 new_cookie(604800, $user_record);
142 unset($_SESSION['remember']);
146 if ($login_initial) {
147 call_hooks('logged_in', $a->user);
149 if (($a->module !== 'home') && isset($_SESSION['return_url'])) {
150 goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
157 function can_write_wall(App $a, $owner) {
159 static $verified = 0;
161 if ((! (local_user())) && (! (remote_user()))) {
167 if (($uid) && ($uid == $owner)) {
173 // use remembered decision and avoid a DB lookup for each and every display item
174 // DO NOT use this function if there are going to be multiple owners
176 // We have a contact-id for an authenticated remote user, this block determines if the contact
177 // belongs to this page owner, and has the necessary permissions to post content
179 if ($verified === 2) {
181 } elseif ($verified === 1) {
186 if (is_array($_SESSION['remote'])) {
187 foreach ($_SESSION['remote'] as $visitor) {
188 if ($visitor['uid'] == $owner) {
189 $cid = $visitor['cid'];
199 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `user`.`uid` = `contact`.`uid`
200 WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
201 AND `user`.`blockwall` = 0 AND `readonly` = 0 AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
204 intval(CONTACT_IS_SHARING),
205 intval(CONTACT_IS_FRIEND),
206 intval(PAGE_COMMUNITY)
209 if (dbm::is_result($r)) {
223 function permissions_sql($owner_id, $remote_verified = false, $groups = null) {
225 $local_user = local_user();
226 $remote_user = remote_user();
229 * Construct permissions
231 * default permissions - anonymous user
233 $sql = " AND allow_cid = ''
240 * Profile owner - everything is visible
243 if (($local_user) && ($local_user == $owner_id)) {
245 } elseif ($remote_user) {
247 * Authenticated visitor. Unless pre-verified,
248 * check that the contact belongs to this $owner_id
249 * and load the groups the visitor belongs to.
250 * If pre-verified, the caller is expected to have already
251 * done this and passed the groups into this function.
254 if (! $remote_verified) {
255 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
256 intval($remote_user),
259 if (dbm::is_result($r)) {
260 $remote_verified = true;
261 $groups = init_groups_visitor($remote_user);
264 if ($remote_verified) {
266 $gs = '<<>>'; // should be impossible to match
268 if (is_array($groups) && count($groups)) {
269 foreach ($groups as $g)
270 $gs .= '|<' . intval($g) . '>';
274 * @TODO old-lost code found?
276 " AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' )
277 AND ( deny_cid = '' OR NOT deny_cid REGEXP '<%d>' )
278 AND ( allow_gid = '' OR allow_gid REGEXP '%s' )
279 AND ( deny_gid = '' OR NOT deny_gid REGEXP '%s')
281 intval($remote_user),
282 intval($remote_user),
288 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
289 AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
292 intval($remote_user),
294 intval($remote_user),
303 function item_permissions_sql($owner_id, $remote_verified = false, $groups = null) {
305 $local_user = local_user();
306 $remote_user = remote_user();
309 * Construct permissions
311 * default permissions - anonymous user
313 $sql = " AND `item`.allow_cid = ''
314 AND `item`.allow_gid = ''
315 AND `item`.deny_cid = ''
316 AND `item`.deny_gid = ''
317 AND `item`.private = 0
321 * Profile owner - everything is visible
323 if ($local_user && ($local_user == $owner_id)) {
325 } elseif ($remote_user) {
327 * Authenticated visitor. Unless pre-verified,
328 * check that the contact belongs to this $owner_id
329 * and load the groups the visitor belongs to.
330 * If pre-verified, the caller is expected to have already
331 * done this and passed the groups into this function.
333 if (! $remote_verified) {
334 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
335 intval($remote_user),
338 if (dbm::is_result($r)) {
339 $remote_verified = true;
340 $groups = init_groups_visitor($remote_user);
343 if ($remote_verified) {
345 $gs = '<<>>'; // should be impossible to match
347 if (is_array($groups) && count($groups)) {
348 foreach ($groups as $g) {
349 $gs .= '|<' . intval($g) . '>';
354 /*" AND ( private = 0 OR ( private in (1,2) AND wall = 1 AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' )
355 AND ( deny_cid = '' OR NOT deny_cid REGEXP '<%d>' )
356 AND ( allow_gid = '' OR allow_gid REGEXP '%s' )
357 AND ( deny_gid = '' OR NOT deny_gid REGEXP '%s')))
359 intval($remote_user),
360 intval($remote_user),
364 " AND ( `item`.private = 0 OR ( `item`.private in (1,2) AND `item`.`wall` = 1
365 AND ( NOT (`item`.deny_cid REGEXP '<%d>' OR `item`.deny_gid REGEXP '%s')
366 AND ( `item`.allow_cid REGEXP '<%d>' OR `item`.allow_gid REGEXP '%s' OR ( `item`.allow_cid = '' AND `item`.allow_gid = '')))))
368 intval($remote_user),
370 intval($remote_user),
381 * Functions used to protect against Cross-Site Request Forgery
382 * 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.
383 * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
384 * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
385 * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
386 * A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
387 * If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
388 * Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
389 * 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).
391 function get_form_security_token($typename = '') {
395 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
397 return $timestamp . '.' . $sec_hash;
400 function check_form_security_token($typename = '', $formname = 'form_security_token') {
401 if (!x($_REQUEST, $formname)) {
405 /// @TODO Careful, not secured!
406 $hash = $_REQUEST[$formname];
408 $max_livetime = 10800; // 3 hours
412 $x = explode('.', $hash);
413 if (time() > (IntVal($x[0]) + $max_livetime)) {
417 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
419 return ($sec_hash == $x[1]);
422 function check_form_security_std_err_msg() {
423 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;
425 function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token') {
426 if (!check_form_security_token($typename, $formname)) {
428 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
429 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
430 notice( check_form_security_std_err_msg() );
431 goaway(App::get_baseurl() . $err_redirect );
434 function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token') {
435 if (!check_form_security_token($typename, $formname)) {
437 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
438 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
439 header('HTTP/1.1 403 Forbidden');
444 // Returns an array of group id's this contact is a member of.
445 // This array will only contain group id's related to the uid of this
446 // DFRN contact. They are *not* neccessarily unique across the entire site.
449 if (! function_exists('init_groups_visitor')) {
450 function init_groups_visitor($contact_id) {
452 $r = q("SELECT `gid` FROM `group_member`
453 WHERE `contact-id` = %d ",
456 if (dbm::is_result($r)) {
458 $groups[] = $rr['gid'];