SetDefine('FS_CACHE', DIR_ABS . '../cache/');
SetDefine('DIR_CLASSES', DIR_ABS . '../classes/');
// Include Smarty
SetDefine('DIR_SMARTY', DIR_ABS . '../smarty/');
// Include SIMPL
include_once FS_SIMPL . 'simpl.php';
include_once DIR_ABS . '../inc/functions.php';
include_once DIR_SMARTY . 'Smarty.class.php';
include_once DIR_CLASSES . 'utilities.php';
// Connect to database
$db = new Db();
$db->Connect();
// Create the template object
$smarty = new FormTemplates();
// Assign the mode to the templates
$smarty->assign('mode', $mode);
SetDefine('CONSUMER_KEY', '');
SetDefine('CONSUMER_SECRET', '');
SetDefine('OAUTH_CALLBACK', ADDRESS . 'callback');
$myUser = new User();
$myAccountInfo = new AccountInfo();
// If the user has already logged in the past week
if (isset($_COOKIE['session']) && $_COOKIE['session'] != '') {
    // Look the user up and set their session
    $myUser->SetValue('sessionid', $_COOKIE['session']);
    $myUser->GetInfo(NULL, array('sessionid'));
    if ($myUser->GetPrimary() != '') {
        $myAccountInfo->SetValue('user_id', $myUser->GetPrimary());
        $myAccountInfo->GetInfo(NULL, array('user_id'));
    }
}
// Add the new token credentials
$myUser->SetValue('oauth_token', $token_credentials['oauth_token']);
$myUser->SetValue('oauth_token_secret', $token_credentials['oauth_token_secret']);
// Create a unique ID for the session
$myUser->SetValue('sessionid', uniqid());
// Update the user information if found or insert if new
if (!$myUser->Save()) {
    throw new SimplException('Error Saving Formspring Client Token', 2, 'Error: Error Saving Formspring Client Token :' . $details->response->username);
}
// Set the session cookie
if (!isset($_GET['delegate'])) {
    setcookie('session', $myUser->GetValue('sessionid'), time() + 3600 * 24 * 7);
} else {
    // Setup the relationship
    $myAccountAccess->SetValue('user_id', $_GET['delegate']);
    $myAccountAccess->SetValue('delegate_id', $myUser->GetPrimary());
    $myAccountAccess->SetValue('type', 'full');
    if (!$myAccountAccess->Save()) {
        throw new SimplException('Error Saving Delegate Information', 2, 'Error: Error Saving Delegate Information. Delegate:' . $_GET['delegate']);
    }
}
// See if this user already exists in the DB
$myAccountInfo->ResetValues();
$myAccountInfo->SetValue('user_id', $myUser->GetPrimary());
$myAccountInfo->GetInfo(NULL, array('user_id'));
// Add their new values
foreach ((array) $details->response as $field => $value) {
    $myAccountInfo->SetValue($field, $value);
}
$myAccountInfo->SetValue('user_id', $myUser->GetPrimary());
// Update the user information if found or insert if new