-// login/logout
-
-if((x($_SESSION,'authenticated')) && (! ($_POST['auth-params'] == 'login'))) {
- if($_POST['auth-params'] == 'logout' || $a->module == "logout") {
- unset($_SESSION['authenticated']);
- unset($_SESSION['uid']);
- unset($_SESSION['visitor_id']);
- unset($_SESSION['administrator']);
- unset($_SESSION['cid']);
- $_SESSION['sysmsg'] = "Logged out." . EOL;
- goaway($a->get_baseurl());
+// When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
+if (isset($_COOKIE["Friendica"])) {
+ $data = json_decode($_COOKIE["Friendica"]);
+ if (isset($data->uid)) {
+ $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
+ FROM `user` WHERE `uid` = %d AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
+ intval($data->uid)
+ );
+
+ if ($r) {
+ if ($data->hash != cookie_hash($r[0])) {
+ logger("Hash for user ".$data->uid." doesn't fit.");
+ nuke_session();
+ goaway(z_root());
+ }
+
+ // Renew the cookie
+ new_cookie(604800, $r[0]);
+
+ // Do the authentification if not done by now
+ if (!isset($_SESSION) OR !isset($_SESSION['authenticated'])) {
+ authenticate_success($r[0]);
+
+ if (get_config('system','paranoia'))
+ $_SESSION['addr'] = $data->ip;
+ }
+ }
+ }
+}
+
+
+// login/logout
+
+if (isset($_SESSION) && x($_SESSION,'authenticated') && (!x($_POST,'auth-params') || ($_POST['auth-params'] !== 'login'))) {
+
+ if ((x($_POST,'auth-params') && ($_POST['auth-params'] === 'logout')) || ($a->module === 'logout')) {
+
+ // process logout request
+ call_hooks("logging_out");
+ nuke_session();
+ info(t('Logged out.').EOL);
+ goaway(z_root());
+ }
+
+ if (x($_SESSION,'visitor_id') && !x($_SESSION,'uid')) {
+ $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
+ intval($_SESSION['visitor_id'])
+ );
+ if (count($r)) {
+ $a->contact = $r[0];
+ }