$envato->set_manual_token($_SESSION['oauth_token']);
        $new_access = $envato->refresh_token();
        if ($new_access) {
            $_SESSION['oauth_token']['access_token'] = $new_access;
        }
        echo json_encode(array('new_token' => $new_access));
    } else {
        echo '-1';
    }
    exit;
}
if (!empty($_REQUEST['code'])) {
    // we have a login callback.
    $token = false;
    try {
        $token = $envato->get_authentication($_REQUEST['code']);
    } catch (Exception $e) {
    }
    if ($token && !empty($token['access_token']) && !empty($token['expires_in'])) {
        $token['expires'] = time() + $token['expires_in'];
        $_SESSION['oauth_token'] = $token;
        $_SESSION['theme'] = isset($_REQUEST['theme']) ? $_REQUEST['theme'] : false;
        $_SESSION['version'] = isset($_REQUEST['version']) ? $_REQUEST['version'] : false;
        $_SESSION['url'] = isset($_REQUEST['url']) ? $_REQUEST['url'] : false;
    }
    ?>

	<!doctype html>
	<html>
	<head>
		<meta charset="utf-8">
    $_SESSION['returnto'] = $_GET['returnto'];
    $_SESSION['item_id'] = $_GET['item_id'];
    $_SESSION['slug'] = $_GET['slug'];
    $_SESSION['auth'] = $_GET['auth'];
    $_SESSION['time'] = time();
    if (!empty($_SESSION['returnto']) && !empty($_SESSION['returnto']) && !empty($_SESSION['returnto'])) {
        $url = $api->get_authorization_url();
    } else {
        $url = $api->get_authorization_url();
    }
    header('Location: ' . $url);
    exit;
    //return from the Envato authorization page
} elseif (isset($_GET['code'])) {
    @session_start();
    $response = $api->get_authentication($_GET['code']);
    if (isset($response['error'])) {
        $url = buildquery($_SESSION['returnto'], array('mymail_error' => urlencode($response['error_description']), 'mymail_nonce' => $_SESSION['auth']));
    } else {
        if (isset($response['refresh_token']) && isset($response['access_token'])) {
            $api->set_personal_token($response['access_token']);
            $params = buildquery(array('item_id' => (int) $_SESSION['item_id'], 'shorten_url' => 'true'));
            $response = $api->get('v3/market/buyer/download' . $params, false, false);
            $item_id = (int) $_SESSION['item_id'];
            $slug = $_SESSION['slug'];
            if (isset($response['error'])) {
                $error_description = $response['description'];
                $url = buildquery($_SESSION['returnto'], array('mymail_error' => urlencode($error_description), 'mymail_slug' => $slug, 'mymail_nonce' => $_SESSION['auth']));
            } else {
                if (isset($response['download_url'])) {
                    $download_url = $response['download_url'];