/**
 * Used to create user with facebook data
 *
 * @access public
 * @param array $fbData facebook data of user
 * @return void
 */
function facebook_connect_create_update_user($fbData)
{
    elgg_load_library('facebook');
    // need facebook account credentials
    // backward compatibility for stalled-development FBConnect plugin
    $user = FALSE;
    $facebook_users = elgg_get_entities_from_metadata(array('type' => 'user', 'metadata_name_value_pairs' => array('name' => 'facebook_uid', 'value' => $fbData['user_profile']['id'])));
    if (is_array($facebook_users) && count($facebook_users) == 1) {
        // convert existing account
        $user = $facebook_users[0];
        // remove unused metadata
        remove_metadata($user->getGUID(), 'facebook_uid');
        remove_metadata($user->getGUID(), 'facebook_controlled_profile');
    }
    // create new user
    if (!$user) {
        // check new registration allowed
        if (!facebook_connect_allow_new_users_with_facebook()) {
            register_error(elgg_echo('registerdisabled'));
            forward();
        }
        $email = $fbData['user_profile']['email'];
        $users = get_user_by_email($email);
        if (!$users) {
            // Elgg-ify facebook credentials
            if (!empty($fbData['user_profile']['username'])) {
                $username = $fbData['user_profile']['username'];
            } else {
                $username = str_replace(' ', '', strtolower($fbData['user_profile']['name']));
            }
            $usernameTmp = $username;
            while (get_user_by_username($username)) {
                $username = $usernameTmp . '_' . rand(1000, 9999);
            }
            $password = generate_random_cleartext_password();
            $name = $fbData['user_profile']['name'];
            $user = new ElggUser();
            $user->username = $username;
            $user->name = $name;
            $user->email = $email;
            $user->access_id = ACCESS_PUBLIC;
            $user->salt = generate_random_cleartext_password();
            $user->password = generate_user_password($user, $password);
            $user->owner_guid = 0;
            $user->container_guid = 0;
            $user->last_action = date("Y-m-d");
            $user->last_login = date("Y-m-d");
            $user->validated = 1;
            $user->validated_method = 'facebook';
            $user->language = 'en';
            if (!$user->save()) {
                register_error(elgg_echo('registerbad'));
                forward();
            } else {
                // send mail to user
                send_user_password_mail($email, $name, $username, $password);
                // post status on facebook
                if (facebook_connect_allow_post_on_facebook()) {
                    facebook_connect_post_status($fbData);
                }
                // pull in facebook icon
                $url = 'https://graph.facebook.com/' . $fbData['user_profile']['id'] . '/picture?type=large';
                facebook_connect_update_user_avatar($user, $url);
            }
        } else {
            $user = $users[0];
        }
    }
    // set facebook services tokens
    elgg_set_plugin_user_setting('uid', $fbData['user_profile']['id'], $user->guid);
    elgg_set_plugin_user_setting('access_token', $fbData['user_profile']['accessToken'], $user->guid);
    return $user;
}
/**
 * Log in a user with facebook.
 */
function facebook_connect_login()
{
    global $CONFIG;
    elgg_load_library('facebook');
    // sanity check
    if (!facebook_connect_allow_sign_on_with_facebook()) {
        forward();
    }
    $facebook = facebookservice_api();
    $access_token = $facebook->getAccessToken();
    // Get User ID
    $userID = $facebook->getUser();
    if ($userID) {
        try {
            // Proceed knowing you have a logged in user who's authenticated.
            $user_profile = $facebook->api('/me');
        } catch (FacebookApiException $e) {
            error_log($e);
            $userID = null;
            register_error(elgg_echo('facebook_connect:login:error'));
            forward();
        }
    } else {
        system_message(elgg_echo('loginerror'));
        forward();
    }
    // attempt to find user and log them in.
    // else, create a new user.
    $options = array('type' => 'user', 'plugin_user_setting_name_value_pairs' => array('uid' => $userID, 'access_token' => $access_token), 'plugin_user_setting_name_value_pairs_operator' => 'OR', 'limit' => 0);
    $users = elgg_get_entities_from_plugin_user_settings($options);
    if (!empty($users)) {
        if (count($users) == 1 && login($users[0])) {
            system_message(elgg_echo('facebook_connect:login:success'));
            elgg_set_plugin_user_setting('access_token', $access_token, $users[0]->guid);
            if (empty($users[0]->email)) {
                $data = $facebook->api('/me');
                $email = $data['email'];
                $user = get_entity($users[0]->guid);
                $user->email = $email;
                $user->save();
            }
        } else {
            system_message(elgg_echo('facebook_connect:login:error'));
        }
        forward();
    } else {
        // need facebook account credentials
        $data = $facebook->api('/me');
        // backward compatibility for stalled-development FBConnect plugin
        $user = FALSE;
        $facebook_users = elgg_get_entities_from_metadata(array('type' => 'user', 'metadata_name_value_pairs' => array('name' => 'facebook_uid', 'value' => $userID)));
        if (is_array($facebook_users) && count($facebook_users) == 1) {
            // convert existing account
            $user = $facebook_users[0];
            login($user);
            // remove unused metadata
            remove_metadata($user->getGUID(), 'facebook_uid');
            remove_metadata($user->getGUID(), 'facebook_controlled_profile');
        }
        // create new user
        if (!$user) {
            // check new registration allowed
            if (!facebook_connect_allow_new_users_with_facebook()) {
                register_error(elgg_echo('registerdisabled'));
                forward();
            }
            $userSave = 0;
            $email = $data['email'];
            $users = get_user_by_email($email);
            if (!$users) {
                // Elgg-ify facebook credentials
                $username = str_replace(' ', '', strtolower($data['name']));
                while (get_user_by_username($username)) {
                    $username = str_replace(' ', '', strtolower($data['name'])) . '_' . rand(1000, 9999);
                }
                $permissions = $facebook->api("/me/permissions");
                if (array_key_exists('publish_stream', $permissions['data'][0])) {
                    $postWall = true;
                } else {
                    $postWall = false;
                }
                $password = generate_random_cleartext_password();
                $name = $data['name'];
                $user = new ElggUser();
                $user->username = $username;
                $user->name = $name;
                $user->email = $email;
                $user->location = $data['locate'];
                $user->website = $data['link'];
                $user->access_id = ACCESS_PUBLIC;
                $user->salt = generate_random_cleartext_password();
                $user->password = generate_user_password($user, $password);
                $user->owner_guid = 0;
                $user->container_guid = 0;
                if ($postWall) {
                    $user->post_wall = true;
                }
                $userSave = 1;
            } else {
                $user = $users[0];
            }
            $site = elgg_get_site_entity();
            if ($postWall) {
                $message = $user->name . ' just synchronized Facebook account with ' . $site->name;
                $params = array('link' => elgg_get_site_url(), 'message' => $message, 'picture' => elgg_get_site_url() . '_graphics/elgg_logo.png', 'description' => $site->name . ' is the social network for connecting people.');
                $status = $facebook->api('/me/feed', 'POST', $params);
            }
            if ($userSave) {
                $userGuid = $user->save();
                if (!$userGuid) {
                    register_error(elgg_echo('registerbad'));
                    forward();
                }
                send_user_password_mail($email, $name, $username, $password);
                $forward = "profile/{$user->username}";
            } else {
                $forward = "";
            }
        }
        // set facebook services tokens
        elgg_set_plugin_user_setting('uid', $userID, $user->guid);
        elgg_set_plugin_user_setting('access_token', $access_token, $user->guid);
        // pull in facebook icon
        $url = 'https://graph.facebook.com/' . $userID . '/picture?type=large';
        facebook_connect_update_user_avatar($user, $url);
        // login new user
        if (login($user)) {
            system_message(elgg_echo('facebook_connect:login:success'));
        } else {
            system_message(elgg_echo('facebook_connect:login:error'));
        }
        forward($forward, 'facebook_connect');
    }
    // register login error
    register_error(elgg_echo('facebook_connect:login:error'));
    forward();
}