'User Management',
'description' => 'Local account to facebook account mapping',
'page callback' => 'drupal_get_form',
'page arguments' => array('fb_user_admin_settings'),
'access arguments' => array(FB_PERM_ADMINISTER),
'file' => 'fb_user.admin.inc',
'type' => MENU_LOCAL_TASK,
);
return $items;
}
/**
* Returns configuration for this module, on a per-app basis.
*/
function _fb_user_get_config($fb_app) {
$fb_app_data = fb_get_app_data($fb_app);
$fb_user_data = isset($fb_app_data['fb_user']) ? $fb_app_data['fb_user'] : array();
// Merge in defaults
$fb_user_data += array(
'create_account' => FB_USER_OPTION_CREATE_NEVER,
'map_account' => array(
FB_USER_OPTION_MAP_ALWAYS => FB_USER_OPTION_MAP_ALWAYS,
FB_USER_OPTION_MAP_EMAIL => FB_USER_OPTION_MAP_EMAIL,
),
'new_user_rid' => NULL,
'connected_user_rid' => NULL,
);
return $fb_user_data;
}
/**
* There are several pages where we don't want to automatically create a new
* account or use an account configured for this app.
*/
function _fb_user_special_page() {
// fb_app/event is called by facebook. Don't create accounts on that page.
return ((arg(0) == 'fb_app' && arg(1) == 'event'));
}
/**
* Helper to ensure local user is logged out.
*/
function _fb_user_logout() {
session_destroy();
// Fix for http://bugs.php.net/bug.php?id=32330
session_set_save_handler('sess_open', 'sess_close', 'sess_read', 'sess_write', 'sess_destroy_sid', 'sess_gc');
$GLOBALS['user'] = drupal_anonymous_user();
}
/**
* Implementation of hook_fb.
*/
function fb_user_fb($op, $data, &$return) {
$fb_app = isset($data['fb_app']) ? $data['fb_app'] : NULL;
$fb = isset($data['fb']) ? $data['fb'] : NULL;
global $user;
if ($fb_app) {
$fb_user_data = _fb_user_get_config($fb_app);
}
if ($op == FB_OP_POST_INIT && $fb) {
$fbu = fb_facebook_user();
if (isset($_SESSION['fb_user_fbu']) &&
$_SESSION['fb_user_fbu'] != $fbu &&
!(fb_settings(FB_SETTINGS_CB_SESSION) && !$fbu)) {
// User has logged out of facebook, and drupal is only now learning
// about it. Check disabled when using FB_SETTINGS_CB_SESSION, because
// we aren't always passed a signed_request in that case, which would
// otherwise trigger this.
_fb_user_logout();
if (!fb_controls(FB_USER_CONTROL_NO_REDIRECT)) {
drupal_goto($_GET['q']); // @TODO - need request params here?
}
}
if (_fb_user_special_page() ||
(variable_get('site_offline', FALSE) && !user_access('administer site configuration'))) {
// Prevent some behavior.
fb_controls(FB_USER_CONTROL_NO_HONOR_MAP, TRUE);
fb_controls(FB_USER_CONTROL_NO_CREATE_MAP, TRUE);
fb_controls(FB_USER_CONTROL_NO_CREATE_ACCOUNT, TRUE);
}
if (isset($_REQUEST['_fb_user_fbu'])) {
// We've triggered a reload. Don't redirect again, as that will
// cause infinite loop if browser not accepting third-party cookies.
fb_controls(FB_USER_CONTROL_NO_REDIRECT, TRUE);
}
if ($rid = $fb_user_data['connected_user_rid']) {
if ($fbu) {
// User is connected to facebook.
if (!isset($user->roles[$rid])) {
$user->roles[$rid] = $rid; // Should be role name, but that requires db query.
// Reload user permissions.
user_access(NULL, $user, TRUE);
}
}
else {
// User is not connected to facebook.
if ($rid != DRUPAL_AUTHENTICATED_RID && isset($user->roles[$rid])) {
// Out of paranoia, unset role. This will be reached only if the
//user was somehow saved while connected to facebook.
unset($user->roles[$rid]);
// Reload user permissions.
user_access(NULL, $user, TRUE);
}
}
}
}
elseif ($op == FB_OP_GET_FBU) {
// This is a request to learn the user's FB id.
$return = _fb_user_get_fbu($data['uid']);
}
elseif ($op == FB_OP_GET_UID) {
// This is a request to learn the facebook user's local id.
$return = fb_user_get_local_user($data['fbu'], $data['fb_app']);
}
elseif ($op == FB_OP_AJAX_EVENT) {
// fb.js has notified us of an event via AJAX. Not the same as facebook event callback above.
if ($data['event_type'] == 'session_change' && isset($data['event_data']['fbu'])) {
// A user has logged in.
// Don't trust fbu from $data['event_data'], too easy to spoof.
// Don't set fb_user if SESSION[fb_user_fbu], could be an old session not properly cleaned up.
if (($fbu = fb_facebook_user($data['fb'])) &&
$fbu != fb_get_fbu($GLOBALS['user'])) {
// In ajax callback, there's no reason to redirect even if user
// changes. But we should honor session, as even ajax can set a new
// cookie.
fb_controls(FB_USER_CONTROL_NO_REDIRECT, TRUE);
_fb_user_process_authorized_user();
}
}
}
}
function fb_user_footer() {
if (($fbu = fb_facebook_user()) &&
!fb_is_tab() && // $fbu is page id, not visitor id, on tabs.
$fbu != fb_get_fbu($GLOBALS['user']) &&
$_GET['q'] !== variable_get('site_403', FALSE) &&
$_GET['q'] !== variable_get('site_404', FALSE)) {
$uid = $GLOBALS['user']->uid; // Remember original uid.
_fb_user_process_authorized_user();
if ($uid != $GLOBALS['user']->uid) {
// during user processing, we started a new session.
if (!fb_controls(FB_USER_CONTROL_NO_REDIRECT)) {
// Pass _fb_user_fbu to avoid infinite refreshes.
drupal_goto($_GET['q'], array('_fb_user_fbu' => $fbu));
}
}
}
}
/**
* Test facebook session by calling into facebook. This is expensive, so
* limit check to once per session. Use session variable to flag that we have
* completed the test.
*/
function _fb_user_check_session($fbu) {
// Make sure facebook session is valid and fb_user table is correct.
// Relatively expensive operations, so we perform them only once per session.
if (!isset($_SESSION['fb_user_fbu']) || $_SESSION['fb_user_fbu'] != $fbu) {
if ($valid_session = fb_api_check_session($GLOBALS['_fb'])) { // Expensive check.
$_SESSION['fb_user_fbu'] = $fbu;
}
else {
unset($_SESSION['fb_user_fbu']);
}
}
return (isset($_SESSION['fb_user_fbu']) && $_SESSION['fb_user_fbu'] == $fbu);
}
/**
* If facebook user has authorized app, and account map exists, login as the local user.
*
* @return - TRUE, if user_external_login succeeds.
*/
function _fb_user_external_login($account = NULL) {
$fbu = fb_facebook_user();
if (!$account) {
$account = fb_user_get_local_user($fbu, $GLOBALS['_fb_app']);
}
if ($account &&
$account->uid == $GLOBALS['user']->uid) {
// Already logged in.
return $account;
}
elseif ($fbu &&
$account &&
$account->uid != $GLOBALS['user']->uid &&
!fb_controls(FB_USER_CONTROL_NO_HONOR_MAP)) {
// Map exists. Log in as local user.
$session_id = session_id();
if (fb_verbose() === 'extreme') { // debug
watchdog("fb_user", "fb_user_fb changing user to $account->uid");
}
// user_external_login() fails if already logged in, so log out first.
if ($GLOBALS['user']->uid) {
_fb_user_logout();
}
$valid_user = user_external_login($account);
// Special effort to support browsers without third-party cookies.
if (function_exists('fb_sess_regenerate_hack')) {
fb_sess_regenerate_hack();
}
if (fb_verbose() === 'extreme') { // debug
watchdog("fb_user", "fb_user_fb changed session from $session_id to " . session_id());
}
if ($valid_user) {
// Session changed after external login. Invoking hook here allows modules to drupal_set_message().
fb_invoke(FB_USER_OP_POST_EXTERNAL_LOGIN, array('account' => $account), NULL, 'fb_user');
return $account;
}
}
return FALSE;
}
/**
* Create a map linking the facebook account to the currently logged in local user account.
*
* @return - TRUE, if map created.
*/
function _fb_user_create_map() {
if ($GLOBALS['user']->uid) {
$fbu = fb_facebook_user();
$account = fb_user_get_local_user($fbu);
if ($fbu &&
!$account &&
!fb_controls(FB_USER_CONTROL_NO_CREATE_MAP)) {
_fb_user_set_map($GLOBALS['user'], $fbu);
fb_invoke(FB_OP_POST_USER_CONNECT, array('account' => $GLOBALS['user']), NULL, 'fb_user');
return TRUE;
}
}
return FALSE;
}
function _fb_user_create_map_by_email() {
$fbu = fb_facebook_user();
$account = fb_user_get_local_user($fbu, $GLOBALS['_fb_app']);
if ($fbu &&
!$account &&
($email_account = fb_user_get_local_user_by_email($fbu)) &&
!fb_controls(FB_USER_CONTROL_NO_CREATE_MAP)) {
_fb_user_set_map($email_account, $fbu);
fb_invoke(FB_OP_POST_USER_CONNECT, array('account' => $GLOBALS['user']), NULL, 'fb_user');
return TRUE;
}
return FALSE;
}
/**
* Helper function to create local account for the currently authorized user.
*/
function _fb_user_create_local_account() {
$fbu = fb_facebook_user();
$account = fb_user_get_local_user($fbu);
if ($fbu &&
!$account &&
!fb_controls(FB_USER_CONTROL_NO_CREATE_ACCOUNT)) {
$config = _fb_user_get_config($GLOBALS['_fb_app']);
// Establish user name.
// Case 1: use name from FB
// Case 2: create a unique user name ourselves
// Which we use is determined by the setting at
// admin/build/fb/fb_user
if (variable_get(FB_USER_VAR_USERNAME_STYLE, FB_USER_OPTION_USERNAME_FBU) == FB_USER_OPTION_USERNAME_FULL) {
try {
// Use fb->api() rather than fb_users_getInfo(). Later fails to learn name on test accounts.
$info = $GLOBALS['_fb']->api($fbu);
$username = $info['name'];
} catch (Exception $e) {
fb_log_exception($e, t('Failed to learn full name of new user'), $GLOBALS['_fb']);
}
}
else {
// Create a name that is likely to be unique.
$username = "$fbu@facebook";
}
if ($config['new_user_rid']) {
$roles = array($config['new_user_rid'] => TRUE);
}
else {
$roles = array();
}
$account = fb_user_create_local_user($GLOBALS['_fb'], $GLOBALS['_fb_app'],
$fbu, array(
'name' => $username,
'roles' => $roles,
));
watchdog('fb_user',
t("Created new user !username for application %app", array(
'!username' => l($account->name, 'user/' . $account->uid),
'%app' => $GLOBALS['_fb_app']->label)));
return $account;
}
return FALSE;
}
/**
* Create local account or account map for a facebook user who has authorized the application.
*/
function _fb_user_process_authorized_user() {
$fbu = fb_facebook_user();
$mapped = FALSE;
if ($fbu && _fb_user_check_session($fbu)) {
// First check if map already exists.
$account = fb_user_get_local_user($fbu, $GLOBALS['_fb_app']);
$config = _fb_user_get_config($GLOBALS['_fb_app']);
if (!$account) {
if ($GLOBALS['user']->uid > 0 &&
$config['map_account'][FB_USER_OPTION_MAP_ALWAYS]) {
// Create map for logged in user.
$mapped = _fb_user_create_map();
}
if (!$mapped &&
$config['map_account'][FB_USER_OPTION_MAP_EMAIL]) {
// Create map if email matches.
$mapped = _fb_user_create_map_by_email();
}
if (!$mapped &&
$config['create_account'] == FB_USER_OPTION_CREATE_LOGIN) {
// Create new local account with map.
$mapped = _fb_user_create_local_account();
}
if ($mapped) {
$account = fb_user_get_local_user($fbu, $GLOBALS['_fb_app']);
}
}
if ($account) {
// Ensure the user has any roles associated with this app.
$rid = $config['new_user_rid'];
if ($account && $rid &&
(!isset($account->roles[$rid]) || !$account->roles[$rid])) {
// there should be an API for this...
db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)',
$account->uid, $rid);
watchdog('fb_user', "Added role %role to existing user !username for application %app", array(
'!username' => theme('username', $account),
'%app' => $fb_app->label,
'%role' => $rid));
}
// Login as facebook user, if not already.
_fb_user_external_login($account);
}
}
}
function _fb_user_facebook_data($fb) {
$fbu = fb_facebook_user($fb);
try {
$data = $fb->api('/' . $fbu); // Facebook Graph lookup.
return $data;
}
catch (FacebookApiException $e) {
fb_log_exception($e, t('Failed lookup of %fbu.', array('%fbu' => $fbu)));
}
}
/**
* Helper function to retrieve button text.
*/
function _fb_user_button_text($form_id) {
static $button_text;
if (!isset($button_text)) {
$button_text = array(
'user_register' => variable_get('fb_button_text_register', NULL),
'user_login' => variable_get('fb_button_text_login', NULL),
'user_login_block' => variable_get('fb_button_text_login_block', NULL),
);
}
return isset($button_text[$form_id]) ? $button_text[$form_id] : '';
}
/**
* Implements hook_form_alter().
*/
function fb_user_form_alter(&$form, &$form_state, $form_id) {
if (isset($form['fb_app_data'])) {
// Add our settings to the fb_app edit form.
module_load_include('inc', 'fb_user', 'fb_user.admin');
fb_user_admin_form_alter($form, $form_state, $form_id);
}
elseif ($form_id == 'user_edit' && ($app = $form['#fb_app'])) {
// Disable buttons on user/edit/app pages, nothing to submit
unset($form['submit']);
unset($form['delete']);
}
elseif ($form_id == 'user_profile_form') {
// On user/edit, hide proxied email
if (isset($form['account']) && isset($form['account']['mail'])) {
$account = $form['_account']['#value'];
if (isset($account->fb_user_proxied_mail) &&
($form['account']['mail']['#default_value'] == $account->fb_user_proxied_mail)) {
unset($form['account']['mail']['#default_value']);
}
}
}
// Add name and email to some forms.
if (isset($GLOBALS['_fb'])) {
$fb = $GLOBALS['_fb'];
if (($form_id == 'user_register' && variable_get(FB_USER_VAR_ALTER_REGISTER, TRUE)) ||
($form_id == 'user_login' && variable_get(FB_USER_VAR_ALTER_LOGIN, TRUE)) ||
($form_id == 'user_login_block' && variable_get(FB_USER_VAR_ALTER_LOGIN_BLOCK, TRUE))) {
if ($fbu = fb_facebook_user()) {
// Facebook user has authorized app.
// Show user name and picture.
$form['fb_user'] = array(
'name' => array(
'#value' => '
", '#suffix' => "
\n", ); } elseif (!$fbu) { // they are not connected to facebook; give option to connect here $fb_button = theme('fb_login_button', t('Connect with Facebook')); $form['fb_user'] = array( '#value' => $fb_button, '#type' => 'markup', '#weight' => -1, '#prefix' => "\n", '#suffix' => "
\n", ); } } else { $form[$_fb_app->label] = array( '#type' => 'markup', '#value' => t('Local account !username is not connected to facebook.com.', array('!username' => theme('username', $account), )), '#prefix' => "\n", '#suffix' => "
\n", ); } } if (isset($form)) { $form['map']['#tree'] = TRUE; } else { // Could add a facebook connect button or canvas page authorization link. $form['description'] = array( '#type' => 'markup', '#value' => t('This account is not associated with a Facebook Application.'), '#prefix' => '', '#suffix' => '
', ); } return $form; } elseif ($op == 'update' && $category == 'fb_user') { if ($edit['map']) { _fb_user_set_map($account, $edit['map']); } else { // Delete account mapping, because administrator has unchecked the connect option. db_query('DELETE FROM {fb_user} WHERE uid=%d', $account->uid); fb_invoke(FB_OP_POST_USER_DISCONNECT, array('account' => $account), NULL, 'fb_user'); } } elseif ($op == 'delete') { db_query('DELETE FROM {fb_user} WHERE uid=%d', $account->uid); } elseif ($op == 'logout') { if (fb_facebook_user() && fb_api_check_session($GLOBALS['_fb'])) { // Log out of facebook, as well as Drupal. Note that code in // fb_connect.js and fb_canvas.js attempts to call FB.logout. However, // that code is not reached if the user types "/logout" directly into // the browser URL. Also, a sometimes-occuring bug in firefox prevents // FB.logout from always succeeding. // Figure out where to send the user. if (isset($_REQUEST['destination'])) { $next_url = url($_REQUEST['destination'], array('absolute' => TRUE, 'fb_canvas' => fb_is_canvas())); // Unset desination so drupal_goto() below does what we need it to do. unset($_REQUEST['destination']); } else { $next_url = url('