/**
*  Grab the user profile from social network
*/
function wsl_process_login_request_user_social_profile($provider)
{
    $adapter = null;
    $config = null;
    $hybridauth_user_profile = null;
    try {
        // get idp adapter
        $adapter = wsl_process_login_get_provider_adapter($provider);
        $config = $adapter->config;
        // if user authenticated successfully with social network
        if ($adapter->isUserConnected()) {
            // grab user profile via hybridauth api
            $hybridauth_user_profile = $adapter->getUserProfile();
        } else {
            return wsl_process_login_render_notice_page(sprintf(_wsl__("Sorry, we couldn't connect you with <b>%s</b>. <a href=\"%s\">Please try again</a>.", 'wordpress-social-login'), $provider, site_url('wp-login.php', 'login_post')));
        }
    } catch (Exception $e) {
        return wsl_process_login_render_error_page($e, $config, $provider, $adapter);
    }
    return $hybridauth_user_profile;
}
function wsl_process_login_auth()
{
    $assets_base_url = WORDPRESS_SOCIAL_LOGIN_PLUGIN_URL . '/assets/img/';
    // let display a loading message. should be better than a white screen
    if (isset($_REQUEST["provider"]) && !isset($_REQUEST["redirect_to_provider"])) {
        wsl_process_login_render_loading_page();
    }
    // if user select a provider to login with
    // and redirect_to_provider eq ture
    if (!(isset($_REQUEST["provider"]) && isset($_REQUEST["redirect_to_provider"]))) {
        wsl_render_notices_pages(_wsl__("Bouncer says this makes no sense.", 'wordpress-social-login'));
        return false;
    }
    try {
        // Bouncer :: Accounts Linking is enabled
        if (get_option('wsl_settings_bouncer_linking_accounts_enabled') != 1 && isset($_REQUEST["link"])) {
            wp_die(_wsl__("Bouncer say you are doin it wrong.", 'wordpress-social-login'));
        }
        if (!isset($_REQUEST["link"]) && is_user_logged_in()) {
            global $current_user;
            get_currentuserinfo();
            wp_die(sprintf(_wsl__("You are already logged in as <b>%</b>.", 'wordpress-social-login'), $current_user->display_name));
        }
        # Hybrid_Auth already used?
        if (class_exists('Hybrid_Auth', false)) {
            return wsl_render_notices_pages(_wsl__("Error: Another plugin seems to be using HybridAuth Library and made WordPress Social Login unusable. We recommand to find this plugin and to kill it with fire!", 'wordpress-social-login'));
        }
        // load hybridauth
        require_once WORDPRESS_SOCIAL_LOGIN_ABS_PATH . "/hybridauth/Hybrid/Auth.php";
        // selected provider name
        $provider = @trim(strip_tags($_REQUEST["provider"]));
        // build required configuratoin for this provider
        if (!get_option('wsl_settings_' . $provider . '_enabled')) {
            throw new Exception(_wsl__('Unknown or disabled provider', 'wordpress-social-login'));
        }
        // default endpoint_url/callback_url
        $endpoint_url = WORDPRESS_SOCIAL_LOGIN_HYBRIDAUTH_ENDPOINT_URL;
        $callback_url = null;
        // autogenerated by hybridauth
        // overwrite endpoint_url if need'd
        if (get_option('wsl_settings_base_url')) {
            $endpoint_url = '';
            // fixme!
            $callback_url = '';
            // fixme!
        }
        // check hybridauth_base_url
        if (!strstr($endpoint_url, "http://") && !strstr($endpoint_url, "https://")) {
            throw new Exception('Invalid base_url: ' . $endpoint_url, 9);
        }
        $config = array();
        $config["base_url"] = $endpoint_url;
        $config["providers"] = array();
        $config["providers"][$provider] = array();
        $config["providers"][$provider]["enabled"] = true;
        // provider application id ?
        if (get_option('wsl_settings_' . $provider . '_app_id')) {
            $config["providers"][$provider]["keys"]["id"] = get_option('wsl_settings_' . $provider . '_app_id');
        }
        // provider application key ?
        if (get_option('wsl_settings_' . $provider . '_app_key')) {
            $config["providers"][$provider]["keys"]["key"] = get_option('wsl_settings_' . $provider . '_app_key');
        }
        // provider application secret ?
        if (get_option('wsl_settings_' . $provider . '_app_secret')) {
            $config["providers"][$provider]["keys"]["secret"] = get_option('wsl_settings_' . $provider . '_app_secret');
        }
        // reset scope for if facebook
        if (strtolower($provider) == "facebook") {
            $config["providers"][$provider]["scope"] = "email, user_about_me, user_birthday, user_hometown, user_website";
            $config["providers"][$provider]["display"] = "popup";
        }
        // reset scope for if google
        if (strtolower($provider) == "google") {
            $config["providers"][$provider]["scope"] = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email";
        }
        // Contacts import
        if (get_option('wsl_settings_contacts_import_facebook') == 1 && strtolower($provider) == "facebook") {
            $config["providers"][$provider]["scope"] = "email, user_about_me, user_birthday, user_hometown, user_website, read_friendlists";
        }
        if (get_option('wsl_settings_contacts_import_google') == 1 && strtolower($provider) == "google") {
            $config["providers"][$provider]["scope"] = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.google.com/m8/feeds/";
        }
        // create an instance for Hybridauth
        $hybridauth = new Hybrid_Auth($config);
        // try to authenticate the selected $provider
        $params = array();
        // if callback_url defined, overwrite Hybrid_Auth::getCurrentUrl();
        if ($callback_url) {
            $params["hauth_return_to"] = $callback_url;
        }
        $adapter = $hybridauth->authenticate($provider, $params);
        // further testing
        if (get_option('wsl_settings_development_mode_enabled')) {
            $profile = $adapter->getUserProfile($provider);
        }
        if (get_option('wsl_settings_use_popup') == 1 || !get_option('wsl_settings_use_popup')) {
            ?>
				<html><head><script>
				function init() {
					window.opener.wsl_wordpress_social_login({
						'action'   : 'wordpress_social_login',
						'provider' : '<?php 
            echo $provider;
            ?>
'
					});

					window.close()
				}
				</script></head><body onload="init();"></body></html>
			<?php 
        } elseif (get_option('wsl_settings_use_popup') == 2) {
            $redirect_to = site_url();
            if (isset($_REQUEST['redirect_to'])) {
                $redirect_to = urldecode($_REQUEST['redirect_to']);
            }
            ?>
				<html><head><script>
				function init() { document.loginform.submit() }
				</script></head><body onload="init();">
				<form name="loginform" method="post" action="<?php 
            echo site_url('wp-login.php', 'login_post');
            ?>
">
					<input type="hidden" id="redirect_to" name="redirect_to" value="<?php 
            echo $redirect_to;
            ?>
"> 
					<input type="hidden" id="provider" name="provider" value="<?php 
            echo $provider;
            ?>
"> 
				<?php 
            if (isset($_REQUEST["link"]) && (int) $_REQUEST["link"]) {
                ?>
					<input type="hidden" id="action" name="action" value="wordpress_social_link">
				<?php 
            } else {
                ?>
					<input type="hidden" id="action" name="action" value="wordpress_social_login">
				<?php 
            }
            ?>
				</form></body></html> 
			<?php 
        }
    } catch (Exception $e) {
        wsl_process_login_render_error_page($e, $config, $hybridauth, $adapter, $profile);
    }
    die;
}