function capture_user_sync($profile = false, $setId = false, $redirect = false)
{
    global $vbulletin;
    if ($profile === false) {
        $profile = load_user_entity();
    }
    if ($profile) {
        $userdata =& datamanager_init('User', $vbulletin, ERRTYPE_STANDARD);
        $userdata->set_existing($vbulletin->userinfo);
        $userdata->set('username', $profile['result']['displayName']);
        if ($profile['result']['birthday']) {
            $userdata->set('birthday', $profile['result']['birthday']);
        }
        if ($setId) {
            $userfield = array($vbulletin->options['janrain_capture_uuid'] => $profile['result']['uuid']);
            $customfields = $userdata->set_userfields($userfield, true, 'admin');
        }
        $userdata->save();
        if ($redirect) {
            exec_header_redirect(capture_current_page());
        }
    }
}
function load_user_entity($can_refresh = true)
{
    global $vbulletin;
    if (!$vbulletin->capture_session) {
        if (!$vbulletin->session->vars['capture_access_token'] && !$vbulletin->session->vars['capture_refresh_token']) {
            return NULL;
        } else {
            $vbulletin->capture_session = array("capture_access_token" => $vbulletin->session->vars['capture_access_token'], "capture_refresh_token" => $vbulletin->session->vars['capture_refresh_token'], "capture_expires_in" => $vbulletin->session->vars['capture_expires_in']);
        }
    }
    $user_entity = NULL;
    // TODO might want to do a sanity check on capture_session,
    //      in case it is set but corrupted.
    // --------------------
    // There are two ways we check if the access token has expired:
    //  - First, check if we know it has expired based on the expiration time.
    //  - Second, try to use it, and check for error 414,
    //    a unique error code that means the token has expired.
    $need_to_refresh = false;
    // Check if we need to refresh the access token
    if (time() >= $vbulletin->capture_session['capture_expires_in']) {
        $need_to_refresh = true;
    } else {
        $user_entity = get_entity($vbulletin->capture_session['capture_access_token']);
        if (isset($user_entity['code']) && $user_entity['code'] == '414') {
            $need_to_refresh = true;
        }
    }
    // If necessary, refresh the access token and try to fetch the entity again.
    if ($need_to_refresh) {
        if ($can_refresh) {
            refresh_access_token($vbulletin->capture_session['capture_refresh_token']);
            return load_user_entity(false);
        }
    }
    return $user_entity;
}