<?php
$cdata = parse_url($setting['url']);
include "data/" . $user_settings['instance'] . ".php";

$cSession = curl_init();
curl_setopt($cSession, CURLOPT_URL, "https://" . $user_settings['instance'] . "/oauth/token");
curl_setopt($cSession, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cSession, CURLOPT_HEADER, false);
curl_setopt($cSession, CURLOPT_POST, 1);
curl_setopt($cSession, CURLOPT_POSTFIELDS, http_build_query(array(
	'client_id' => $client['client_id'],
	'client_secret' => $client['client_secret'],
	'grant_type' => 'authorization_code',
	'grant_type' => 'authorization_code',
	'code' => $_GET['code'],
	'redirect_uri' => $client['redirect_uri']
)));
$result = curl_exec($cSession);
curl_close($cSession);
$data = json_decode($result, true);
//$atoken = msc($data['access_token'],'e');

$atoken = (isset($_COOKIE['token']) ? json_decode(base64_decode($_COOKIE['token']),true) : array());
$atoken[$index] = $data['access_token'];

setcookie('token', base64_encode(json_encode($atoken)), time() + 60 * 60 * 24 * 30, $cdata['path'], $cdata['host'], false, true);
$token = $data['access_token'];

$info = api_get("accounts/verify_credentials");

$cookie[$index]['acct'] = $info['acct'];
$cookie[$index]['username'] = $info['display_name'];
$cookie[$index]['avatar'] = $info['avatar'];
$cookie[$index]['uid'] = $info['id'];
$cookie[$index]['linkpv'] = "on";

$info = api_get("instance");
if (is_numeric(strpos($info['version'], 'Pleroma'))) {
	$cookie[$index]['pleroma'] = 'true';
}

setrawcookie("user_settings", base64_encode(json_encode($cookie)) , time() + 60 * 60 * 24 * 30, '/');

header('Location: ' . $setting['url']);

