4 use Friendica\Core\Config;
5 use Friendica\Core\PConfig;
6 use Friendica\Core\System;
7 use Friendica\Database\DBM;
10 * @brief Calculate the hash that is needed for the "Friendica" cookie
12 * @param array $user Record from "user" table
14 * @return string Hashed data
16 function cookie_hash($user) {
17 return(hash("sha256", Config::get("system", "site_prvkey").
23 * @brief Set the "Friendica" cookie
26 * @param array $user Record from "user" table
28 function new_cookie($time, $user = array()) {
31 $time = $time + time();
35 $value = json_encode(array("uid" => $user["uid"],
36 "hash" => cookie_hash($user),
37 "ip" => $_SERVER['REMOTE_ADDR']));
43 setcookie("Friendica", $value, $time, "/", "",
44 (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL), true);
48 function authenticate_success($user_record, $login_initial = false, $interactive = false, $login_refresh = false) {
52 $_SESSION['uid'] = $user_record['uid'];
53 $_SESSION['theme'] = $user_record['theme'];
54 $_SESSION['mobile-theme'] = PConfig::get($user_record['uid'], 'system', 'mobile_theme');
55 $_SESSION['authenticated'] = 1;
56 $_SESSION['page_flags'] = $user_record['page-flags'];
57 $_SESSION['my_url'] = System::baseUrl() . '/profile/' . $user_record['nickname'];
58 $_SESSION['my_address'] = $user_record['nickname'] . '@' . substr(System::baseUrl(),strpos(System::baseUrl(),'://')+3);
59 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
61 $a->user = $user_record;
64 if ($a->user['login_date'] <= NULL_DATE) {
65 $_SESSION['return_url'] = 'profile_photo/new';
66 $a->module = 'profile_photo';
67 info( t("Welcome ") . $a->user['username'] . EOL);
68 info( t('Please upload a profile photo.') . EOL);
70 info( t("Welcome back ") . $a->user['username'] . EOL);
74 $member_since = strtotime($a->user['register_date']);
75 if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
76 $_SESSION['new_member'] = true;
78 $_SESSION['new_member'] = false;
80 if (strlen($a->user['timezone'])) {
81 date_default_timezone_set($a->user['timezone']);
82 $a->timezone = $a->user['timezone'];
85 $master_record = $a->user;
87 if ((x($_SESSION,'submanage')) && intval($_SESSION['submanage'])) {
88 $r = dba::fetch_first("SELECT * FROM `user` WHERE `uid` = ? LIMIT 1",
89 intval($_SESSION['submanage'])
91 if (DBM::is_result($r)) {
96 $r = dba::select('user', array('uid', 'username', 'nickname'),
97 array('password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false));
98 if (DBM::is_result($r)) {
99 $a->identities = dba::inArray($r);
101 $a->identities = array();
104 $r = dba::p("SELECT `user`.`uid`, `user`.`username`, `user`.`nickname`
106 INNER JOIN `user` ON `manage`.`mid` = `user`.`uid`
107 WHERE `user`.`account_removed` = 0 AND `manage`.`uid` = ?",
108 $master_record['uid']
110 if (DBM::is_result($r)) {
111 $a->identities = array_merge($a->identities, dba::inArray($r));
114 if ($login_initial) {
115 logger('auth_identities: ' . print_r($a->identities,true), LOGGER_DEBUG);
117 if ($login_refresh) {
118 logger('auth_identities refresh: ' . print_r($a->identities,true), LOGGER_DEBUG);
121 $r = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `self` LIMIT 1", $_SESSION['uid']);
122 if (DBM::is_result($r)) {
125 $_SESSION['cid'] = $a->cid;
128 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] .'"');
130 if ($login_initial || $login_refresh) {
131 dba::update('user', array('login_date' => datetime_convert()), array('uid' => $_SESSION['uid']));
133 // Set the login date for all identities of the user
134 dba::update('user', array('login_date' => datetime_convert()),
135 array('password' => $master_record['password'], 'email' => $master_record['email'], 'account_removed' => false));
138 if ($login_initial) {
139 // If the user specified to remember the authentication, then set a cookie
140 // that expires after one week (the default is when the browser is closed).
141 // The cookie will be renewed automatically.
142 // The week ensures that sessions will expire after some inactivity.
143 if ($_SESSION['remember']) {
144 logger('Injecting cookie for remembered user '. $_SESSION['remember_user']['nickname']);
145 new_cookie(604800, $user_record);
146 unset($_SESSION['remember']);
150 if ($login_initial) {
151 call_hooks('logged_in', $a->user);
153 if (($a->module !== 'home') && isset($_SESSION['return_url'])) {
154 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
161 function can_write_wall(App $a, $owner) {
163 static $verified = 0;
165 if ((! (local_user())) && (! (remote_user()))) {
171 if (($uid) && ($uid == $owner)) {
177 // use remembered decision and avoid a DB lookup for each and every display item
178 // DO NOT use this function if there are going to be multiple owners
180 // We have a contact-id for an authenticated remote user, this block determines if the contact
181 // belongs to this page owner, and has the necessary permissions to post content
183 if ($verified === 2) {
185 } elseif ($verified === 1) {
190 if (is_array($_SESSION['remote'])) {
191 foreach ($_SESSION['remote'] as $visitor) {
192 if ($visitor['uid'] == $owner) {
193 $cid = $visitor['cid'];
203 $r = q("SELECT `contact`.*, `user`.`page-flags` FROM `contact` INNER JOIN `user` on `user`.`uid` = `contact`.`uid`
204 WHERE `contact`.`uid` = %d AND `contact`.`id` = %d AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
205 AND `user`.`blockwall` = 0 AND `readonly` = 0 AND ( `contact`.`rel` IN ( %d , %d ) OR `user`.`page-flags` = %d ) LIMIT 1",
208 intval(CONTACT_IS_SHARING),
209 intval(CONTACT_IS_FRIEND),
210 intval(PAGE_COMMUNITY)
213 if (DBM::is_result($r)) {
227 function permissions_sql($owner_id, $remote_verified = false, $groups = null) {
229 $local_user = local_user();
230 $remote_user = remote_user();
233 * Construct permissions
235 * default permissions - anonymous user
237 $sql = " AND allow_cid = ''
244 * Profile owner - everything is visible
247 if (($local_user) && ($local_user == $owner_id)) {
249 } elseif ($remote_user) {
251 * Authenticated visitor. Unless pre-verified,
252 * check that the contact belongs to this $owner_id
253 * and load the groups the visitor belongs to.
254 * If pre-verified, the caller is expected to have already
255 * done this and passed the groups into this function.
258 if (! $remote_verified) {
259 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
260 intval($remote_user),
263 if (DBM::is_result($r)) {
264 $remote_verified = true;
265 $groups = init_groups_visitor($remote_user);
268 if ($remote_verified) {
270 $gs = '<<>>'; // should be impossible to match
272 if (is_array($groups) && count($groups)) {
273 foreach ($groups as $g)
274 $gs .= '|<' . intval($g) . '>';
278 * @TODO old-lost code found?
280 " AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' )
281 AND ( deny_cid = '' OR NOT deny_cid REGEXP '<%d>' )
282 AND ( allow_gid = '' OR allow_gid REGEXP '%s' )
283 AND ( deny_gid = '' OR NOT deny_gid REGEXP '%s')
285 intval($remote_user),
286 intval($remote_user),
292 " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')
293 AND ( allow_cid REGEXP '<%d>' OR allow_gid REGEXP '%s' OR ( allow_cid = '' AND allow_gid = '') )
296 intval($remote_user),
298 intval($remote_user),
307 function item_permissions_sql($owner_id, $remote_verified = false, $groups = null) {
309 $local_user = local_user();
310 $remote_user = remote_user();
313 * Construct permissions
315 * default permissions - anonymous user
317 $sql = " AND `item`.allow_cid = ''
318 AND `item`.allow_gid = ''
319 AND `item`.deny_cid = ''
320 AND `item`.deny_gid = ''
321 AND `item`.private = 0
325 * Profile owner - everything is visible
327 if ($local_user && ($local_user == $owner_id)) {
329 } elseif ($remote_user) {
331 * Authenticated visitor. Unless pre-verified,
332 * check that the contact belongs to this $owner_id
333 * and load the groups the visitor belongs to.
334 * If pre-verified, the caller is expected to have already
335 * done this and passed the groups into this function.
337 if (! $remote_verified) {
338 $r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1",
339 intval($remote_user),
342 if (DBM::is_result($r)) {
343 $remote_verified = true;
344 $groups = init_groups_visitor($remote_user);
347 if ($remote_verified) {
349 $gs = '<<>>'; // should be impossible to match
351 if (is_array($groups) && count($groups)) {
352 foreach ($groups as $g) {
353 $gs .= '|<' . intval($g) . '>';
358 /*" AND ( private = 0 OR ( private in (1,2) AND wall = 1 AND ( allow_cid = '' OR allow_cid REGEXP '<%d>' )
359 AND ( deny_cid = '' OR NOT deny_cid REGEXP '<%d>' )
360 AND ( allow_gid = '' OR allow_gid REGEXP '%s' )
361 AND ( deny_gid = '' OR NOT deny_gid REGEXP '%s')))
363 intval($remote_user),
364 intval($remote_user),
368 " AND ( `item`.private = 0 OR ( `item`.private in (1,2) AND `item`.`wall` = 1
369 AND ( NOT (`item`.deny_cid REGEXP '<%d>' OR `item`.deny_gid REGEXP '%s')
370 AND ( `item`.allow_cid REGEXP '<%d>' OR `item`.allow_gid REGEXP '%s' OR ( `item`.allow_cid = '' AND `item`.allow_gid = '')))))
372 intval($remote_user),
374 intval($remote_user),
385 * Functions used to protect against Cross-Site Request Forgery
386 * 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.
387 * In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
388 * or if the security token is used for ajax-calls that happen several times), but only valid for a certain amout of time (3hours).
389 * The "typename" seperates the security tokens of different types of forms. This could be relevant in the following case:
390 * A security token is used to protekt a link from CSRF (e.g. the "delete this profile"-link).
391 * If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
392 * Actually, important actions should not be triggered by Links / GET-Requests at all, but somethimes they still are,
393 * 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).
395 function get_form_security_token($typename = '') {
399 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $timestamp . $typename);
401 return $timestamp . '.' . $sec_hash;
404 function check_form_security_token($typename = '', $formname = 'form_security_token') {
405 if (!x($_REQUEST, $formname)) {
409 /// @TODO Careful, not secured!
410 $hash = $_REQUEST[$formname];
412 $max_livetime = 10800; // 3 hours
416 $x = explode('.', $hash);
417 if (time() > (IntVal($x[0]) + $max_livetime)) {
421 $sec_hash = hash('whirlpool', $a->user['guid'] . $a->user['prvkey'] . session_id() . $x[0] . $typename);
423 return ($sec_hash == $x[1]);
426 function check_form_security_std_err_msg() {
427 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;
429 function check_form_security_token_redirectOnErr($err_redirect, $typename = '', $formname = 'form_security_token') {
430 if (!check_form_security_token($typename, $formname)) {
432 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
433 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
434 notice( check_form_security_std_err_msg() );
435 goaway(System::baseUrl() . $err_redirect );
438 function check_form_security_token_ForbiddenOnErr($typename = '', $formname = 'form_security_token') {
439 if (!check_form_security_token($typename, $formname)) {
441 logger('check_form_security_token failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
442 logger('check_form_security_token failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA);
443 header('HTTP/1.1 403 Forbidden');
448 // Returns an array of group id's this contact is a member of.
449 // This array will only contain group id's related to the uid of this
450 // DFRN contact. They are *not* neccessarily unique across the entire site.
453 if (! function_exists('init_groups_visitor')) {
454 function init_groups_visitor($contact_id) {
456 $r = q("SELECT `gid` FROM `group_member`
457 WHERE `contact-id` = %d ",
460 if (DBM::is_result($r)) {
462 $groups[] = $rr['gid'];